Sub topic 10
Practical Patterns: Top-N, Period Change, Gaps and Islands
Assume you know SELECT, WHERE, ORDER BY, aggregates, subqueries, and common table expressions (CTEs). A window function lets you calculate across related rows while keeping each original row. These patterns combine window functions with a CTE or outer query to solve common reporting problems.
Top-N rows per group
Suppose sales contains region, salesperson, and amount. To find the three largest sales in every region, rank rows inside each region:
WITH ranked AS (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC, salesperson
) AS rn
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn <= 3
ORDER BY region, rn;The PARTITION BY clause restarts the ranking for each region. The salesperson tie-breaker makes the result deterministic when two amounts match. Use RANK() instead of ROW_NUMBER() when tied rows should share a rank and all tied rows should be included. For example, RANK() <= 3 can return more than three rows for a region.
| Function | Ties | Possible result for amounts 100, 100, 80 |
|---|---|---|
| `ROW_NUMBER()` | Always unique | 1, 2, 3 |
| `RANK()` | Same rank, then gaps | 1, 1, 3 |
| `DENSE_RANK()` | Same rank, no gaps | 1, 1, 2 |
Period-over-period change
LAG() reads a value from an earlier row in the window order. This makes it useful for month-over-month or day-over-day comparisons:
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS previous_revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_previous
FROM monthly_revenue
ORDER BY sale_month;The first month has no previous row, so LAG() returns NULL. If the table contains several products, add PARTITION BY product_id so each product is compared with its own previous month. LEAD() works the same way for looking ahead.
Gaps and islands
A gaps-and-islands problem finds consecutive runs, called islands, separated by gaps. Assume logins contains one row per user login day, and day_no is a distinct integer day number for one user.
Subtracting a row number from each day produces the same grouping value inside a consecutive run:
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
) AS numbered
GROUP BY grp
ORDER BY start_day;For days 10, 11, 12, and 15, the first three rows share one grp value. Day 15 receives another value because the missing days create a gap.
Common errors
- Omitting a tie-breaker can produce different row numbers between executions.
- Ordering period data by a text label such as
Januarycan put months in alphabetical order. Use a date or numeric period key. - Duplicate dates can make a streak query count rows rather than distinct days. Deduplicate first when the business rule requires one row per day.
LAG()returnsNULLat a partition boundary. Handle it explicitly when calculating percentages or displaying changes.
Exercise
Which function should you use to return every salesperson tied for third place within each region?
Show answer
Use RANK() and filter the result with rank_value <= 3. RANK() gives tied rows the same rank, although the query can return more than three rows.