Window Functions: OVER & PARTITION BY
The problem with GROUP BY
GROUP BY collapses rows: you get the total, but lose the individual expenses. What if you want both — each expense and its share of the user's total?
Window functions keep every row
An aggregate with OVER (…) is calculated over a window of related rows, and the result is attached to each row:
SELECT title, amount,
sum(amount) OVER (PARTITION BY user_id) AS user_total
FROM expenses;
Parts of the OVER clause
function(...) OVER (
PARTITION BY col -- split rows into groups (like GROUP BY, but no collapsing)
ORDER BY col -- order within each partition
ROWS/RANGE frame -- which rows to include (lesson 9.4)
)
OVER ()– the window is all rows (the grand total on every row)PARTITION BY user_id– a separate window per user- Adding
ORDER BYchanges aggregates into running values (running total)
Which functions can be used?
- Aggregates:
sum,avg,count,min,max+ OVER - Ranking:
row_number,rank,dense_rank,ntile,percent_rank(9.2) - Offset/value:
lag,lead,first_value,last_value,nth_value(9.3)
Where they run
Window functions are computed after WHERE, GROUP BY and HAVING (in the SELECT step). So:
- ❌ You can't use them in WHERE → wrap the query in a subquery/CTE and filter outside
- ✅ You can use them on top of GROUP BY results:
sum(sum(amount)) OVER ()
Named windows
Reuse a definition: … OVER w … WINDOW w AS (PARTITION BY user_id ORDER BY spent_on)
Example
-- Each expense with the user's total and its share (no rows lost!)
SELECT user_id, title, amount,
sum(amount) OVER (PARTITION BY user_id) AS user_total,
round(100.0 * amount / sum(amount) OVER (PARTITION BY user_id), 1) AS pct_of_user
FROM expenses
WHERE user_id = 4
ORDER BY amount DESC;
-- 4 | Concert | 2500.00 | 7940.00 | 31.5
-- 4 | Groceries | 1750.00 | 7940.00 | 22.0 ...
-- OVER (): compare with the grand total and the global average
SELECT title, amount,
round(avg(amount) OVER (), 2) AS overall_avg,
amount - round(avg(amount) OVER (), 2) AS diff_from_avg
FROM expenses
ORDER BY amount DESC
LIMIT 3;
-- Several windows at once
SELECT user_id, title, amount,
count(*) OVER (PARTITION BY user_id) AS user_expense_count,
max(amount) OVER (PARTITION BY user_id) AS user_max,
avg(amount) OVER (PARTITION BY category_id) AS category_avg
FROM expenses
WHERE user_id = 1
LIMIT 4;
-- Window over GROUP BY results: each category's share of all spending
SELECT c.name,
sum(e.amount) AS total,
round(100.0 * sum(e.amount) / sum(sum(e.amount)) OVER (), 1) AS pct
FROM expenses e JOIN categories c ON c.id = e.category_id
GROUP BY c.name
ORDER BY total DESC;
-- ❌ Not allowed: WHERE sum(amount) OVER (...) > 5000
-- ✅ Filter outside:
SELECT * FROM (
SELECT user_id, title, amount, sum(amount) OVER (PARTITION BY user_id) AS user_total
FROM expenses
) t
WHERE user_total > 22000;