Subqueries

Lesson 12 of 20

A query inside a query — watch the engine run the inner SELECT first and feed its answer to the outer one.

The big picture

A query inside a query

Some questions cannot be answered in one flat WHERE — like "who earns more than the average?". The answer needs two queries, and SQL lets you nest one inside the other.

Nested queries

A subquery is a complete SELECT wrapped in parentheses, living inside another statement.

Inner runs first

The engine evaluates the innermost query, then hands its result up to the outer query.

One value or a list

A scalar subquery returns a single value usable like a number; IN ( ... ) consumes a whole list of values.

Readable questions

Who earns above average? is awkward in one WHERE but natural as two small queries.