SQL Subquery Interview Questions
Subqueries let one query use the result of another. Interviewers use them to check that you can break a problem into steps, like finding the average first and then the rows above it.
Several questions here can also be solved with joins or window functions. Comparing approaches is a good way to prepare for follow-up questions.
Patterns to know
- Comparing each row to an overall value, such as the average
- Second highest value and other single-value lookups
- IN vs EXISTS, and the NULL trap in NOT IN
- Correlated subqueries that compare a row to its own group
- Subqueries in FROM to aggregate an aggregate
Easy questions
Medium questions
- Medium Top 3 Salaries per Department Identify Top 3 Earners per Department Premium
- Medium Nth Purchase per Customer Find Customer's Third Purchase Premium
- Medium Longest Consecutive Login Streak Daily Active User Streaks Premium
- Medium Compare to the Previous Row With LAG Compare Sales to Previous Day Premium
- Medium Find Missing IDs in a Sequence Detect Missing Order IDs Premium
- Medium 90th Percentile Salary Calculate 90th Percentile Salary Free
- Medium 7-Day Moving Average 7-Day Moving Average of Sales Premium
- Medium Cumulative Sum Over Time Cumulative Student Enrollment Growth Premium
- Medium Select Every Other Row Select Every Other Row Premium
- Medium Rows Above Their Group Average Above-Average Track Length per Album Premium
- Medium Best Seller per Category Best Seller in Each Category Premium
- Medium EXISTS vs IN Find Customers With Recent Orders Free
Hard questions
- Hard Monthly User Retention Rate Calculate Monthly Retention Rate Premium
- Hard Year-over-Year Revenue Growth Year-Over-Year Revenue Growth Analysis Premium
- Hard Median Without a MEDIAN Function Department Salary Median (No MEDIAN Function) Premium
- Hard Org Chart Hierarchy With a Recursive CTE Full Organizational Hierarchy Depth Premium
- Hard Longest Winning Streak Longest Winning Streak in Games Premium
- Hard Compound Annual Growth Rate (CAGR) Calculate CAGR (Compound Annual Growth Rate) Premium
- Hard User Session Duration Calculate User Session Duration Premium
- Hard Cohort Retention Analysis Monthly Signup Cohort Retention Premium
- Hard Cumulative Distribution Cumulative Salary Distribution Premium
- Hard Consecutive Increases (Gaps and Islands) Detect Consecutive Price Increases Premium
- Hard Business Metrics in One Query Multi-Metric Executive Dashboard Premium
- Hard Fibonacci With a Recursive CTE Generate Fibonacci Sequence with SQL Premium