Solving Classic Problems with Window Functions
Use window functions to solve the interview questions and real-world puzzles that trip up most beginners.
Finding the Nth highest salary, top N per group, duplicate detection — these are all solved elegantly with window functions.
EXERCISE
1Top N Per Group — The Most Asked SQL Interview Problem
Finding the top 1, 2, or N records per group is one of the most common SQL problems. Window functions solve it cleanly and efficiently.
The classic way to solve "top N per group" is: rank within each group, then filter for rank <= N. **Top 1 salary per department:** ```sql WITH ranked AS ( SELECT name, department, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees ) SELECT name, department, salary FROM ranked WHERE rn = 1; ``` **Top 2 salaries per department (handle ties with DENSE_RANK):** ```sql WITH ranked AS ( SELECT name, department, salary, DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk FROM employees ) SELECT name, department, salary, rnk FROM ranked WHERE rnk <= 2; -- If two people tie for 2nd, both are returned ``` **Most recent order per customer:** ```sql WITH latest AS ( SELECT customer_id, order_id, total, created_at, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn FROM orders ) SELECT customer_id, order_id, total, created_at FROM latest WHERE rn = 1; ``` **Top 3 products by revenue per category:** ```sql WITH ranked_products AS ( SELECT category, product_name, total_revenue, RANK() OVER (PARTITION BY category ORDER BY total_revenue DESC) AS rnk FROM product_sales ) SELECT category, product_name, total_revenue FROM ranked_products WHERE rnk <= 3 ORDER BY category, rnk; ``` > **Pro Tip:** The pattern is always the same: `WITH ranked AS (... ROW_NUMBER/RANK OVER (PARTITION BY group ORDER BY metric DESC))` then `WHERE rn = 1`. Memorise this pattern — it comes up in almost every SQL interview.
EXERCISE
2Deduplication, Gap Detection & Consecutive Events
Window functions make light work of three classic data problems: finding duplicate records, detecting missing data in a sequence, and identifying consecutive events.
Deduplication — keep only the first occurrence:
-- Keep only the first registration per email:
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at ASC) AS rn
FROM customers
)
DELETE FROM customers
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);
-- Deletes all but the earliest registration for each email
Finding missing IDs in a sequence (gap detection):
-- Find gaps in order IDs:
WITH order_sequence AS (
SELECT
id,
LEAD(id) OVER (ORDER BY id) AS next_id
FROM orders
)
SELECT id AS gap_after, next_id AS gap_before,
next_id - id - 1 AS missing_count
FROM order_sequence
WHERE next_id - id > 1;
-- Shows ranges where IDs are missing
Identifying consecutive days with activity:
-- Find users who were active 3 or more consecutive days:
WITH
activity AS (
SELECT DISTINCT user_id, DATE(created_at) AS activity_date FROM events
),
grouped AS (
SELECT user_id, activity_date,
activity_date - INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY activity_date) DAY AS grp
FROM activity
),
streaks AS (
SELECT user_id, grp, COUNT(*) AS streak_length,
MIN(activity_date) AS streak_start,
MAX(activity_date) AS streak_end
FROM grouped
GROUP BY user_id, grp
)
SELECT user_id, streak_start, streak_end, streak_length
FROM streaks
WHERE streak_length >= 3
ORDER BY streak_length DESC;
Pro Tip: The "consecutive events" pattern works by subtracting the row number from the date. Rows that are part of the same consecutive run will all produce the same
grpvalue — a clever trick worth memorising.
EXERCISE
3Pivot Tables in SQL — Rows to Columns
Pivoting transforms row values into columns — turning a vertical list of categories into a horizontal summary table. SQL does this with conditional aggregation.
MySQL does not have a native PIVOT keyword (unlike SQL ), but conditional aggregation with CASE achieves the same result.
The problem — data is vertical:
-- sales: product, month, revenue
-- Jan: Electronics 50000, Clothing 30000
-- Feb: Electronics 62000, Clothing 25000
-- Original shape:
-- +-------------+-------+---------+
-- | product | month | revenue |
-- +-------------+-------+---------+
-- | Electronics | 1 | 50000 |
-- | Clothing | 1 | 30000 |
-- | Electronics | 2 | 62000 |
-- | Clothing | 2 | 25000 |
The pivot — make months into columns:
SELECT
product,
SUM(CASE WHEN month = 1 THEN revenue ELSE 0 END) AS jan,
SUM(CASE WHEN month = 2 THEN revenue ELSE 0 END) AS feb,
SUM(CASE WHEN month = 3 THEN revenue ELSE 0 END) AS mar,
SUM(revenue) AS total
FROM sales
GROUP BY product;
Output:
+-------------+-------+-------+------+--------+
| product | jan | feb | mar | total |
+-------------+-------+-------+------+--------+
| Clothing | 30000 | 25000 | 8000 | 63000 |
| Electronics | 50000 | 62000 |75000 | 187000 |
+-------------+-------+-------+------+--------+
Count pivot — headcount per department per year:
SELECT department,
COUNT(CASE WHEN YEAR(hire_date) = 2022 THEN 1 END) AS hired_2022,
COUNT(CASE WHEN YEAR(hire_date) = 2023 THEN 1 END) AS hired_2023,
COUNT(CASE WHEN YEAR(hire_date) = 2024 THEN 1 END) AS hired_2024
FROM employees
GROUP BY department;
Pro Tip: The pattern is:
SUM(CASE WHEN category = 'X' THEN value ELSE 0 END) AS X. This works for any number of categories. The trade-off is that you must know your categories in advance to write the CASE expressions.
