Window functions
- Version
- 19
- Since
- 8.4
- Review
- Draft
Summary#
A window function calculates over rows related to the current row without collapsing them. PARTITION BY splits the rows and the window ORDER BY sequences each partition.
Syntax#
function_name(arguments) OVER (
[PARTITION BY partition_column]
[ORDER BY sort_column]
[frame_clause]
)
lag(value) IGNORE NULLS OVER window_name
WINDOW window_name AS (PARTITION BY partition_column ORDER BY sort_column)
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE readings (
sensor text NOT NULL,
step integer NOT NULL,
value integer,
PRIMARY KEY (sensor, step)
);
INSERT INTO readings VALUES
('a', 1, 10), ('a', 2, NULL), ('a', 3, 16),
('b', 1, 7), ('b', 2, 9);
SELECT sensor, step, value,
row_number() OVER w AS row_no,
sum(value) OVER w AS running_sum,
lag(value) OVER w AS previous,
lag(value) IGNORE NULLS OVER w AS previous_known
FROM readings
WINDOW w AS (PARTITION BY sensor ORDER BY step)
ORDER BY sensor, step;
-- Rank in a subquery, then filter on the result outside it.
SELECT sensor, step, value
FROM (
SELECT sensor, step, value,
rank() OVER (PARTITION BY sensor ORDER BY value DESC NULLS LAST) AS place
FROM readings
) AS ranked
WHERE place = 1
ORDER BY sensor;
ROLLBACK;
Expected output#
sensor|step|value|row_no|running_sum|previous|previous_known
a|1|10|1|10|NULL|NULL
a|2|NULL|2|10|10|10
a|3|16|3|26|NULL|10
b|1|7|1|7|NULL|NULL
b|2|9|2|16|7|7
(5 rows)
sensor|step|value
a|3|16
b|2|9
(2 rows)
Common mistakes#
With a window ORDER BY, the default frame ends at the last row tied with the current row. This makes sum a running total and makes last_value stop at that peer instead of the end of the partition. Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to include the whole partition. Filter a window result in an outer query.
Version applicability#
PostgreSQL 8.4 added window functions. The IGNORE NULLS and RESPECT NULLS options for lead, lag, first_value, last_value and nth_value are new in PostgreSQL 19, so the first query in the example fails on earlier versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0