Named Window Clause Reuse
Name a window once in a WINDOW clause and reuse it with OVER w, appending frame clauses without repeating partition and order definitions.
Code
-- WINDOW 子句给分区与排序命名:多个窗口函数复用同一窗口,改一处全局生效
-- 引用命名窗口时只能追加帧子句,不能再写 PARTITION BY / ORDER BY
SELECT
endpoint,
occurred_at,
latency_ms,
ROW_NUMBER() OVER w AS seq,
LAG(latency_ms) OVER w AS prev_latency,
latency_ms - LAG(latency_ms) OVER w AS delta_ms,
AVG(latency_ms) OVER (w ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_avg,
-- 同一查询可以定义多个命名窗口
RANK() OVER w2 AS latency_rank
FROM request_log
WINDOW w AS (PARTITION BY endpoint ORDER BY occurred_at),
w2 AS (PARTITION BY endpoint ORDER BY latency_ms DESC)
ORDER BY endpoint, occurred_at;How it works
The statement is SELECT, touching request_log.
The pieces that do the work: AVG 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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `request_log` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.