Advanced SQL Interview Questions
Advanced SQL Interview Questions
Senior and staff data engineer SQL interview problems including recursive CTEs, skew handling, and EXPLAIN reading.
The senior-and-up subset of the data engineer SQL questions. Recursive CTEs for hierarchies and graphs. Gap-and-island for streak detection. Sessionization with LAG and SUM OVER. SCD2 half-open joins. EXPLAIN plan reading. Skew handling with salt-and-rebalance. Idempotent MERGE patterns for late-arriving data.
Advanced SQL in 2026 data engineer interviews means the 7 patterns that mid-level loops mostly skip and senior-plus loops live in. Recursive CTEs for org-chart and graph traversal use an anchor (WHERE id equals root) and a recursive clause (JOIN cte ON cte.id equals child.parent_id) with a depth column carried forward to bound recursion at 20 levels. Real HR data sometimes has cycles from bad data entry; the depth guard matters in production, not just in the interview. Gap-and-island for streak detection uses the trick of date minus ROW_NUMBER OVER (PARTITION BY user ORDER BY date), multiplied by INTERVAL 1 day; runs of consecutive dates produce a constant difference, so GROUP BY user and streak_key with HAVING COUNT greater-than-or-equal-to N detects streaks of length N or more. Sessionization with explicit gap thresholds uses LAG to get the previous event timestamp, CASE WHEN gap exceeds 30 minutes THEN 1 ELSE 0 AS new_session, SUM OVER ORDER BY ts to accumulate the session_id.
SCD2 half-open joins use effective_from less-than-or-equal-to event_time AND (effective_to IS NULL OR event_time less-than effective_to). The half-open interval prevents boundary doubling at the changeover microsecond when a dimension row's effective_to equals the next row's effective_from. The closed-interval mistake doubles facts; the open-interval mistake drops them. EXPLAIN plan reading at L5 and above asks the data engineer to identify sequential scan versus index seek, explain why a function in WHERE prevents predicate pushdown (WHERE DATE(timestamp) equals '2026-05-27' blocks the partition pruner; rewrite as WHERE timestamp greater-than-or-equal-to '2026-05-27' AND timestamp less-than '2026-05-28'), identify partition pruning and column-store implications, and explain hash join versus sort-merge join versus nested loop selection.
Skew handling for hot keys is a senior data engineer signal. Identify hot keys with SELECT join_key, COUNT(*) FROM table GROUP BY join_key ORDER BY 2 DESC LIMIT 20. If the top key has 10 times the median count, salt: append a mod-N suffix to the hot key on both sides (CONCAT(key, '_', user_id mod 8)), join on the salted key, aggregate by salted key, then strip the salt and re-aggregate. Trade-off is N-fold replication of the small side plus an extra aggregation pass versus the original one-task-doing-all-work bottleneck. In Spark this is AQE skew-join optimization done automatically; in SQL warehouses (Snowflake, BigQuery, Redshift) the data engineer does it manually or via clustering / micro-partition decisions.
Idempotent MERGE for late-arriving reconciliation is the L5-plus design-and-code question. MERGE INTO daily_revenue d USING (SELECT DATE(event_at) AS revenue_date, SUM(amount) AS revenue FROM events WHERE processed_at greater-than-or-equal-to since GROUP BY 1) src ON d.revenue_date equals src.revenue_date WHEN MATCHED THEN UPDATE SET revenue equals d.revenue plus src.revenue WHEN NOT MATCHED THEN INSERT VALUES (src.revenue_date, src.revenue). The principle is ADD, not REPLACE. Late events for an old date correct yesterday's total instead of overwriting it. Replacing is the silent-bug failure mode interviewers fish for.
- What is the recursive CTE pattern for an org chart?
- Anchor: SELECT id, name, 0 AS depth FROM employees WHERE id equals root_id. Recursive: SELECT e.id, e.name, cte.depth plus 1 FROM employees e JOIN cte ON e.manager_id equals cte.id WHERE cte.depth less-than 20. The depth column bounds the recursion and lets a data engineer answer the natural follow-up about org depth. Real HR data sometimes has cycles from bad data entry; the depth guard matters in production.
- How does the gap-and-island pattern work?
- For each user, take the activity date and subtract ROW_NUMBER OVER (PARTITION BY user ORDER BY date) multiplied by INTERVAL 1 day. Runs of consecutive dates produce a constant difference; runs separated by gaps produce different differences. GROUP BY (user, date minus rn times interval) and HAVING COUNT(*) greater-than-or-equal-to N detects streaks of length N or more. The trick generalizes to consecutive integers (date minus rn produces a constant) and to detecting groups by any monotonic sequence.
- What is the SCD2 half-open join and why does it matter?
- Joining a fact at event_time to a SCD Type 2 dimension uses ON dim.entity_id equals fact.entity_id AND dim.effective_from less-than-or-equal-to fact.event_time AND (dim.effective_to IS NULL OR fact.event_time less-than dim.effective_to). The half-open (less-than-or-equal on the left, strict less-than on the right) prevents two dim rows from matching at the exact changeover microsecond. The closed-interval mistake doubles facts at the boundary; the open-interval mistake drops facts at the boundary.
- How does a data engineer handle skew in a SQL JOIN?
- Identify the hot key with SELECT join_key, COUNT(*) FROM table GROUP BY join_key ORDER BY 2 DESC LIMIT 20. If the top key has 10 times the median count, salt both sides: append a mod-N suffix to the hot key (CONCAT(key, '_', user_id mod 8)), join, aggregate by the salted key, then unsalt and re-aggregate. Trade-off is extra shuffle cost (N-fold replication of the small side) versus balanced executor workload. In Spark this is AQE skew-join automatic; in SQL warehouses the data engineer does it manually.
- When does a function in WHERE prevent predicate pushdown?
- Whenever the function wraps the indexed column. WHERE DATE(event_ts) equals '2026-05-27' prevents the partition pruner from using the event_ts index because the optimizer cannot reason about DATE() in reverse. The fix is to invert: WHERE event_ts greater-than-or-equal-to '2026-05-27' AND event_ts less-than '2026-05-28'. Same applies to UPPER(name), CAST(id AS string), and any user-defined function on an indexed column.
- What is an idempotent MERGE for late-arriving data?
- MERGE INTO daily_revenue d USING (SELECT DATE(event_at) AS date, SUM(amount) AS revenue FROM events WHERE processed_at greater-than-or-equal-to since GROUP BY date) src ON d.date equals src.date WHEN MATCHED THEN UPDATE SET revenue equals d.revenue plus src.revenue WHEN NOT MATCHED THEN INSERT VALUES (src.date, src.revenue). The key is ADD, not REPLACE. Late events for an old date correct the existing total instead of overwriting it. Data engineer interviewers check whether you spot this; replacing is a silent bug.
- What is QUALIFY and which engines support it?
- QUALIFY filters the result of a window function the way HAVING filters the result of a GROUP BY. Native in Snowflake, BigQuery, and Teradata. Not in Postgres, MySQL, or SQL Server. On those engines, wrap the window in a CTE and filter in the outer SELECT. QUALIFY is a data engineer fluency signal in Snowflake and BigQuery interviews; mention it when you reach for the CTE-then-filter pattern.
133 practice problems matching this filter. Difficulty: medium (50), hard (65), easy (18).
SQL (133)
- 7-Check Rolling Average - medium - Seven entries hold the trend.
- 7-Day Onboarding Conversion - hard - Signed up Monday. Still here by Sunday?
- 7-Day Token Retention - medium - Premium tokens, day by day.
- Above Average Interactions - easy - The average user is boring. Who is above?
- Above Category Average - easy - The category average is one thing. These beat it.
- Active User Penetration Rate - hard - How much of the user base is actually alive?
- Against the Clock - easy - Promised by noon. Delivered at midnight.
- Age of Discovery - hard - Every generation searches differently. See who finds what they came for.
- Alert Severity - medium - When the alarms go off, who screams loudest?
- App Stability by Region - medium - Some regions crash more than others.
- Back From the Brink - hard - Roll it back, then nail the next one.
- Before the Rush - easy - The holidays are coming. See where each category's money moves, month by month.
- Below the Peaks - hard - The biggest bills catch every eye. The overspend hiding just beneath them does not.
- Best Day for Ad Revenue - medium - Some days of the month convert far better than others.
- Cache Efficiency - hard - Some edges run hot. Others coast on the global average.
- Campaign Bookend Engagement - hard - First impression versus last. The gap.
- Campaign Conversion Window - hard - A narrow window between impression and action.
- Chain of Command - hard - The tree runs deep. Trace every branch back to the top.
- Cheapest CDN Route - easy - The cheapest path across regions.
- Competing Standards - hard - Every framework has a star model.
- Consecutive Cost Growth Periods - hard - Five straight months of spending increases.
- Cost Efficiency Variance - hard - Cost efficiency varies. By how much?
- Crossed Signals - hard - No shared key, only a shared clock.
- Department Running Totals - medium - Compute cumulative metric values within each department using window operations.
- Deploy Velocity - medium - Days between deploys. Some services ship fast, others crawl.
- Deploy Velocity Swings - medium - Month to month, who sped up and who stalled.
- Double or Nothing - hard - Same shelf, wildly different stickers. Spot the pricing gaps.
- Even the Silent Ones - medium - The quietest accounts still belong in the numbers.
- Experiment Impact - hard - Which experiments moved the needle? Settle the standings inside every variant.
- Extreme Category Totals - medium - The highest and the lowest. Both are interesting.
- Fastest Page View to Click - hard - How fast from view to click?
- Fault Lines - medium - Errors by day and region. Some areas are worse than they appear.
- Feature Flag Engagement Impact - hard - Flags on versus flags off. The engagement gap.
- First Arrivals - medium - Every customer has a first day. Find when the crowds showed up.
- First Interaction Credit - hard - Attribute transactions to earliest touchpoint
- First Light - medium - Every repo has a scrappy stretch before its first green build. See who was shipping then, and how big their changes were.
- Ghost Products - medium - Listed but never sold. The shelves collect dust.
- Heavy Ad Exposure - medium - Saturated with ads. Is it too much?
- Honeymoon Phase - medium - Every signup class starts hot. Which ones spend the year they arrive?
- Idle Team Members - easy - Sprint started. Some people never got assigned.
- Keep Most Recent Record - medium - Carbon copies clutter the table. Only the latest matters.
- Kings for a Day - medium - Every day, one job moves more rows than all the rest.
- Largest Group - easy - One group towers above the rest.
- Latest Commit Build Cost - medium - The latest commit came with a build cost.
- Loaded Dice - hard - Every flag's rollout is a bet. Map the odds from longest shot to favorite.
- Longest Gap Between Token Events - medium - The longest gap between token events.
- Longest Uptime Streak - hard - Pass, pass, pass. How long until fail?
- Long Messages - medium - Some commit messages tell a novel.
- Losing Altitude - hard - Two months apart, the same campaigns. Find the ones that slipped.
- Love and Loathing - hard - Some teams champion the flag. Others would kill it.
- Market Share - hard - Every category wants a bigger slice.
- Max Value Per Location - easy - Every location has a peak.
- Median Failure Rate by Table - hard - Half the tables fail more than this.
- Median Model Accuracy - hard - The median accuracy. Not the mean.
- Metric Range Per Group - easy - The spread within each group.
- Minimum Parallel Workers - hard - Too few workers and it stalls.
- Monthly Running Total - medium - Cumulative sales per product across months.
- Normalization Tradeoffs in Practice - hard - Clean data or fast queries? You can't always have both.
- Nth Highest Salary Per Department - medium - Third place in every department.
- One Year to the Next - hard - This year versus last year. Growing or shrinking?
- Only Here - hard - Exclusive to one source. Missing from the other.
- Peak Company - hard - Every token lived among others. Find the moment the crowd was largest.
- Quarters Apart - hard - Latency trending up or down? The quarters have the answer.
- Radio Silence - hard - Some codebases stop speaking for too long.
- Rapid Retry Detection - medium - Detect retried API calls within 5 minutes of failure.
- Recent Price Drops - medium - The price just dropped. Who noticed?
- Repeat Purchases Within a Week - medium - They bought again within seven days.
- Response Buckets - medium - Fast, normal, or slow. Every API call gets a verdict.
- Retried Failed API Calls - medium - Spot users who retry API calls within 5 minutes of a failure.
- Rolling Revenue Average - hard - Smooth out the revenue bumps. The trend matters more.
- Rooms in Common - hard - Two people, one channel, a connection you never counted.
- Same First and Last Reply Target - medium - They started and ended the month messaging the same person.
- Second Purchase - medium - The first buy is curiosity. The second is commitment.
- Service Uptime Minutes - medium - Status changed. How long was it actually up?
- Session Page View Distance - hard - Page view distance per session.
- Six Degrees - hard - Every reply ties two names together. Find whose web reaches the furthest.
- Smooth Latency - medium - Noisy latency readings, smoothed into a trend you can trust.
- Speed and Substance - hard - When a run takes longer, is it moving more rows or just stalling?
- Spend and Rank - hard - Five thrones at the top of the spending leaderboard.
- Spending Range - hard - Between the smallest purchase and the biggest lies the story.
- Spending Velocity - medium - Fraud hides in the pace, not the price. Watch each customer's last seven purchases roll forward.
- Successful Call Volume per Endpoint - medium - Not every ping is honest.
- Team Cost Allocation Comparison - hard - Individual spend versus team average.
- The Address That Changed - hard - Addresses change. History must not be erased.
- The Blind Spot - medium - Pages they haven't discovered yet.
- The Budget Line - easy - Some rows are over. Some are under. Label every one.
- The Cannibalization Report - hard - The new product launched. The old one suffered.
- The Clean Aisle Numbers - medium - Clear the noise. What did each category actually earn?
- The Comfortable Middle - hard - Above average but not extreme.
- The Company You Keep - medium - Only experiments with a crowd count. Find the Friday sessions they drove.
- The Conversion Story - medium - Signups are one thing. Paid purchases are another. Find the gap by source.
- The Crowded Hour - easy - Every device type has a moment when the room is fullest. Find it.
- The Crown Jewels - easy - Revenue crowns the winners. Who sold the most?
- The Fault Lines - medium - Some account groups hit far more errors than others. Surface the ones that break most.
- The Final Sale - medium - Every product has a last sale. When was it?
- The Freshest Record - medium - Duplicates everywhere. Only the most recent version of the truth survives.
- The Full Picture - easy - Two tables know different things about the same people. Combine them.
- The Gap Between Neighbors - hard - Same region, and still they disagree.
- The Ground We Keep - hard - Every region is a claim once made. Measure how much of it endures.
- The Holdouts - medium - Subscribed. But never upgraded.
- The Long Way Back - hard - Some services fell apart and clawed their way back. Find them, and measure the climb.
- Then and Now - hard - Accuracy used to be higher.
- The Notification That Paid Off - hard - The message went out to thousands. A smaller number actually bit.
- The Path Not Taken - hard - Some found the new path without ever walking the old one.
- The Roster - easy - Every department, counted head by head.
- The Shape of a User - medium - Every user leaves a trail of events. The report needs them lined up side by side.
- The Space Between Us - hard - Every viewer lives inside a world of campaigns. Measure how much two of those worlds are really one.
- The Standings - medium - Every category earns its place on the board. Find where each one lands.
- The Subscription Ghost - medium - Some charges come back to haunt the same card a month later.
- The Upper Rungs - easy - The top rungs set the ceiling for everyone below.
- The Vote Tally - hard - One product, every day it sold, and the money it brought in.
- The Weight of a Click - hard - Where users actually spend their attention.
- The Weight of Giants - medium - In every sky, only two hold the throne.
- Tiers of Want - hard - In each category, some carts weigh more than others. Sort the shoppers by what they spend.
- Tipping Points - hard - A service's health is a story told in how it turns. Find every turn.
- Top Average By Region - easy - Region by region, who pulls the best average?
- Top Campaign by User Revenue - medium - Which campaign made each user spend the most?
- Top Commit Authors by Repo - hard - Three authors per repo. The top committers.
- Top CPU Pods per Namespace - hard - The two most CPU-hungry pods in each namespace.
- Top Endpoint by Power Users - hard - Power users have a favorite endpoint.
- Top Lessons Each Month - medium - Rank items within time periods and keep top 3
- Top Percentile API Tokens - hard - The most suspicious tokens.
- Top Percentile Spenders - medium - Top 1% of users by total spend via percentile bucketing.
- Top Recent Sellers - easy - Fresh data, top sellers. The recent leaderboard.
- Top Regions by High CPU Nodes - hard - Five regions with the hottest CPUs.
- Two Sides of the Ledger - hard - Two cost tables, one region. Which way does the balance tip?
- Unique Hostnames per Region - medium - How many distinct machines live in each region?
- User 360 - hard - One row per user. Everything they did, or didn't do.
- Weekly Build Status Report - hard - Every CI run, bucketed by week.
- Where the Bill Settles - hard - When a handful of giant charges skew the average, the middle tells the truth.
- Where the Minutes Go - hard - Attention piles up device by device. Find where it pools.
- Where The Rows Go - easy - Every run loses a little on the way. Measure what makes it through.
- Who Stayed - hard - Day after day after day. Who kept coming back?