OVER: aggregates that keep every row
GROUP BY squashes each group into one row. Sometimes you want the group’s total and every row. “Each order, next to the customer’s total”:
SELECT id,
customer_id,
total,
sum(total) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;
| id | customer_id | total | customer_total |
|---|---|---|---|
| 10 | 1 | 20 | 50 |
| 11 | 1 | 30 | 50 |
| 12 | 2 | 15 | 15 |
OVER (…) is what makes it a window functionWindow functionA SQL function computed over a set of related rows with OVER, keeping every row in the result.Open in glossary →:
OVER ()with nothing inside: the window is all rows.sum(total) OVER ()puts the grand total on every row.OVER (PARTITION BY customer_id): the window is the rows with the same customer as the current row. LikeGROUP BY, but the rows stay.
Every aggregate works this way: count(*) OVER (…), avg(…) OVER (…), max(…) OVER (…).
Window functions are computed late, after WHERE, GROUP BY and HAVING, right where SELECT runs. So you can’t use one in WHERE. To filter on it, compute it in a subquery or CTE, then filter outside:
WITH t AS (
SELECT id, customer_id, total,
avg(total) OVER (PARTITION BY customer_id) AS customer_avg
FROM orders
)
SELECT * FROM t WHERE total > 2 * customer_avg; -- unusually big orders- Evaluation order:
FROM→WHERE→GROUP BY→HAVING→ window functions →SELECTlist →DISTINCT→ORDER BY→LIMIT. Hence: no windows inWHERE/HAVING; they see rows afterWHERE; and you can window over aggregates:sum(sum(total)) OVER ()gives a grand total next to grouped rows,sum(total) / sum(sum(total)) OVER ()a share. - Filtering: a subquery or CTE. Snowflake, BigQuery, DuckDB and Databricks have
QUALIFY; PostgreSQL, MySQL and SQL Server don’t. - Anatomy:
fn(args) OVER (PARTITION BY … ORDER BY … frame). Reuse withWINDOW w AS (PARTITION BY customer_id ORDER BY created_at)andOVER w. - Execution: a WindowAgg node over input sorted by partition and order keys. An index on
(partition_col, order_col)can provide the order; several different windows in one query may mean several sorts. - Support: PostgreSQL 8.4+, MySQL 8.0+, SQL Server, Oracle, SQLite 3.25+. On Android the bundled SQLite reached 3.25+ only around API 30, so Room queries with
OVERneed a recentminSdkor a bundled SQLite; iOS has had it for years.
Predict the output
orders has 5 rows from 2 customers. How many rows does each query return?
SELECT customer_id, sum(total)
FROM orders
GROUP BY customer_id;
SELECT customer_id, sum(total) OVER (PARTITION BY customer_id)
FROM orders;GROUP BY collapses each customer's orders into one row: 2 rows. The window function computes the same per-customer sum but keeps every order: 5 rows, each showing its customer's total. That's the whole difference between the two.
SELECT id,
customer_id,
total,
round(100.0 * total / sum(total) OVER (PARTITION BY customer_id), 1) AS pct_of_customer,
round(100.0 * total / sum(total) OVER (), 2) AS pct_of_all,
total - avg(total) OVER (PARTITION BY customer_id) AS vs_customer_avg
FROM orders
WHERE status = 'PAID';
-- window over an aggregate: each country's share of all customers
SELECT country,
count(*) AS customers,
round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM customers
GROUP BY country;Worked example: a partition, row by row
Five paid orders:
| id | customer_id | total |
|---|---|---|
| 10 | 1 | 20 |
| 11 | 1 | 30 |
| 12 | 1 | 50 |
| 13 | 2 | 40 |
| 14 | 2 | 10 |
We want round(100.0 * total / sum(total) OVER (PARTITION BY customer_id)): each order’s share of its customer’s spending.
- Split into partitions. Customer 1: orders 10, 11, 12. Customer 2: orders 13, 14. Nothing is removed.
- Compute the window sum per partition. Customer 1: 20 + 30 + 50 = 100. Customer 2: 40 + 10 = 50.
- Put it on every row of its partition. Orders 10, 11 and 12 see 100; orders 13 and 14 see 50.
- Finish the expression per row. Order 10: 100 × 20 / 100 = 20%. Order 11: 30%. Order 12: 50%. Order 13: 80%. Order 14: 20%.
- Result: five rows, each with its own percentage. With
GROUP BYyou’d have needed the totals in a subquery and a join back toorders.
Deep diveWhy you can't filter on a window function in WHERE, and what to do insteadInterview favorite
SELECT …, row_number() OVER (…) AS rn FROM t WHERE rn = 1 fails with “column rn does not exist”, and writing the function itself in WHERE fails with “window functions are not allowed in WHERE”. The reason is the evaluation order: WHERE decides which rows exist before windows are computed, and a window’s value depends on which rows exist. Filtering on it in WHERE would be circular.
The options:
- Subquery or CTE, then filter. The standard answer, works everywhere.
QUALIFYin Snowflake, BigQuery, DuckDB, Databricks:… QUALIFY row_number() OVER (…) = 1. Mention it, but don’t use it in a PostgreSQL interview.DISTINCT ONin PostgreSQL for “first row per group”:SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC.LATERAL … LIMIT nfor top-N per group when there’s a good index and few groups.
A subtle follow-up: filters in the outer query don’t change the window, while filters inside do. “Share of the customer’s total” computed over all orders, then filtered to November, still divides by the all-time total; filtering to November inside the CTE divides by the November total. Decide which question you’re answering before choosing.
fn() OVER (PARTITION BY … ORDER BY … frame): aggregate per window, rows kept.WINDOW w AS (…)for reuse.- Evaluated after
HAVING, beforeORDER BY/LIMIT: no windows inWHERE; filter in an outer query (QUALIFYonly in Snowflake/BigQuery/DuckDB). - Windows over aggregates:
sum(count(*)) OVER (). Inner vs outer filters change the denominator. - SQLite 3.25+ (Android: recent API levels), MySQL 8.0+.
SELECT customer_id, id, total,
sum(total) OVER w AS customer_total,
round(100.0 * total / sum(total) OVER w, 1) AS pct
FROM orders
WINDOW w AS (PARTITION BY customer_id);Check this part
How is sum(total) OVER (PARTITION BY customer_id) different from GROUP BY customer_id?
What window does OVER () cover?
How do you keep only rows where a window function equals 1 in PostgreSQL?
What does sum(count(*)) OVER () compute in a GROUP BY country query?