Overview

A window function computes a value for each row using a set of related rows (its window) without collapsing rows the way GROUP BY does. They are the main tool for running totals, rankings, period-over-period comparisons and de-duplication.

Core concepts

func(args) OVER (
  PARTITION BY ...        -- independent groups
  ORDER BY ...            -- order inside each partition
  ROWS | RANGE | GROUPS BETWEEN ... AND ...   -- frame
)
  • Ranking: ROW_NUMBER() (unique), RANK() (ties share rank, gaps), DENSE_RANK() (ties, no gaps), NTILE(n).
  • Offset: LAG(x, n), LEAD(x, n), FIRST_VALUE, LAST_VALUE, NTH_VALUE.
  • Aggregates as windows: SUM(x) OVER (...), AVG, COUNT.
  • Frame: with ORDER BY and no explicit frame the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. ROWS counts physical rows, RANGE includes all peers (rows with the same sort value).

Worked example

Verified on PostgreSQL 17 with the orders data from sql-joins:

SELECT id, customer_id, amount,
       sum(amount) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS running,
       rank()      OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rk,
       lag(amount) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS prev
FROM orders
ORDER BY customer_id, ordered_at;

For customer 1 (orders of 100, 50, 80) the running totals are 100, 150, 230, the ranks by amount are 1, 3, 2, and prev is NULL, 100, 50.

ROWS versus RANGE with ties, over amounts 10, 10, 20:

SELECT id, amount,
  sum(amount) OVER (ORDER BY amount RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS r_range,
  sum(amount) OVER (ORDER BY amount ROWS  BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS r_rows
FROM (VALUES (1,10),(2,10),(3,20)) t(id, amount);

gives r_range = 20, 20, 40 (both tied rows are peers) and r_rows = 10, 20, 40.

Latest row per group (de-duplication):

SELECT * FROM (
  SELECT o.*, row_number() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC) AS rn
  FROM orders o
) x WHERE rn = 1;

How it works (internals)

The engine sorts (or uses an index to read in order) by partition then order keys, then streams through rows maintaining the frame. One sort can serve several window functions with the same PARTITION BY/ORDER BY, so group such functions together.

Pitfalls and production notes

  • Window functions are evaluated after WHERE/GROUP BY/HAVING, so you cannot filter on them directly; wrap in a subquery or CTE (sql-ctes-recursion).
  • LAST_VALUE with the default frame returns the current row; extend the frame to UNBOUNDED FOLLOWING.
  • A partition of millions of rows can spill to disk when sorting; index (partition cols, order cols) to avoid it (indexing-theory).
  • Always give a deterministic ORDER BY (add a unique tie-breaker) for ROW_NUMBER.

Practice questions

  1. Compute month-over-month revenue growth with LAG.
  2. Why does RANK() skip numbers after a tie and DENSE_RANK() not?
  3. Write the median of amount per customer using a window function or an ordered-set aggregate.

References

sql-aggregation · sql-ctes-recursion · sql-joins