SQL Window functions, explained
A window function calculates across a set of rows related to the current row, but unlike GROUP BY it keeps every row. You add OVER (...) to say which rows count.
PARTITION BY splits rows into groups that are handled separately, and ORDER BY inside OVER decides the order for rankings and running totals.
Examples
1. Rank within each group
SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank
FROM products;Numbering restarts at 1 for each category.
2. Running total
SELECT order_date, total,
SUM(total) OVER (ORDER BY order_date) AS running_total
FROM orders;Each row shows the sum of all orders up to that date.
Practice Window functions
3 questions, easiest first. Your progress is saved on this device.
- โRank within a categoryhard
- ๐Running totalhard
- ๐Top earner per teamhard