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.
Code
-- 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-levelWHEREwill 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- Which tables does the SQL touch?
- The references are `request_log`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.