RANGE Interval Window Frames

Aggregate time-ordered rows over a sliding RANGE frame with INTERVAL offset, where peer rows sharing a timestamp enter the frame together.

SqlData Fetching

Code

snippet
-- RANGE 帧按排序键的区间划窗,而不是按行数:同时间戳的 peer 行一起进窗
-- 时间列排序 + INTERVAL 偏移 = "最近 N 分钟"的滑动统计(PostgreSQL 11+)
SELECT
  endpoint,
  occurred_at,
  COUNT(*) OVER (
    PARTITION BY endpoint
    ORDER BY occurred_at
    RANGE BETWEEN INTERVAL '5 minutes' PRECEDING AND CURRENT ROW
  ) AS errors_last_5m,
  -- 窗口起点随行移动:便于核对帧的实际覆盖范围
  MIN(occurred_at) OVER (
    PARTITION BY endpoint
    ORDER BY occurred_at
    RANGE BETWEEN INTERVAL '5 minutes' PRECEDING AND CURRENT ROW
  ) AS frame_start
FROM request_log
WHERE status_code >= 500
ORDER BY endpoint, occurred_at;

Inside the snippet

What runs is SELECT, with request_log as the object involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; COUNT, MIN aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

The request_log table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `request_log`.