SQL Problem-Solving Checklist (Interview Cheat Sheet)
1) Understand the question
• Identify output columns & metric (COUNT/SUM/AVG/RATIO/RANK/STREAK)
• Is the result per-group or global?
2) Restate in plain words
• Describe transforms, joins, and edge cases in one sentence.
3) Edge cases to check
• Missing rows → use LEFT JOIN + COALESCE
• Zero denominator → NULLIF(...,0)
• Date-range joins → BETWEEN start_date AND end_date
• Duplicates, NULLs, timezones
4) Plan steps / CTEs
• Preprocess (dedupe/filter)
• Compute base aggregates (per entity)
• Final aggregation and formatting
5) Common templates
Safe division: SUM(x)/NULLIF(SUM(y),0)
Null default: COALESCE(col,0)
Conditional agg: SUM(CASE WHEN cond THEN 1 ELSE 0 END)
Top-N per group: ROW_NUMBER() OVER (PARTITION BY grp ORDER BY metric DESC)
6) Testing tips
• Run with LIMIT to validate logic
• Manually walk through a small example
• Test edge cases explicitly
Quick code snippets
SUM(CASE WHEN cond THEN 1 ELSE 0 END) -- conditional count
COALESCE(col, 0) -- null -> default
SUM(x)/NULLIF(SUM(y),0) -- safe division
ROW_NUMBER() OVER (PARTITION BY g ORDER BY t) -- top-n per group
DATE_SUB(day, INTERVAL rn DAY) -- gaps & islands grouping