Subqueries
Filter by a number or a list that another query works out.
Put a whole query in brackets inside WHERE. It runs first, and its answer is used.
Show the title of every book that has been borrowed at least once, using a list of book_ids from loans.
Run your query to see the result table.
Press the green Run button or Ctrl+Enter.
How (SELECT ...) works
1. The inner query runs first
SELECT AVG(pages) FROM books
AVG(pages) 312 2. Its answer goes into WHERE
SELECT title, pages FROM books WHERE pages > (312);
title pages Dracula 418 Emma 474 Dune 412
Change the books and the average changes with them. A typed-in 312 would not.
1. The inner query gives a list
SELECT book_id FROM loans
book_id 2 5 2 7 2. IN keeps rows whose id is in it
SELECT title FROM books WHERE book_id IN (2, 5, 7);
title Emma Carrie The Hobbit
What is a subquery?
A query in brackets inside another query. It runs first, and its answer is used by the outer query, like a cell that feeds a formula.
Where can a subquery go?
Where a value goes:
WHERE pages > (SELECT AVG(pages) FROM books). Where a list goes:WHERE book_id IN (SELECT book_id FROM loans). Or where a table goes, afterFROM.Why not type the number in?
A typed number is only right for today's data. The subquery works it out again every time the query runs.
Can a subquery give more than one value?
After
=or>it must give one row and one column. AfterINit can give a whole column.How is this like Excel?
Like
=FILTER(A2:B11, B2:B11 > AVERAGE(B2:B11)): theAVERAGEis worked out first, then each row is compared with it.
How other databases do it
The lessons run on SQLite. Most of SQL is the same everywhere; these are the places where this lesson's SQL differs.
| Database | How | Note |
|---|---|---|
| SQLite (these lessons) | Optional | The name can be left out, but give one anyway. |
| PostgreSQL | Optional | Required before PostgreSQL 16. |
| MySQL / MariaDB | Required | Every derived table must have its own alias. |
| SQL Server | Required | |
| Oracle | Optional | And write it without AS: FROM (SELECT ...) t. |
| Sybase ASE | Required |
Know someone fighting with a spreadsheet? Send them this page.