Window functions
Compute rankings, running totals and comparisons without collapsing rows.
A window function computes a value across a set of related rows but, unlike GROUP BY, it keeps every row. You write it with OVER (...).
SELECT id, user_id, total,
SUM(total) OVER (PARTITION BY user_id) AS user_total
FROM orders;PARTITION BYsplits the rows into groups (likeGROUP BY, but without merging).ORDER BYinsideOVERdefines the order for ranking and running calculations.
Ranking
SELECT user_id, total,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS rn
FROM orders;| Function | Ties |
|---|---|
ROW_NUMBER() | Always unique: 1, 2, 3, 4 |
RANK() | Ties share a rank and leave a gap: 1, 2, 2, 4 |
DENSE_RANK() | Ties share a rank with no gap: 1, 2, 2, 3 |
Running totals and neighbours
SELECT created_at, total,
SUM(total) OVER (ORDER BY created_at) AS running_total,
LAG(total) OVER (ORDER BY created_at) AS previous_total
FROM orders;LAG and LEAD read the previous and next row. Use them to compare a value with the one before it.
CarefulYou cannot use a window function in WHERE. To filter on a rank, put the query in a CTE or subquery and filter in the outer query.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.