Sub topic 1
From GROUP BY to window functions
Prerequisites
This chapter assumes you can write SELECT queries with WHERE and ORDER BY, group rows with GROUP BY, use aggregates such as SUM and COUNT, and read a common table expression (CTE). You also need a database that supports window functions, such as PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+, or Oracle.
The problem with GROUP BY
An aggregate function summarizes several rows into one value. For example, this query returns one row per region:
SELECT
region,
SUM(amount) AS region_total,
AVG(amount) AS average_sale
FROM sales
GROUP BY region;GROUP BY changes the result's shape. The individual sales rows are no longer available in the result. That is useful for reports, but it is limiting when each sale must also show information about its region.
A window function calculates over related rows while keeping the current row. The following query returns every sale and repeats the total for that sale's region:
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;The SUM is still an aggregate, but OVER turns it into a window function.
The `OVER` clause
The OVER clause defines the set of rows that a window function can inspect. Its most common parts are:
| Part | Meaning |
|---|---|
| `PARTITION BY region` | Divide the result into independent groups |
| `ORDER BY sale_date` | Define the order inside each group |
| Frame clause | Limit the rows relative to the current row |
PARTITION BY is similar to GROUP BY, but it does not collapse the rows. Without PARTITION BY, the window contains all rows returned by the query:
SELECT
id,
amount,
SUM(amount) OVER () AS grand_total
FROM sales;Every result row receives the same grand total.
Window ordering is separate from the query's final presentation order. You can calculate values in date order and display the result in another order:
SELECT
id,
sale_date,
amount,
SUM(amount) OVER (
ORDER BY sale_date, id
) AS running_total
FROM sales
ORDER BY amount DESC;The inner ORDER BY controls the calculation. The final ORDER BY controls how rows are displayed. Adding id gives a deterministic order when two sales have the same date.
Choosing the right tool
Use GROUP BY when you need one result row per group. Use a window function when you need both detail and context, such as a regional total, a percentage of the total, or a comparison with nearby rows.
A window function cannot replace every grouped query. It adds calculations to rows; it does not automatically remove duplicates or produce one row per group.
Exercise
You need each employee's salary and the average salary in that employee's department on the same row. Should you use GROUP BY or a window function?
Show answer
Use a window function: AVG(salary) OVER (PARTITION BY department_id). GROUP BY would remove the individual employee rows.