Sub topic 10
Practical patterns: top-N, period change, gaps and islands
This chapter combines the pieces from earlier chapters into three patterns you will use often. I assume you can already write OVER (PARTITION BY ... ORDER BY ...), you know ROW_NUMBER, RANK and LAG, and you are comfortable with CTEs. The examples use the sales, monthly_revenue and logins tables described below and run on PostgreSQL, MySQL 8+, SQL Server and SQLite 3.25+, unless a note says otherwise.
Pattern 1: top-N per group
The goal is "the three biggest sales in each region". A GROUP BY cannot do this because it collapses rows. A window function can number the rows inside each region, and an outer query keeps the first N.
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;The ranking lives in a CTE because window functions are evaluated after WHERE. Writing WHERE ROW_NUMBER() OVER (...) <= 3 directly is an error. Some engines (Snowflake, BigQuery, DuckDB) offer a QUALIFY clause that filters on window results in the same query. PostgreSQL, MySQL, SQL Server, SQLite and Oracle do not.
Choosing the ranking function
The three ranking functions behave differently when amounts tie. Suppose a region has amounts 500, 400, 400, 300.
| Function | Values returned | Rows kept by `<= 2` |
|---|---|---|
| `ROW_NUMBER` | 1, 2, 3, 4 | 2 rows, but which 400 survives is arbitrary |
| `RANK` | 1, 2, 2, 4 | 3 rows (500, 400, 400) |
| `DENSE_RANK` | 1, 2, 2, 3 | 3 rows (500, 400, 400) |
Pick the function from the business question:
- Use
ROW_NUMBERwhen you need exactly N rows per group. Add a tiebreaker such asORDER BY amount DESC, idso the result is the same on every run. - Use
RANKorDENSE_RANKwhen tied rows should all qualify. The result can contain more than N rows per group. - For "latest row per customer", use
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC)and keeprn = 1.
Pattern 2: period-over-period change
Here you compare each row with the one before it. LAG(column, offset, default) reads a column from a row offset positions earlier in the window's order. The default offset is 1.
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;The first row has no predecessor, so prev_revenue and change_from_prev are NULL there. That is usually the correct answer, because there is nothing to compare against. Pass a third argument, such as LAG(revenue, 1, 0), only when a default is meaningful. A default of 0 would make the first month look like infinite growth.
Percentage change
You cannot refer to the prev_revenue alias in the same SELECT, so compute the lag in a CTE first. Guard against division by zero with NULLIF.
WITH monthly AS (
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS prev_revenue
FROM monthly_revenue
)
SELECT
sale_month,
revenue,
prev_revenue,
ROUND(100.0 * (revenue - prev_revenue) / NULLIF(prev_revenue, 0), 1) AS pct_change
FROM monthly;NULLIF(prev_revenue, 0) returns NULL when the previous value is 0, so the division yields NULL instead of an error. The 100.0 literal forces decimal division, which avoids integer truncation in engines such as PostgreSQL and SQL Server.
Year-over-year and missing periods
LAG(revenue, 12) compares a month with the same month a year earlier. It counts rows, not calendar months. If a month has no row, for example because no sales happened, every later comparison is off by one month. Two fixes are common:
- Build a complete calendar of months (a calendar table, or
generate_seriesin PostgreSQL), left join your data onto it, and useCOALESCE(revenue, 0). - Self-join on the exact date arithmetic, such as the current month minus one year, and accept
NULLwhen no row matches.
If the table holds several products, add PARTITION BY product_id so the first month of each product gets NULL instead of borrowing the last month of the previous product.
LEAD is the mirror image and looks forward. It is useful for "days until the next event" calculations.
Pattern 3: gaps and islands
An island is a run of consecutive values, such as a login streak. A gap is the missing stretch between two islands. Both problems come up in attendance data, uptime logs and sequence numbers. Use this data:
CREATE TABLE logins (day_no INTEGER PRIMARY KEY);
INSERT INTO logins (day_no) VALUES (1), (2), (3), (5), (6), (8);Finding islands
Within a run of consecutive integers, day_no and ROW_NUMBER() both rise by 1 on each row. Their difference is therefore constant inside a run and jumps when a day is skipped.
| day_no | ROW_NUMBER | day_no - ROW_NUMBER |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 3 | 0 |
| 5 | 4 | 1 |
| 6 | 5 | 1 |
| 8 | 6 | 2 |
The difference is a label for each island. Group on it:
SELECT
MIN(day_no) AS start_day,
MAX(day_no) AS end_day,
COUNT(*) AS streak_length
FROM (
SELECT
day_no,
day_no - ROW_NUMBER() OVER (ORDER BY day_no) AS grp
FROM logins
) t
GROUP BY grp;The result is three islands: days 1 to 3 (length 3), days 5 to 6 (length 2) and day 8 (length 1). The group label grp has no meaning of its own. It only has to be equal within an island and different between islands.
Dates and duplicates
The trick needs two things to hold:
- Values must be distinct. A duplicate gets a new row number but not a new value, so the difference changes inside a run and splits the island. Use
SELECT DISTINCTin the inner query, orDENSE_RANKin place ofROW_NUMBER. - Values must be integers, or convertible to them. For dates in PostgreSQL,
date - integerreturns a date, so this works:
SELECT
MIN(login_date) AS start_date,
MAX(login_date) AS end_date,
COUNT(*) AS streak_days
FROM (
SELECT
login_date,
login_date - CAST(ROW_NUMBER() OVER (ORDER BY login_date) AS INTEGER) AS grp
FROM (SELECT DISTINCT login_date FROM user_logins) d
) t
GROUP BY grp;Other engines need their own date arithmetic, such as DATEADD(day, -rn, login_date) in SQL Server or DATE_SUB(login_date, INTERVAL rn DAY) in MySQL. If the data has a user column, add PARTITION BY user_id to the ROW_NUMBER and put user_id in the GROUP BY alongside grp.
Finding the gaps
To list the missing stretches, compare each value with the next one using LEAD:
SELECT
day_no + 1 AS gap_start,
next_day - 1 AS gap_end
FROM (
SELECT
day_no,
LEAD(day_no) OVER (ORDER BY day_no) AS next_day
FROM logins
) t
WHERE next_day - day_no > 1;This returns days 4 to 4 and 7 to 7. The last row has a NULL next_day, and the comparison with NULL is not true, so the row is filtered out. That is the behavior you want.
Choosing the right tool
| Question | Pattern | Key function |
|---|---|---|
| Best N rows per category | Rank in a CTE, filter outside | `ROW_NUMBER`, `RANK`, `DENSE_RANK` |
| Change from the previous row | Read a neighbour | `LAG`, `LEAD` |
| Runs of consecutive values | Value minus row number, then group | `ROW_NUMBER` |
| Missing stretches | Compare with the next value | `LEAD` |
Exercises
Exercise
A table scores(player, game, points) has ties. You want each game's top two scores, and every player tied for second place must be included. Which ranking function do you use, and what is the filter?
Show answer
Use DENSE_RANK() OVER (PARTITION BY game ORDER BY points DESC) AS dr in a CTE, then filter WHERE dr <= 2 in the outer query. RANK also keeps all tied rows, but DENSE_RANK is the usual choice for "top two distinct scores" because it does not skip numbers after a tie. ROW_NUMBER would drop some tied players.
Exercise
The logins table now holds (1), (2), (2), (3), (5), with day 2 duplicated because the key constraint was removed. Your island query returns four rows instead of two. What causes it, and how do you fix it?
Show answer
The duplicate day 2 receives its own row number, so day_no - ROW_NUMBER() changes in the middle of the first run and splits it into separate groups. Deduplicate before numbering, for example FROM (SELECT DISTINCT day_no FROM logins) d. The result is then the islands 1 to 3 and 5 to 5.