Sub topic 1
From GROUP BY to window functions
Prerequisites
This chapter assumes you can write SELECT, WHERE and ORDER BY, use GROUP BY with SUM and COUNT, and read a simple common table expression (CTE). The examples use a sales table and run on PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+ or Oracle.
Why GROUP BY hides detail
GROUP BY collapses rows. Each group becomes one output row, so the individual sales disappear.
SELECT region, SUM(amount) AS region_total
FROM sales
GROUP BY region;This returns one row per region. You cannot also show each sale's id next to the regional total in the same query.
A window function computes an aggregate over a set of related rows but keeps every row. The query below returns every sale and its region's total.
Reading the OVER clause
A window function is a function followed by an OVER clause. The OVER clause defines the set of rows the function sees for each output row.
SELECT
id,
region,
amount,
SUM(amount) OVER () AS grand_total
FROM sales;An empty OVER () means the window is the whole result set. Each row gets the same grand total.
Splitting rows into partitions with PARTITION BY
PARTITION BY splits the rows into groups. The function runs separately inside each group, and the group boundaries do not remove rows.
SELECT
id,
region,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales;Ordering rows inside a window
An ORDER BY inside OVER sets the row sequence within each partition. Aggregates then accumulate in that order, which produces a running total.
SELECT
region,
sale_date,
id,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS running_total
FROM sales;Partitioning and ordering are independent. You can partition without ordering, order without partitioning, or use both.
Exercise
Write a query that returns each sale's id, region and amount, plus the total amount for that sale's region, without removing any rows.
Show answer
SELECT id, region, amount, SUM(amount) OVER (PARTITION BY region) AS region_total FROM sales;