SQL round
SQL is the one round almost every DE loop has. It's rarely about obscure syntax. It's about getting the right answer on messy data and explaining why it's right.
Format
Usually 45–60 minutes in a shared editor, sometimes with a real database, often without. Expect 2–4 questions that get harder, with follow-ups like "now make it incremental" or "what if this table has duplicates?". Practice on the playground so you can run things. In the real round, you may have to reason without running.
A method that works for every question
- Restate the output. Columns, one row per what, sort order. "So one row per customer, with their first and second order dates, ordered by customer?"
- Ask about the data. Can keys repeat? Can values be NULL? Are timestamps in one time zone? Can events arrive late? Ties?
- Plan in steps, out loud. "First dedup, then aggregate per day, then the window." Each step becomes a CTE.
- Write it with CTEs. One idea per CTE, named for what it holds (
latest_txns,daily_revenue). - Check edge cases. Walk through a NULL, a duplicate, a tie and an empty group. Fix before the interviewer asks.
- Talk about scale if there's time. Indexes or clustering, what's expensive, how you'd compute it incrementally.
The patterns
Most SQL questions are one of these patterns, or two combined. Each links to practice questions.
| Pattern | Core idea | Practice |
|---|---|---|
| Top-N per group | ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) then filter | |
| Deduplication | Number copies by a rule, keep 1 | |
| Running totals, moving averages | Window SUM/AVG with an explicit frame | |
| Gaps and islands | Row-number difference labels runs | |
| Sessionization | Flag starts with LAG, cumulative-sum the flags | |
| Retention and cohorts | Per-user flag first, then aggregate per cohort | |
| Funnels | Carry each step's timestamp forward | |
| Pivot | Conditional aggregation (AVG(CASE …)) | |
| SCD Type 2 and point-in-time joins | LEAD to close versions; join on validity range | |
| Percentiles | PERCENTILE_CONT … WITHIN GROUP | |
| Self-joins and hierarchies | Alias the same table twice; recursive CTEs | |
| Anti-joins | NOT EXISTS, never NOT IN with NULLs | |
| Date spine | Generate every day, then left join | |
| Period over period | LAG over aggregated periods | |
| As-of / bitemporal | Latest row with ts <= cutoff; filter knowledge time first | |
| Fan-out bugs | Aggregate the child to the parent's grain before joining | |
| Interval overlap | a.start < b.end AND b.start < a.end |
The mistakes that fail candidates
NOT INwith a NULL in the subquery. It returns no rows. UseNOT EXISTS.COUNT(DISTINCT)to "dedup". It counts keys; it doesn't pick the right copy.- Joining before aggregating. One-to-many joins multiply rows and inflate sums and counts.
- Window frames by accident.
ORDER BYwithout a frame defaults toRANGE … CURRENT ROWin most engines. WriteROWS BETWEEN …when you mean rows. ELSE 0in a conditional average. It turns "not applicable" into zero.BETWEENon timestamps with a date upper bound. It misses most of the last day. Use>= start AND < next_start.- No tie-breaker.
ROW_NUMBERwithout a unique ordering gives different answers on different runs.
Dialects
Interviews usually accept any reasonable SQL, but know your target warehouse's quirks. See the dialect gotchas cheatsheet and the window functions cheatsheet. Questions in the bank include dialect notes with links to vendor docs.
Quick check
What's wrong with this query, which should list customers with no orders?
SELECT customer_id FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);
Show answer
If any orders.customer_id is NULL (guest checkouts, for example), NOT IN returns no rows at all. x NOT IN (…, NULL) is never true. Use NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id).
All SQL questions
- 7-day moving average of completed trips per city
- Build an SCD Type 2 table from a change log
- Cancellation rate, with and without a driver assigned
- Each category's share of total revenue
- Monthly chargeback rate on settled payments
- Customers who ordered in every month of Q4
- Customers who never placed an order
- Days between a customer's first and second order
- Deduplicate replayed transactions
- Choose a distribution key by measuring skew
- Three-step page funnel with step-to-step conversion
- Employees who earn more than their manager
- Check a month of feed files for missing, late and broken deliveries
- Validate a raw feed and count rejects by reason
- Daily EUR rate for January, filled forward over weekends
- Fix the inflated order count
- Flag days with abnormal trip volume
- Longest login streak per user
- Accounts with 3 or more failed transactions in a row
- Median and 90th percentile fare per city
- Month-end account balances (a semi-additive measure)
- Month-over-month revenue growth
- Daily revenue with a month-to-date running total
- Reporting depth and management path for every employee
- Drivers with overlapping trips
- Measure a data freshness SLA from ingestion timestamps
- Pivot ratings into driver and rider columns
- Revenue by the customer's country at order time vs today
- Rolling 28-day active users for each day of December
- Average session length by plan
- Sessionize page views with a 30-minute timeout
- Top 3 products by revenue in each category
- Reconstruct what the dashboard showed at a past moment
- Histogram of trip durations in 10-minute buckets
- Decide insert, update or unchanged for an incremental load
- Daily settled volume in USD using the latest FX rate
- Week-1 retention by weekly signup cohort
Further reading
- PostgreSQL: window functions tutorial: read this if
PARTITION BYversusGROUP BYstill feels fuzzy. - PostgreSQL: using EXPLAIN: read this before a round where you may be asked why a query is slow.