Sub topic 2
Reading the OVER clause
What you need before starting
This chapter assumes you can write SELECT, WHERE, ORDER BY and GROUP BY queries and use aggregates such as SUM and COUNT. You will run the examples on PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+ or Oracle. The earlier chapter showed that a window function keeps every row, where GROUP BY collapses them. This chapter covers the syntax that makes that happen: the OVER clause.
The sample table
Every example below uses this small table. The INSERT rows are written so they run on all the databases listed above.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
salesperson VARCHAR(20),
amount INTEGER,
sale_date DATE
);
INSERT INTO sales (id, region, salesperson, amount, sale_date) VALUES
(1, 'East', 'Ana', 100, '2025-01-05'),
(2, 'East', 'Ben', 250, '2025-01-12'),
(3, 'East', 'Ana', 150, '2025-02-03'),
(4, 'West', 'Cy', 300, '2025-01-08'),
(5, 'West', 'Dee', 200, '2025-01-20'),
(6, 'West', 'Cy', 100, '2025-02-10');The East rows total 500, the West rows total 600, and all six rows total 1100.
The anatomy of a window function call
A window function call has two parts. The first is a function, such as SUM(amount). The second is the OVER clause, which says which rows the function looks at for each row of the result.
function_name(arguments) OVER (
[PARTITION BY expression, ...]
[ORDER BY expression [ASC | DESC], ...]
[frame clause]
)All three parts inside the parentheses are optional. Each one narrows or shapes the set of rows the function sees:
PARTITION BYsplits the rows into independent groups.ORDER BYputs the rows of each group in a sequence.- The frame clause picks a sliding or growing subset of that sequence.
The next chapters cover each part in detail. Here you only need to recognise them and know what happens when they are missing.
The empty OVER: one window for the whole result
The simplest OVER has nothing inside the parentheses. It means every row of the result is in one window.
SELECT
id,
region,
amount,
SUM(amount) OVER () AS grand_total
FROM sales;| id | region | amount | grand_total |
|---|---|---|---|
| 1 | East | 100 | 1100 |
| 2 | East | 250 | 1100 |
| 3 | East | 150 | 1100 |
| 4 | West | 300 | 1100 |
| 5 | West | 200 | 1100 |
| 6 | West | 100 | 1100 |
The query returned six rows, one per sale, and each row carries the same grand total. Without OVER, SUM(amount) next to plain columns would be an error, because the database would not know how to collapse id and region.
Adding PARTITION BY
Putting PARTITION BY region inside the parentheses gives each region its own window. The function runs once per window, and each row receives the value for its own window.
SELECT
id,
region,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales;| id | region | amount | region_total |
|---|---|---|---|
| 1 | East | 100 | 500 |
| 2 | East | 250 | 500 |
| 3 | East | 150 | 500 |
| 4 | West | 300 | 600 |
| 5 | West | 200 | 600 |
| 6 | West | 100 | 600 |
Adding ORDER BY
An ORDER BY inside OVER changes what an aggregate means. The window is no longer "all rows in the partition". For each row it becomes "the rows from the start of the partition up to this row", so the result is a running total.
SELECT
id,
amount,
SUM(amount) OVER (ORDER BY id) AS running_total
FROM sales;| id | amount | running_total |
|---|---|---|
| 1 | 100 | 100 |
| 2 | 250 | 350 |
| 3 | 150 | 500 |
| 4 | 300 | 800 |
| 5 | 200 | 1000 |
| 6 | 100 | 1100 |
This shift happens because an ORDER BY with no frame clause triggers a default frame. A later chapter explains that default and its surprises. For now, remember this rule: with no ORDER BY, an aggregate covers the whole partition, and with ORDER BY, it covers the partition up to the current row.
The window ORDER BY is separate from the ORDER BY at the end of the query. The window one controls what the function sees. The final one controls the order of the output rows. A query can have both, and they can differ.
Which functions accept OVER
Three families of functions can be followed by OVER:
- Aggregate functions:
SUM,COUNT,AVG,MIN,MAX. - Ranking functions:
ROW_NUMBER,RANK,DENSE_RANK,NTILE. - Value functions:
LAG,LEAD,FIRST_VALUE,LAST_VALUE,NTH_VALUE.
Ranking and value functions are only valid as window functions, so OVER is required with them. Aggregates work either way: SUM(amount) with GROUP BY collapses rows, and SUM(amount) OVER (...) does not.
Support for details varies by database. For example, SQL Server requires an ORDER BY in the OVER of ranking functions, and several databases reject DISTINCT inside a window aggregate such as COUNT(DISTINCT x) OVER (...). Check your database's documentation before relying on either.
Combining OVER with GROUP BY
A query can use both GROUP BY and OVER. The database groups first, and the window function then runs on the grouped rows. That means the window function's input is the aggregated output, not the original table.
SELECT
region,
SUM(amount) AS region_total,
SUM(SUM(amount)) OVER () AS grand_total
FROM sales
GROUP BY region;| region | region_total | grand_total |
|---|---|---|
| East | 500 | 1100 |
| West | 600 | 1100 |
The inner SUM(amount) is the ordinary aggregate that produces one row per region. The outer SUM(...) OVER () adds up those two region totals. This form is useful when you want group totals and a share of the overall total in one pass, but it reads poorly. If it gets confusing, put the GROUP BY in a CTE and apply the window function in the outer query.
Common errors when reading and writing OVER
- Leaving out the parentheses.
SUM(amount) OVERis a syntax error. WriteOVER ()for an empty window. The only exception is the named-window formOVER w, which a later chapter covers. - Leaving out
OVERand getting aGROUP BYerror. If you writeSELECT region, SUM(amount) FROM sales, the database reports thatregionmust appear inGROUP BY. The fix is to addOVER (...)if you want to keep every row. - Expecting
PARTITION BYto reduce the row count. It does not. The result has exactly as many rows as the input, soPARTITION BYonly decides which rows share a window. - Expecting the window
ORDER BYto order the output. As noted above, only the finalORDER BYdoes that. - Forgetting that adding
ORDER BYchanges an aggregate. If a "total" column suddenly turns into a running total, check whether you added anORDER BYto the window. - Using a window function in
WHERE. Window functions may appear in theSELECTlist and in the finalORDER BY, but not inWHERE,GROUP BYorHAVING. A later chapter on evaluation order shows how to filter on window results.
A reading checklist
When you meet an unfamiliar window function call, read it in this order:
- Find the function and its arguments. This tells you what is being computed.
- Look for
PARTITION BY. If it is missing, all rows form one partition. - Look for
ORDER BY. If it is missing, an aggregate sees the whole partition. - Look for a frame clause (
ROWS,RANGEorGROUPS). If it is missing and there is anORDER BY, the default frame applies.
Applying this to AVG(amount) OVER (PARTITION BY region ORDER BY sale_date) gives: the average of amount, restarted for each region, over the rows from the region's first sale up to the current one in date order.
Exercise
Using the sales table above, what value does SUM(amount) OVER (PARTITION BY region ORDER BY id) return on the row with id 5, and why?
Show answer
500. Row 5 is in the West partition, which contains ids 4, 5 and 6. Ordered by id, the running total is 300 at id 4, then 300 + 200 = 500 at id 5, then 600 at id 6. The East rows form a separate partition, so they do not affect it.
Exercise
A colleague writes SELECT region, amount, SUM(amount) OVER () FROM sales WHERE SUM(amount) OVER () > 1000; and gets an error. Name the problem and describe how to fix it.
Show answer
Window functions cannot be used in WHERE. Compute the window value in a subquery or CTE, give it an alias such as grandtotal, and filter on that alias in the outer query. For example: WITH t AS (SELECT region, amount, SUM(amount) OVER () AS grandtotal FROM sales) SELECT region, amount, grandtotal FROM t WHERE grandtotal > 1000;