11 / 17 · Structuring Queries
Window functions
Keep one result row per sale while computing a product total, a rank or the value on a neighbouring row.
On this page 4
The shop wants a table with each sale, its amount and the total for its product. A grouping query gives the total and collapses the sales. A second query could join that total back to each sale. A window function expresses the calculation on related rows while keeping each sale in the result.
Give every row its product total#
The example uses a new set of seven sales. Run the setup once in a fresh session. One row is one sale, sold_on records its date, and cents is its full amount. Two tea sales share a date, and two tea sales share an amount.
CREATE TEMP TABLE sales (
sale_id integer PRIMARY KEY,
product text NOT NULL,
sold_on date NOT NULL,
cents integer NOT NULL
);
INSERT INTO sales VALUES
(201, 'tea', DATE '2026-01-01', 100),
(202, 'tea', DATE '2026-01-02', 200),
(203, 'tea', DATE '2026-01-02', 300),
(204, 'tea', DATE '2026-01-05', 300),
(205, 'tea', DATE '2026-01-06', 500),
(206, 'coffee', DATE '2026-01-01', 300),
(207, 'coffee', DATE '2026-01-05', 300);
SELECT sale_id, product, cents,
SUM(cents) OVER (PARTITION BY product) AS product_total
FROM sales
ORDER BY sale_id;
The OVER clause turns the aggregate into a window function. PARTITION BY product divides the input rows into groups of related rows called partitions. Here the aggregate can use the entire partition of each row. For tea the sum is . For coffee it is . The five tea rows each carry 1400 in the new column, and the two coffee rows each carry 600. The result still has seven rows. With GROUP BY product, it would have two. (PostgreSQL 18, §3.5, SQLite, §§1–2.1)
A partition gives each sale its context
A product total is repeated context for each sale. Adding it over all seven output rows gives , which counts the same totals several times. Adding the individual amounts gives 2000. The row still describes a sale after the window calculation.
Put related rows in order#
The shop wants the two largest sales for each product. ORDER BY inside OVER sets the order used for the calculation. The final ORDER BY sets the display order. These are separate choices. (PostgreSQL 18, §3.5, SQLite, §2)
SELECT sale_id, product, cents,
ROW_NUMBER() OVER (
PARTITION BY product ORDER BY cents DESC, sale_id
) AS position,
RANK() OVER (PARTITION BY product ORDER BY cents DESC) AS rank,
DENSE_RANK() OVER (PARTITION BY product ORDER BY cents DESC) AS dense_rank
FROM sales
ORDER BY product, position;
For tea, descending amount puts the 500-cent sale first. Both 300-cent sales have equal amount. Rows equal on all window sort keys are peers. A unique sale ID breaks the tie for ROW_NUMBER(), which assigns distinct positions. The other two functions use amount alone, so the 300-cent sales are peers for them.
| Tea sale ID | Cents | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| 205 | 500 | 1 | 1 | 1 |
| 203 | 300 | 2 | 2 | 2 |
| 204 | 300 | 3 | 2 | 2 |
| 202 | 200 | 4 | 4 | 3 |
| 201 | 100 | 5 | 5 | 4 |
RANK gives the position where the peer group starts. The two rows at rank 2 occupy positions 2 and 3, so the next rank is 4. DENSE_RANK counts peer groups, so its next value is 3. If the rule is at most two sales per product, use row numbers with a tie-breaker. If the rule is to include all ties at the second position, use ranks based on amount alone. Adding the ID to the ranking order would dissolve those peers. (PostgreSQL 18, §9.22)
Read a neighbour#
For a chronological comparison, order by the sale date and then by sale ID. The second key fixes an order within each date in this toy dataset. LAG reads a value from the preceding row, and LEAD reads from the following row. Both default to an offset of one and return NULL when the requested row lies outside the partition. The WINDOW clause gives the shared definition a name. (PostgreSQL 18, §9.22, DuckDB 1.4, Window Functions)
SELECT sale_id, cents,
LAG(cents) OVER by_time AS previous_cents,
LEAD(cents) OVER by_time AS next_cents
FROM sales
WHERE product = 'tea'
WINDOW by_time AS (ORDER BY sold_on, sale_id)
ORDER BY sold_on, sale_id;
For tea sale 203, the preceding amount is 200 from sale 202 and the following amount is 300 from sale 204. Sale 201 has no preceding row. Sale 205 has no following row. A difference such as cents - LAG(cents) OVER by_time compares consecutive sales in this order. It does not compare consecutive calendar dates. Two sales can share a date, and some dates can have no sales at all.
Filter after calculating#
PostgreSQL evaluates window functions over the rows that reach them after WHERE, grouping and HAVING. A condition in the same statement’s WHERE cannot use a window result. Put the calculation in a CTE or a subquery, and filter its output. (PostgreSQL 18, §3.5)
WITH ranked AS (
SELECT sale_id, product, cents,
ROW_NUMBER() OVER (
PARTITION BY product ORDER BY cents DESC, sale_id
) AS position
FROM sales
)
SELECT sale_id, product, cents
FROM ranked
WHERE position <= 2
ORDER BY product, position;
The query retains coffee sales 206 and 207 and tea sales 205 and 203. Moving a filter on cents into the CTE changes which rows compete for those positions. In DuckDB 1.4, QUALIFY can filter a window result within the same query. The CTE above uses PostgreSQL syntax. (DuckDB 1.4, Window Functions)
Next#
An ordered window gives each row a place within its partition. A running total or a moving average also needs a rule for which neighbours contribute to the current value. Window frames specify those bounds.
References#
- PostgreSQL Global Development Group. PostgreSQL 18 documentation. Window Functions, §3.5, and Window Functions Reference, §9.22. Defines partitions, order, peer ranks and offsets.
- SQLite Project. Window Functions, §§1–3. Shows that aggregate window functions preserve row count and distinguishes window order from display order.
- DuckDB Foundation. Window Functions, DuckDB 1.4. Documents named windows, offsets and the engine’s
QUALIFYextension.