Sub topic 1
From GROUP BY to window functions
Prerequisites
This chapter assumes you can already do the following:
- Write
SELECT,WHEREandORDER BYqueries. - Use
GROUP BYwith aggregates such asSUM,COUNTandAVG, and filter groups withHAVING. - Read a subquery or a common table expression (CTE).
- Run SQL on a database that supports window functions: PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+ or Oracle.
Every example uses one small table called sales. You can create it in any of those databases with this script.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
salesperson VARCHAR(20),
sale_date DATE,
amount INTEGER
);
INSERT INTO sales (id, region, salesperson, sale_date, amount) VALUES
(1, 'East', 'Ana', '2025-01-05', 100),
(2, 'East', 'Ben', '2025-01-12', 300),
(3, 'East', 'Ana', '2025-02-02', 200),
(4, 'West', 'Cara', '2025-01-08', 400),
(5, 'West', 'Dev', '2025-01-20', 100),
(6, 'West', 'Cara', '2025-02-10', 500);The problem GROUP BY cannot solve
GROUP BY answers questions about groups of rows. It collapses each group into a single output row. That is what you want for a report of total sales per region.
SELECT region, SUM(amount) AS region_total
FROM sales
GROUP BY region;The result has two rows, one per region.
| region | region_total |
|---|---|
| East | 600 |
| West | 1000 |
Now suppose a manager asks a slightly different question: "Show me every sale, and next to each one, the total for its region and the share of that total." The detail rows must stay. The group total must appear on each of them.
With only GROUP BY, you have two awkward options. The first is to select only columns that are in the GROUP BY list or inside aggregates. That loses the detail. The second is to compute the totals in a subquery and join them back to the detail rows.
SELECT s.id, s.region, s.salesperson, s.amount,
t.region_total,
s.amount * 100.0 / t.region_total AS pct_of_region
FROM sales AS s
JOIN (
SELECT region, SUM(amount) AS region_total
FROM sales
GROUP BY region
) AS t ON t.region = s.region;This works, but it reads the table twice, repeats the grouping column in two places, and gets harder to maintain as you add more calculations. Window functions solve this directly.
What a window function is
A window function computes a value for each row from a related set of rows, called the row's window. Unlike a GROUP BY aggregate, it does not collapse rows. Every input row appears in the output, and the function adds a column to it.
Here is the same request as a window query.
SELECT
id,
region,
salesperson,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total,
amount * 100.0 / SUM(amount) OVER (PARTITION BY region) AS pct_of_region
FROM sales;All six rows come back. Each carries the total for its own region.
| id | region | salesperson | amount | region_total | pct_of_region |
|---|---|---|---|---|---|
| 1 | East | Ana | 100 | 600 | 16.67 |
| 2 | East | Ben | 300 | 600 | 50.00 |
| 3 | East | Ana | 200 | 600 | 33.33 |
| 4 | West | Cara | 400 | 1000 | 40.00 |
| 5 | West | Dev | 100 | 1000 | 10.00 |
| 6 | West | Cara | 500 | 1000 | 50.00 |
The only new syntax is OVER (...). The keyword OVER is what turns SUM from a regular aggregate into a window function. Without it, SUM(amount) next to plain columns would be an error in most databases, because the query would be mixing aggregated and non-aggregated values.
How the two approaches differ
The difference is in what happens to the rows, and it affects what you can select.
| Aspect | GROUP BY aggregate | Window function |
|---|---|---|
| Output rows | One per group | One per input row |
| Detail columns | Only grouped columns or aggregates | Any column of the row |
| Grouping defined by | `GROUP BY` clause | `PARTITION BY` inside `OVER` |
| Different groupings in one query | Needs subqueries or joins | Each function can have its own `OVER` |
| Filtered with | `HAVING` | A CTE or subquery (covered later in this tutorial) |
The fourth row matters in practice. One query can contain several window functions, each with a different window definition. You can show the total per region, the total per salesperson and the grand total side by side, without a single join.
SELECT
id,
region,
salesperson,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total,
SUM(amount) OVER (PARTITION BY salesperson) AS person_total,
SUM(amount) OVER () AS grand_total
FROM sales;The empty OVER () means "no partitions and no ordering". The window is the whole result set, so every row sees the grand total of 1600.
The window is not a group
It helps to hold a clear mental model, because it prevents most early mistakes.
- A
GROUP BYgroup is a bucket. Rows go in, and one summary row comes out. - A window is a view that each row gets of the other rows. Every row has its own window, and windows can overlap.
When you use only PARTITION BY, the windows of all rows in the same partition happen to be identical, so it looks like grouping. Once you add ordering and frames in later chapters, the window for each row can differ. A running total, for example, gives row 1 a window of one row and row 5 a window of five rows.
Combining both in one query
Window functions and GROUP BY can appear in the same query, but they run in a fixed order. The GROUP BY step runs first, and the window function then operates on the grouped rows. That means the window function can only reference grouped columns and aggregates.
This query first totals each salesperson's sales per region, then ranks those totals across all regions in one pass.
SELECT
region,
salesperson,
SUM(amount) AS person_total,
SUM(SUM(amount)) OVER (PARTITION BY region) AS region_total
FROM sales
GROUP BY region, salesperson;Read SUM(SUM(amount)) OVER (...) from the inside out. The inner SUM(amount) is the regular aggregate computed per GROUP BY group. The outer SUM(...) OVER adds those per-person totals within each region. The result has one row per region and salesperson, and each row shows its region total.
| region | salesperson | person_total | region_total |
|---|---|---|---|
| East | Ana | 300 | 600 |
| East | Ben | 300 | 600 |
| West | Cara | 900 | 1000 |
| West | Dev | 100 | 1000 |
The row order of the output is not guaranteed, because the query has no final ORDER BY.
Common mistakes at this stage
These errors appear often when people first switch from GROUP BY to window functions.
- Forgetting
OVER.SUM(amount)alone is a regular aggregate. Mixed with plain columns and noGROUP BY, it fails with an error such as "column must appear in the GROUP BY clause or be used in an aggregate function". - Expecting fewer rows. A window function never reduces the row count. If you want one row per group, you still need
GROUP BYor a later step that picks one row per group. - Using a window function in
WHERE. This is not allowed. TheWHEREclause runs before windows are computed. You need a CTE or subquery, which a later chapter shows. - Repeating the same long window. Copying
OVER (PARTITION BY region ORDER BY sale_date, id)into five columns is error-prone. A later chapter introduces theWINDOWclause to name it once.
When to choose which
Pick the tool by the shape of the answer you need.
- Use
GROUP BYwhen the answer is one row per group, such as a summary report. - Use a window function when each original row must stay visible and also needs a value derived from other rows: a share of a total, a rank, a running total, or a comparison to the previous row.
- Use both when you need to summarize first and then compare the summaries, as in the
SUM(SUM(amount)) OVERexample.
Window functions are not automatically faster than a join to a grouped subquery. Often the database sorts or partitions the data once and does the work in a single pass, which can be cheaper. But for a very large table with a highly selective filter, the cost depends on indexes and the query plan, so measure on your own data. Performance is revisited in the last chapter of this tutorial.
Exercise
Using the sales table, write a query that returns each sale's id, salesperson and amount, plus a column called salesperson_total with the total amount for that salesperson across all of their sales. Then say how many rows the query returns and why.
Show answer
SELECT id, salesperson, amount, SUM(amount) OVER (PARTITION BY salesperson) AS salesperson_total FROM sales; The query returns 6 rows, the same as the number of rows in sales, because a window function does not collapse rows. Ana's two sales both show 300, Ben's sale shows 300, Cara's two sales both show 900, and Dev's sale shows 100.
Exercise
A colleague writes SELECT region, amount, SUM(amount) FROM sales GROUP BY region; and gets an error. Explain the cause and give two ways to fix it, one that keeps every sale row and one that returns one row per region.
Show answer
The column amount is neither in the GROUP BY list nor inside an aggregate, so the database cannot decide which amount to show for a region group. To keep every sale row, use a window function: SELECT region, amount, SUM(amount) OVER (PARTITION BY region) AS region_total FROM sales; To return one row per region, remove amount from the select list: SELECT region, SUM(amount) FROM sales GROUP BY region;