Sub topic 2
Ranking rows: ROW_NUMBER, RANK and DENSE_RANK
Prerequisites
This chapter assumes you can write SELECT, WHERE and ORDER BY, use GROUP BY with SUM and AVG, and write a common table expression (CTE) with WITH. The examples use a sales table with id, region, salesperson, sale_date and amount columns. You need a database that supports window functions, such as PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+ or Oracle.
Ranking rows with ROW_NUMBER, RANK and DENSE_RANK
A window function computes a value for each row using a set of related rows. Unlike GROUP BY, it keeps every row. The OVER clause defines that set. ORDER BY inside OVER sets the ranking order.
SELECT
salesperson,
amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS row_num,
RANK() OVER (ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY amount DESC) AS dense_rnk
FROM sales;For tied amounts, ROW_NUMBER always gives unique numbers. RANK repeats a number and then skips ahead. DENSE_RANK repeats a number without skipping.
Running totals and per-group aggregates
An aggregate such as SUM becomes a window function when you add OVER. Adding PARTITION BY restarts the calculation for each group. The frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW includes every row from the start of the group up to the current row.
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM sales;The extra id in ORDER BY makes the order stable when two sales share a date.
Looking at neighbouring rows with LAG and LEAD
LAG(col) returns the value from the previous row in the window order. LEAD(col) returns the value from the next row. The first row gets NULL from LAG.
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS prev_revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_prev
FROM monthly_revenue;Where window functions run and how to filter on them
To keep the top three sales in each region, rank the rows in a CTE and filter in the outer query:
WITH ranked AS (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn <= 3;Exercise
Using the sales table, how would you list each region's sales with the rank of each amount, so that tied amounts in a region share a rank and the next rank has no gap?
Show answer
Use DENSE_RANK() OVER (PARTITION BY region ORDER BY amount DESC) in a SELECT. Tied amounts get the same number, and the following number is one higher, with no skip.