Subqueries
1410 min
A subquery is a query written in brackets inside another query. It runs first and hands its result to the outer query.
A subquery that returns one value
“Teachers who earn more than the average” — we do not know the average in advance, but the database can work it out:
The subquery returns one number, and the outer query compares against it.
A subquery that returns a list: IN
“Students who got at least one score of 95 or more”:
If a subquery returns several rows, use
IN, not=. With=the database complains that the subquery returns more than one row.
EXISTS — “is there any?”
EXISTS is true when the subquery returns at least one row. It usually refers to the outer row:
Products that have never been sold. SELECT 1 — what comes back does not matter, only whether anything does.
Correlated subqueries
The subquery uses a value from the outer row and runs again for every row. “Products more expensive than the average of their own category”:
A subquery in FROM
A result can be used like a temporary table. It must be given an alias:
Show name and credits of the subjects that have more credits than the average.
How many riders have taken at least one trip? Use IN or EXISTS.
Remember
- One value — compare with
=,>; a list — useIN. EXISTS/NOT EXISTScheck whether rows exist.- A subquery in
FROMneeds an alias.