Window functions
GROUP BY collapses several rows into one: when you group by customer, you lose the detail of each order. But sometimes you need both at once: to see each row and, next to it, a calculation made over a set of related rows, such as the running total, the position in a ranking or the difference from the previous order. Window functions do exactly that: they calculate over a window of rows without collapsing them. They are one of the most powerful tools of modern SQL, and they are asked about a lot in interviews.
The OVER clause
A window function is recognized by the OVER (...) clause. Inside you can put PARTITION BY, which splits the rows into independent groups (like a GROUP BY that does not collapse), and ORDER BY, which defines the order within each group. If you put nothing, the window is the whole result. We will use the order_totals view from the previous lesson. First, the rankings: ROW_NUMBER numbers the rows 1, 2, 3, with no ties; RANK gives the same number to ties and skips the following ones (1, 2, 2, 4); DENSE_RANK gives the same number to ties without gaps (1, 2, 2, 3).
-- Number of non-cancelled orders per customer, ranked three ways (note the ties)
WITH per_customer AS (
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
)
SELECT customer_id, orders,
ROW_NUMBER() OVER (ORDER BY orders DESC) AS row_num,
RANK() OVER (ORDER BY orders DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY orders DESC) AS dense_rnk
FROM per_customer
ORDER BY orders DESC, customer_id;
-- Ranking inside each category (PARTITION BY)
SELECT category, name, price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rank_in_category
FROM products
ORDER BY category, rank_in_category;In the first result, customers 3, 4 and 5 tie with 2 orders: RANK gives them 2, 2, 2 and the next one a 5; DENSE_RANK gives them 2, 2, 2 and the next one a 3; ROW_NUMBER gives them 2, 3 and 4 (the order among tied rows is not defined, so add a tie-breaker if you need one). The second example shows how PARTITION BY restarts the numbering in each category.
Running totals, LAG and percentages
Any aggregate (SUM, AVG, COUNT, MIN, MAX) can become a window function by adding OVER. With ORDER BY inside, SUM becomes a running total. The ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW part defines the frame: from the first row to the current one. LAG(value) brings the value of the previous row within the window, and LEAD that of the next: they are ideal for computing differences between periods. An aggregate with an empty OVER () gives the grand total on each row, useful for computing percentages.
-- Running revenue over time (non-cancelled orders)
SELECT order_id, order_date, order_total,
SUM(order_total) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM order_totals
WHERE status <> 'cancelled'
ORDER BY order_date;
-- Compare each order with the previous one of the same customer
SELECT customer_id, order_id, order_total,
LAG(order_total) OVER (PARTITION BY customer_id ORDER BY order_date) AS previous_total,
order_total - LAG(order_total) OVER (PARTITION BY customer_id ORDER BY order_date) AS change
FROM order_totals
WHERE status <> 'cancelled'
ORDER BY customer_id, order_date;
-- Share of each order in the grand total
SELECT order_id, order_total,
ROUND(100.0 * order_total / SUM(order_total) OVER (), 1) AS percent_of_total
FROM order_totals
WHERE status <> 'cancelled';The top-N per group pattern
A classic use case: the largest order of each customer. Window functions cannot be used directly in WHERE (they are calculated after filtering), so they are computed first in a CTE or subquery and filtered by row number in the outer query. It is a pattern you will reuse again and again: number with ROW_NUMBER() within each group and keep the rows whose number is 1 (or less than or equal to N).
WITH ranked AS (
SELECT customer_id, order_id, order_total,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_total DESC) AS rn
FROM order_totals
WHERE status <> 'cancelled'
)
SELECT customer_id, order_id, order_total
FROM ranked
WHERE rn = 1
ORDER BY customer_id;✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères