Window functions
Overview
Aggregates with GROUP BY answer “what’s the total per customer?” — but they throw away the individual rows. Often you need both at once: each order, next to its customer’s total; each product, next to its category’s average; each month’s revenue, as a share of the year. Window functions do exactly this. They calculate over a group of related rows — the window — and attach the result to every row, without collapsing anything.
They’re one of the most powerful features in SQL, and a favourite topic in data-analyst interviews.
GROUP BY versus OVER
Start with a familiar aggregate — the average product price — but add OVER () after it:
SELECT name, price,
round(avg(price) OVER (), 2) AS avg_price
FROM products
WHERE category_id = 1; name | price | avg_price
-----------------------+-------+-----------
Ethiopian Yirgacheffe | 14.50 | 12.58
Colombian Supremo | 12.00 | 12.58
Decaf House Blend | 11.25 | 12.58
(3 rows)Three rows in, three rows out. avg(price) OVER () computed the average over the window — here (), meaning all the rows of the result — and wrote it on every row. With GROUP BY you’d have got one row; with OVER you keep every row and get the aggregate.
Note that the window is the rows after WHERE: the average is over the three coffees, not all twelve products.
PARTITION BY: one window per group
PARTITION BY splits the rows into separate windows, much like GROUP BY splits them into groups — except the rows stay:
SELECT name, category_id, price,
round(avg(price) OVER (PARTITION BY category_id), 2) AS category_avg,
count(*) OVER (PARTITION BY category_id) AS in_category
FROM products
WHERE category_id IS NOT NULL
ORDER BY category_id, price DESC; name | category_id | price | category_avg | in_category
------------------------+-------------+-------+--------------+-------------
Ethiopian Yirgacheffe | 1 | 14.50 | 12.58 | 3
Colombian Supremo | 1 | 12.00 | 12.58 | 3
Decaf House Blend | 1 | 11.25 | 12.58 | 3
Darjeeling First Flush | 2 | 18.00 | 12.06 | 4
Jasmine Green | 2 | 12.75 | 12.06 | 4
Assam Breakfast | 2 | 9.50 | 12.06 | 4
Chamomile Calm | 2 | 8.00 | 12.06 | 4
Burr Grinder | 3 | 89.00 | 51.23 | 4
Electric Kettle | 3 | 59.90 | 51.23 | 4
Glass Teapot | 3 | 32.00 | 51.23 | 4
Pour-Over Dripper | 3 | 24.00 | 51.23 | 4
(11 rows)Each product sits next to its own category’s average and size. Now comparisons are easy — which products are above their category average? You did that in the last chapter with a correlated subquery; with a window function it’s one expression.
Any aggregate becomes a window function by adding OVER: sum, avg, count, min, max, string_agg, even bool_and. You can also put several window functions with different partitions in the same query.
Shares of a total
The most common use is “what fraction of the whole is this row?”. Each customer’s orders, with the share of that customer’s spending:
WITH order_totals AS (
SELECT o.customer_id, o.id AS order_id,
sum(oi.quantity * oi.unit_price) AS total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.customer_id IN (1, 2)
GROUP BY o.customer_id, o.id
)
SELECT customer_id, order_id, total,
sum(total) OVER (PARTITION BY customer_id) AS customer_total,
round(100 * total / sum(total) OVER (PARTITION BY customer_id), 1) AS pct
FROM order_totals
ORDER BY customer_id, order_id; customer_id | order_id | total | customer_total | pct
-------------+----------+--------+----------------+------
1 | 1 | 38.50 | 217.65 | 17.7
1 | 3 | 18.00 | 217.65 | 8.3
1 | 9 | 72.65 | 217.65 | 33.4
1 | 17 | 40.50 | 217.65 | 18.6
1 | 23 | 48.00 | 217.65 | 22.1
2 | 2 | 113.00 | 285.25 | 39.6
2 | 7 | 36.00 | 285.25 | 12.6
2 | 14 | 27.25 | 285.25 | 9.6
2 | 21 | 109.00 | 285.25 | 38.2
(9 rows)That’s the diagram, calculated. Ben’s two big orders make up over three quarters of his spending.
Window functions also work on top of a GROUP BY in the same query. The aggregates run first, then the window functions run over the grouped rows — so you can show each category’s revenue and its share of all revenue at once:
SELECT cat.name AS category,
sum(oi.quantity * oi.unit_price) AS revenue,
round(100 * sum(oi.quantity * oi.unit_price)
/ sum(sum(oi.quantity * oi.unit_price)) OVER (), 1) AS pct_of_total
FROM order_items AS oi
JOIN products AS p ON p.id = oi.product_id
LEFT JOIN categories AS cat ON cat.id = p.category_id
GROUP BY cat.name
ORDER BY revenue DESC; category | revenue | pct_of_total
-----------+---------+--------------
Equipment | 514.70 | 42.4
Tea | 334.00 | 27.5
Coffee | 290.25 | 23.9
| 75.00 | 6.2
(4 rows)sum(sum(…)) OVER () looks odd at first: the inner sum is the per-category aggregate from GROUP BY; the outer sum … OVER () adds those category totals up across all result rows. The gift card’s revenue shows up under a NULL category.
Where window functions fit
In the logical order of a query, window functions are calculated after WHERE, GROUP BY and HAVING, and before ORDER BY and LIMIT. Two consequences:
- They see only the rows that survived
WHERE(as you saw with the coffee average). - You can’t use them in
WHEREorHAVING:
SELECT name, price
FROM products
WHERE price > avg(price) OVER ();ERROR: window functions are not allowed in WHERE
LINE 3: WHERE price > avg(price) OVER ();
^To filter on a window result, calculate it in a CTE (or subquery), then filter in the outer query:
WITH priced AS (
SELECT name, category_id, price,
avg(price) OVER (PARTITION BY category_id) AS category_avg
FROM products
)
SELECT name, category_id, price, round(category_avg, 2) AS category_avg
FROM priced
WHERE price > category_avg
ORDER BY category_id, price DESC; name | category_id | price | category_avg
------------------------+-------------+-------+--------------
Ethiopian Yirgacheffe | 1 | 14.50 | 12.58
Darjeeling First Flush | 2 | 18.00 | 12.06
Jasmine Green | 2 | 12.75 | 12.06
Burr Grinder | 3 | 89.00 | 51.23
Electric Kettle | 3 | 59.90 | 51.23
(5 rows)The same five products as the correlated-subquery version in EXISTS and correlated subqueries — but often easier to read, and usually faster, because the averages are computed in a single pass.
Naming a window
When several functions share the same window, define it once with a WINDOW clause and refer to it by name:
SELECT name, category_id, price,
min(price) OVER w AS cheapest_in_cat,
max(price) OVER w AS dearest_in_cat,
count(*) OVER w AS products_in_cat
FROM products
WHERE category_id IS NOT NULL
WINDOW w AS (PARTITION BY category_id)
ORDER BY category_id, price; name | category_id | price | cheapest_in_cat | dearest_in_cat | products_in_cat
------------------------+-------------+-------+-----------------+----------------+-----------------
Decaf House Blend | 1 | 11.25 | 11.25 | 14.50 | 3
Colombian Supremo | 1 | 12.00 | 11.25 | 14.50 | 3
Ethiopian Yirgacheffe | 1 | 14.50 | 11.25 | 14.50 | 3
Chamomile Calm | 2 | 8.00 | 8.00 | 18.00 | 4
Assam Breakfast | 2 | 9.50 | 8.00 | 18.00 | 4
Jasmine Green | 2 | 12.75 | 8.00 | 18.00 | 4
Darjeeling First Flush | 2 | 18.00 | 8.00 | 18.00 | 4
Pour-Over Dripper | 3 | 24.00 | 24.00 | 89.00 | 4
Glass Teapot | 3 | 32.00 | 24.00 | 89.00 | 4
Electric Kettle | 3 | 59.90 | 24.00 | 89.00 | 4
Burr Grinder | 3 | 89.00 | 24.00 | 89.00 | 4
(11 rows)What’s next
So far each window has been a whole partition, and the order of rows inside it didn’t matter. Add ORDER BY inside OVER (…) and window functions can do things aggregates never could: number and rank rows (the next lesson), and compute running totals, moving averages and comparisons with the previous row (the one after).
Other databases: window functions are standard SQL and supported by PostgreSQL, MySQL 8, SQLite 3.25+, SQL Server, Oracle, and every cloud warehouse — everything in this chapter is portable.
How does each product compare with its category?
For every product that has a category, return name, category_id, price, the category's average price as category_avg (rounded to 2 decimal places) and the difference between the product's price and that average as diff (also rounded to 2 places). Use a window function with PARTITION BY category_id — not GROUP BY. Sort by category_id, then price from highest to lowest.
SELECT name, category_id, price
FROM products
WHERE category_id IS NOT NULL
ORDER BY category_id, price DESC;SELECT name, category_id, price,
round(avg(price) OVER (PARTITION BY category_id), 2) AS category_avg,
round(price - avg(price) OVER (PARTITION BY category_id), 2) AS diff
FROM products
WHERE category_id IS NOT NULL
ORDER BY category_id, price DESC;Summary
- A window function calculates over a set of related rows (the window) but returns a value on every row — rows are not collapsed.
- function(...) OVER () uses all rows of the result as the window; OVER (PARTITION BY col) uses the rows that share col's value.
- Any aggregate — sum, avg, count, min, max — can be used as a window function by adding OVER.
- Window functions run after WHERE, GROUP BY and HAVING, so to filter on them, wrap the query in a CTE or subquery.
- A named WINDOW clause avoids repeating the same OVER (…) definition.