skipnothing/SQL
UNIT 06

Window Functions

Aggregate without collapsing, OVER, PARTITION BY, ranking, running totals

Window functions compute aggregates *next to* every row instead of collapsing rows into groups. Ranking, running totals, period-over-period comparisons, all live here.

Loading…
BUILDS ON
TOPICS
#20

OVER() & Ranking

Add OVER() to an aggregate so the rows stop collapsing, number rows with ROW_NUMBER, RANK, and DENSE_RANK, and choose among the three when two rows tie at the same value.

Four rows in orders hold amounts 99.00, 42.00, 42.00, 17.50, and totalling them folds the four into one number, 200.50. Total them a second way and all four rows stay, each now carrying that 200.50 beside it.

14 min
#21

PARTITION BY & ORDER BY

Split a window into one partition per group so an aggregate or ranking restarts at each boundary, order rows inside each partition, and watch ORDER BY turn a flat total into one that climbs row by row.

Four orders sit in orders, two from user 1 and two from user 2, and adding every amount gives one number: 246.50. Ask instead for each user's total beside their rows and that 246.50 splits into 141.00 and 105.50.

13 min
#22

LAG, LEAD & Frames

Reach to a row's neighbors with LAG and LEAD, draw a window's edges explicitly with ROWS BETWEEN, and watch the default RANGE frame lump tied rows where ROWS makes them climb.

Five orders from one customer sit in orders, sorted by date. Each row knows its own amount but not what came just before it, so the answer to 'bigger or smaller than last time' is sitting one row up.

14 min
#23

Window vs GROUP BY

Choose window when you need a value beside every row and GROUP BY when you need one row per group, rewrite either form as the other, and wrap a window in an outer query when you must filter on its result.

Four rows in orders, two customers, and the same SUM(amount) asked twice: once it answers with two totals, once it answers with four rows that each carry their customer's total along for the ride.

12 min
All units