GROUP BY squashes each group into one row. A window function keeps every row and adds a value worked out over a set of related rows, its window. OVER (…) is what makes a function a window function. Each product beside its category's average price:
SELECT name, category, price,
ROUND(AVG(price) OVER (PARTITION BY category), 2) AS category_avg
FROM products
ORDER BY category, price;
PARTITION BY splits the rows into groups, like GROUP BY but without collapsing anything. With empty brackets, OVER (), the window is the whole result.
Add ORDER BY inside the OVER and the numbering functions come into play. ROW_NUMBER() numbers the rows 1, 2, 3 in that order, starting again in each partition. Each customer's orders, numbered by date:
SELECT customer_id, id, ordered_on,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_on) AS nth
FROM orders
WHERE customer_id <= 3
ORDER BY customer_id, nth;
Ties are where the numbering functions differ. ROW_NUMBER always gives 1, 2, 3, 4, choosing between tied rows any way it likes unless you add a tie-breaker. RANK gives tied rows the same number and then skips (1, 2, 2, 4). DENSE_RANK doesn't skip (1, 2, 2, 3). Theo and Zara earn the same:
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary, name) AS row_num,
RANK() OVER (ORDER BY salary) AS rnk,
DENSE_RANK() OVER (ORDER BY salary) AS dense
FROM staff
WHERE salary < 50000
ORDER BY salary, name;
Window functions are worked out after WHERE, GROUP BY and HAVING, just before ORDER BY. So you can't filter on one in WHERE: WHERE ROW_NUMBER() OVER (…) = 1 is an error. Put the query in a CTE and filter outside it (next lessons). It also means a window can run over grouped results: SUM(COUNT(*)) OVER () is the total of all the groups' counts.
Practice
Number each customer's orders by date: customer_id, the order id, and the number (1 for their first order).