SQL interview · guide
SQL interview questions for data analysts, with answers
These questions come up again and again in analyst screens. Practise saying the answer in one or two sentences, then show the query.
Fundamentals
- WHERE vs HAVING? WHERE filters rows before grouping; HAVING filters groups after aggregation.
- INNER vs LEFT JOIN? INNER keeps matches only; LEFT keeps every left row and fills NULL where nothing matches.
- COUNT(*) vs COUNT(column)? COUNT(*) counts rows; COUNT(column) skips NULLs.
- What does GROUP BY do? Collapses rows into one per group so you can aggregate.
- NULL behaviour? NULL is unknown: NULL = NULL is not true. Use IS NULL, and COALESCE to replace it.
Intermediate
- Top N per group? ROW_NUMBER() OVER (PARTITION BY group ORDER BY value DESC), then filter rn <= N.
- Running total? SUM(x) OVER (ORDER BY date).
- Month over month change? value - LAG(value) OVER (ORDER BY month).
- Find duplicates? GROUP BY the key and HAVING COUNT(*) > 1.
- CTE vs subquery? A CTE names a step for readability and reuse; results are equivalent for simple cases.
Analytics-flavoured
- Retention or cohort query? Assign each user a first-activity month, join back to activity, and count users per month offset.
- Conditional totals? SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), also called pivoting with conditional sums.
How to answer well
- Restate the question and ask about ties, NULLs and the grain of the table.
- Write the simple version first, then improve it.
- Say how you would check the result, for example by comparing totals.