Pivots, Medians & Tricky Interview Questions
1. Pivot rows into columns
sum(amount) FILTER (WHERE month = 'Sep') AS sep, … (or CASE inside the aggregate). For a dynamic number of columns, the crosstab() function from tablefunc, or pivot in the app.
2. Unpivot columns into rows
CROSS JOIN LATERAL (VALUES ('sep', sep), ('oct', oct)) AS v(month, amount)
3. Customers who never ordered
NOT EXISTS / LEFT JOIN … IS NULL (never NOT IN with NULLable columns)
4. Median without percentile functions
Average of the middle one or two rows using row_number() and count(*) OVER ().
5. Employees earning more than their manager
A self join: e.salary > m.salary where m.id = e.manager_id
6. Top N per group
row_number() / dense_rank() + filter, or LATERAL … LIMIT N
7. Running difference / delta
value - lag(value) OVER (ORDER BY …)
8. Swap values (a classic "UPDATE" question)
UPDATE t SET gender = CASE gender WHEN 'm' THEN 'f' ELSE 'm' END;
9. Find rows present in table A but not in table B
EXCEPT, or an anti-join
10. "Exactly / at least / all" questions
- Users who used all categories:
HAVING count(DISTINCT category_id) = (SELECT count(*) FROM categories) - Users who bought X and Y:
HAVING bool_or(x) AND bool_or(y), or INTERSECT
Interview strategy
- Clarify: ties, NULLs, duplicates, time zones, what "active" means
- Think out loud and start simple — a correct query first, then optimize
- Use CTEs to show clear steps
- Test edge cases mentally: empty table, one row, NULLs, ties
- Mention performance: indexes, avoiding correlated subqueries on big tables
- Practice: LeetCode SQL 50, DataLemur, StrataScratch, HackerRank
Example
-- 1. Pivot: spending per user per month
SELECT u.name,
COALESCE(sum(e.amount) FILTER (WHERE e.spent_on < '2026-10-01'), 0) AS sep,
COALESCE(sum(e.amount) FILTER (WHERE e.spent_on >= '2026-10-01' AND e.spent_on < '2026-11-01'), 0) AS oct,
COALESCE(sum(e.amount) FILTER (WHERE e.spent_on >= '2026-11-01'), 0) AS nov
FROM users u LEFT JOIN expenses e ON e.user_id = u.id
GROUP BY u.id ORDER BY u.id;
-- 2. Unpivot it back into rows
WITH pivoted AS (
SELECT 'Asha' AS name, 6050 AS sep, 8820 AS oct, 7100 AS nov
)
SELECT name, v.month, v.amount
FROM pivoted CROSS JOIN LATERAL (VALUES ('Sep', sep), ('Oct', oct), ('Nov', nov)) AS v(month, amount);
-- 3. Users who never logged an expense
SELECT name FROM users u WHERE NOT EXISTS (SELECT 1 FROM expenses e WHERE e.user_id = u.id); -- Maya, Hari
-- 4. Median without percentile_cont
SELECT round(avg(amount), 2) AS median FROM (
SELECT amount, row_number() OVER (ORDER BY amount) AS rn, count(*) OVER () AS n FROM expenses
) t
WHERE rn IN ((n + 1) / 2, (n + 2) / 2); -- 1750.00 (same as percentile_cont(0.5))
-- 5. Users who spent more in November than the person who referred them
WITH nov AS (
SELECT user_id, sum(amount) AS total FROM expenses WHERE spent_on >= '2026-11-01' GROUP BY user_id
)
SELECT u.name, n1.total AS their_nov, r.name AS referrer, n2.total AS referrer_nov
FROM users u
JOIN users r ON r.id = u.referred_by
JOIN nov n1 ON n1.user_id = u.id
JOIN nov n2 ON n2.user_id = r.id
WHERE n1.total > n2.total;
-- Ravi 11700 > Asha 7100 | Sita 11950 > Asha 7100
-- 7. Difference from the previous expense of the same user
SELECT user_id, spent_on, amount,
amount - lag(amount) OVER (PARTITION BY user_id ORDER BY spent_on) AS change
FROM expenses WHERE user_id = 4 ORDER BY spent_on;
-- 8. Swap values in one UPDATE
BEGIN;
UPDATE bills SET paid = NOT paid RETURNING title, paid;
ROLLBACK;
-- 10a. Users who spent in EVERY top-level category that has expenses directly or via children
SELECT u.name
FROM users u
JOIN expenses e ON e.user_id = u.id
JOIN categories c ON c.id = e.category_id
GROUP BY u.name
HAVING count(DISTINCT COALESCE(c.parent_id, c.id)) =
(SELECT count(DISTINCT COALESCE(c2.parent_id, c2.id)) FROM expenses e2 JOIN categories c2 ON c2.id = e2.category_id);
-- Asha, Bikash, Ravi (Sita never spent on Entertainment)
-- 10b. Users who bought BOTH groceries (7) AND entertainment (5)
SELECT user_id FROM expenses
GROUP BY user_id
HAVING bool_or(category_id = 7) AND bool_or(category_id = 5)
ORDER BY user_id; -- 1, 2, 4