CoreTrail

Interview patterns

Recognize recurring problems and choose a reliable approach.

Chapter overview 9 min read
On this page

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.

Examples: MoM revenue, rank stores by total visits, percentage of total, cumulative monthly sales.

LAG → arithmetic

For current value x_t and previous value 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

Use for sessions, state changes, event runs, and many gaps-and-islands problems.

ROW_NUMBER → filter

  1. Partition by business key
  2. Order by preferred survivor
  3. Assign ROW_NUMBER
  4. Keep rn = 1

Use for latest records and deterministic deduplication.

Calendar → LEFT JOIN

  1. Generate expected dates
  2. Aggregate observed data
  3. LEFT JOIN on the date
  4. Fill zero only when appropriate

Needed when “no row” must appear explicitly as a date with zero activity.

CROSS JOIN → LEFT JOIN

Use for students × subjects, stores × days, customers × months.

First event → later event

  1. MIN(event_time) per entity
  2. Establish first-event attributes
  3. 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

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.

Type a concept, keyword, or function.