Subqueries
SQL Subquery Interview Questions
A subquery is a query inside another one, used when a question needs two steps: work something out first, then use it. A CTE is the same idea written so the query can be read from top to bottom instead of inside out.
What subquery questions ask you to do
Across the questions here, these are the shapes that come up:
- Compare each row against an overall figure such as the average
- Find rows whose key does not appear in another table
- Filter on a value that has to be calculated first
- Break a two-step question into two readable steps
Common mistakes with subqueries
Asking for rows that are NOT IN a list containing a single empty value returns nothing at all. Not an error, just an empty result, because nothing can be shown to differ from an unknown. Phrasing it as NOT EXISTS instead does what was meant and is safe against empty values.
Questions to practice
Roles this comes up in
Companies these come from
Other topics
- Filtering7
- Logical operators4
- Calculations11
- Conditional logic12
- NULL handling9
- Dates16
- Joins15
- Aggregations14
- Window functions32
- Reshaping15
- Arrays6
- Strings11
- Hashing8
- Two pointers4
- Sliding window1
- Binary search4
- Sorting1
- Math3
- Lists5
- Tuples3
- Dictionaries3
- Ranking16
- Running totals10
- Deduplication2
- Chunking1
- Similarity1
- Token budget2
- Parsing4
- Backoff3
- Agent loop1
- Cost1