Sub topic 2
Reading the `OVER` Clause
This chapter assumes you know SELECT, WHERE, ORDER BY, GROUP BY, aggregate functions, subqueries, and common table expressions (CTEs). You also need a database that supports window functions, such as PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+, or Oracle.
A window function calculates a value from related rows while keeping one result row for each input row. The OVER clause defines which related rows the function can inspect and how it should interpret them.
The basic shape
A window function has this form:
function_name(...) OVER (
PARTITION BY partition_columns
ORDER BY ordering_columns
)Each part has a different job:
- The function performs the calculation, such as
SUM,AVG,ROW_NUMBER, orLAG. PARTITION BYdivides the result rows into independent groups.ORDER BYdefines the sequence of rows inside each group.
Unlike GROUP BY, PARTITION BY does not combine rows into one row per group.
`PARTITION BY` defines independent groups
Suppose sales contains id, region, salesperson, and amount. This query calculates each region's total beside every sale:
SELECT
id,
region,
salesperson,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales;The database calculates one sum for each region. Every sale in that region receives the same region_total, but every sale remains visible.
Without PARTITION BY, the window contains all rows:
SELECT
id,
region,
amount,
SUM(amount) OVER () AS company_total
FROM sales;The empty OVER () means that the function can inspect the complete result set.
`ORDER BY` defines the window sequence
Add an ordering expression when the calculation depends on position:
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS running_total
FROM sales;For each region, the database sorts by sale_date, then by id when dates tie. The sum can then build a running total in that sequence.
The ORDER BY inside OVER is separate from the query's final ORDER BY. The window ordering controls the calculation. A final ORDER BY controls how the returned rows are displayed:
SELECT
region,
sale_date,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC, id
) AS amount_position
FROM sales
ORDER BY sale_date, region;Here, rows are ranked by amount within each region, but displayed by date and region.
Always add a tie-breaker such as id when equal values could produce an unspecified order. This makes functions such as ROW_NUMBER deterministic.
Choosing the window
Before writing a window function, answer these questions:
- Should all rows share one window, or should rows be separated with
PARTITION BY? - Does the calculation depend on row order?
- If it does, which columns define that order?
- Can two rows tie, and what column provides a stable tie-breaker?
Exercise
What does SUM(amount) OVER (PARTITION BY region) return for each sale?
Show answer
It returns the total amount for that sale's region while preserving one output row for every sale.