Window Frame RANGE Groups NULL Peers Together
Compare ROWS and RANGE frames when ORDER BY contains NULL values: RANGE treats all NULL rows as peers while ROWS steps row by row.
Code
CREATE TEMP TABLE player_scores (
player text PRIMARY KEY,
points integer
);
INSERT INTO player_scores VALUES
('ada', 10),
('ben', 20),
('cyd', NULL),
('dan', NULL);
SELECT
player,
points,
-- ROWS steps one row at a time even across equal or NULL sort keys
COUNT(*) OVER (
ORDER BY points ASC NULLS LAST
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS rows_running_count,
-- RANGE groups all NULL rows as peers, so cyd and dan jump together
COUNT(*) OVER (
ORDER BY points ASC NULLS LAST
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS range_running_count,
-- Numeric RANGE offsets match NULL only against other NULL peers
COUNT(*) OVER (
ORDER BY points ASC NULLS LAST
RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING
) AS range_window_peers
FROM player_scores
ORDER BY points ASC NULLS LAST, player;What the code does
What runs here is SELECT / INSERT / CREATE — player_scores are the objects involved.
player_scores initializes temporary scratch schema structures scoped tightly to this database session so external fixtures are skipped and objects drop at close.
Clause by clause, expect: COUNT aggregation; a window function (OVER (…)) calculating row-level analytics across partitions without merging rows; an ORDER BY that fixes the output order; a PRIMARY KEY that enforces row identity.
Points of care
- Window functions are evaluated after
WHEREandGROUP BY— their output is not visible to a same-levelWHERE.
Applying it
The file sets up its own scratch surface: it builds the session-local tables it works with (player_scores), so one full run against a throwaway database is enough.
Statements that matter
INSERT INTO player_scores VALUES
('ada', 10),
('ben', 20),
('cyd', NULL),
('dan', NULL);
CREATE TEMP TABLE player_scores (
player text PRIMARY KEY,
points integer
);
Interactive Tools for This Topic
FAQ
- Which relations are involved here?
- The references are `player_scores`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.