Recognize a problem, then compose a solution
Interview questions often combine a few operations across different grains. The wording map suggests a starting point; the worked lessons show why the stages are needed and where a plausible shortcut breaks.
Technique map
Use this when the problem sounds familiar but the SQL shape does not come back immediately. Start from the problem shape, then open the page that owns the detailed explanation.
Pick the right row
| Problem shape | Technique | Building blocks | Detailed page |
|---|---|---|---|
| latest / earliest row per entity | Latest-per-group | ROW_NUMBER → filter rn = 1 |
Duplicates & latest records |
| exactly top N rows per group | Top-N per group | ROW_NUMBER + outer filter |
Ranking |
| top N distinct values / levels | Tie-preserving ranking | DENSE_RANK + outer filter |
Ranking |
| previous / next observed value | Neighbor comparison | LAG / LEAD |
LAG & LEAD |
Sequences & events
| Problem shape | Technique | Building blocks | Detailed page |
|---|---|---|---|
| consecutive dates / streaks | Gaps & Islands | deduplicate → ROW_NUMBER → stable island key |
Gaps & Islands |
| new session after inactivity | Sessionization | LAG → boundary flag → cumulative SUM |
Sessions & state changes |
| runs of the same state | State-change islands | LAG → changed flag → cumulative SUM |
Sessions & state changes |
| view → cart → purchase | Ordered funnel | stage timestamps / ordered existence checks | Ordered funnels |
| first event followed by a later event | First → later | first-event CTE → later join / EXISTS |
Ordered funnels |
Time & periods
| Problem shape | Technique | Building blocks | Detailed page |
|---|---|---|---|
| month-over-month / year-over-year change | Period comparison | aggregate to period → LAG |
Period changes |
| missing dates must appear | Calendar spine | generate dates → aggregate facts → LEFT JOIN |
Retention & missing dates |
| running / cumulative metric | Running window | aggregate if needed → SUM OVER + frame |
Running calculations |
| last N observations / days | Moving window | ROWS or time-aware RANGE |
Window frames |
Existence & sets
| Problem shape | Technique | Building blocks | Detailed page |
|---|---|---|---|
| at least one related row | Semi-join | correlated EXISTS |
EXISTS, IN, ANY & ALL |
| no related row | Anti-join | NOT EXISTS |
EXISTS, IN, ANY & ALL |
| every required item | Relational division | double NOT EXISTS or constrained HAVING COUNT(DISTINCT ...) |
Set operations & all-item matches |
| every entity × category/date pair | Expected combinations | CROSS JOIN → LEFT JOIN |
Joins & row multiplication |
Metrics & comparisons
| Problem shape | Technique | Building blocks | Detailed page |
|---|---|---|---|
| categories become columns | Conditional pivot | SUM(CASE ...) / conditional aggregates |
Conditional aggregation & pivots |
| percentage / conversion rate | Population-first rate | align numerator + denominator grain | Rates & populations |
| combine group rates | Weighted average | sum weighted numerators / denominators | Rates & populations |
| median / p95 / threshold | Ordered-set percentile | PERCENTILE_CONT / DISC ... WITHIN GROUP |
Percentiles & thresholds |
| quartiles / deciles | Equal-row buckets | NTILE(n) OVER (...) |
Window distributions |
| overlapping bookings / ranges | Interval overlap | self join + overlap condition | Interval overlaps |
High-value composition patterns
Aggregate → window
Use whenever a comparison should happen after reducing data to the reporting grain.
Swipe or scroll sideways to read the full diagram.
Examples: MoM revenue, rank stores by total visits, percentage of total, cumulative monthly sales.
LAG → arithmetic
For current value x_t x_t and previous value x_{t-1} x_{t-1} :
\text{absolute change}=x_t-x_{t-1} \text{change (\%)}=100\times\frac{x_t-x_{t-1}}{x_{t-1}} Percentage change is undefined when the previous value is zero. Protect that denominator in SQL with NULLIF.
LAG → flag → cumulative SUM
Swipe or scroll sideways to read the full diagram.
- Ordered events
- LAG: previous event or state
- CASE: mark each boundary
- Cumulative SUM of boundaries
- Session, island, or run ID
Use for sessions, state changes, event runs, and many gaps-and-islands problems.
ROW_NUMBER → filter
Swipe or scroll sideways to read the full diagram.
- Partition by business key
- Order by preferred survivor
- Assign ROW_NUMBER
- Keep rn = 1
Use for latest records and deterministic deduplication.
Calendar → LEFT JOIN
Swipe or scroll sideways to read the full diagram.
- Generate expected dates
- Aggregate observed data
- LEFT JOIN on the date
- Fill zero only when appropriate
Needed when “no row” must appear explicitly as a date with zero activity.
CROSS JOIN → LEFT JOIN
Swipe or scroll sideways to read the full diagram.
- Expected entities
- CROSS JOIN expected categories or dates
- LEFT JOIN observations
Use for students × subjects, stores × days, customers × months.
First event → later event
Swipe or scroll sideways to read the full diagram.
- MIN(event_time) per entity
- Establish first-event attributes
- Find events after first_time
Useful for first purchase, repeat purchase, activation, campaign follow-up, and retention questions.
Percentile decision map
| Question | Use |
|---|---|
| “What is the p95 threshold?” | PERCENTILE_CONT(0.95) WITHIN GROUP |
| “Give an actual observed value at the percentile” | PERCENTILE_DISC |
| “Where does each row rank from 0–1?” | PERCENT_RANK() |
| “What fraction is at or below this row?” | CUME_DIST() |
| “Split rows into 10 groups” | NTILE(10) |
In this chapter
- Duplicates & latest recordsFind repeated business keys and choose one version deterministically.
- Gaps & Islands: consecutive days & streaksGroup runs using deduplicated dates and row numbers.
- Sessions & changes in stateTurn boundary flags into groups with a cumulative sum.
- Retention & missing datesDefine observation windows and construct complete calendars.
- Conditional aggregation & pivotsTurn category values into columns without losing the intended grain.
- Interval overlapsDetect overlapping ranges while avoiding self-pairs and mirrored duplicates.
- Ordered funnelsRequire the right sequence of events instead of merely counting users with each event.
- Period changes and missing monthsAggregate to calendar grain before LAG, and make missing periods explicit.
- Rates, populations, and weighted averagesDefine numerator and denominator at the same grain before dividing.
Practice without the label
Hide the technique column and read only the problem shape. Sketch the transformation sequence you would use, then open the linked lesson and compare where your approach differs.