SQL · Queries that survive scale
What are subqueries and where can they appear?
Short answer
A subquery is a query nested inside another statement. It can return a scalar value, a list for IN, a table in FROM, or an existence check with EXISTS.
Subqueries let you compose a query from smaller parts. The shape of the result determines where it can be used: one row and one column is scalar, one column is a list, and a full table works in FROM or a join.
SELECT p.id, p.title, p.view_count
FROM posts p
WHERE p.author_id IN (
SELECT u.id
FROM users u
WHERE u.plan = 'pro'
)
AND p.view_count > (
SELECT AVG(view_count) FROM posts
);Subquery shapes
- Scalar subquery: returns one row and one column, usable where a value is expected
- Row or list subquery: used with IN, ANY, or ALL
- Derived table: a subquery in FROM that behaves like a temporary table
- Correlated subquery: references columns from the outer query
- EXISTS: checks whether the subquery returns any row
Many subqueries are rewritten by the optimizer into joins or semi-joins. That means a readable subquery is not automatically slower. Still, check the plan when the subquery is correlated or returns a large intermediate set.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a scalar subquery and a derived table?
- 2When does a scalar subquery fail at runtime?
- 3Does a subquery always run separately from the outer query?
- 4How do you decide between a subquery and a join?
Say it in the interview
A subquery is a query nested inside another statement. It can be scalar, return a list for IN, act as a derived table in FROM, or drive an EXISTS check. I choose the shape based on what the outer query needs. Modern optimizers often rewrite subqueries into joins, so I focus on clarity first and then verify the plan when the subquery is correlated or large.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.