SQL Subqueries: Queries Inside WHERE, IN and EXISTS
A subquery is a SELECT written inside another statement, in parentheses. It lets one query use the answer of another, such as "books priced above the average price", without you copying numbers by hand.
Scalar subqueries
A subquery that returns exactly one value, one row and one column, can be used anywhere a single value fits. WHERE price > (SELECT avg(price) FROM books) computes the average first (22.568 for our books) and compares every row with it. This solves the problem from the aggregates chapter, where WHERE price > avg(price) was not allowed.
IN with a subquery
A subquery that returns one column of many rows can feed IN. WHERE id IN (SELECT author_id FROM books WHERE genre = 'Fiction') finds authors who have written at least one Fiction book. Each author appears once, even though Aiko Tanaka and Daniel Okafor both have one Fiction title and Maya Lindqvist has one, because the outer query reads each author row only once. A join would produce one row per matching book and might need DISTINCT.
Expected output
title | price Northern Lights Code | 39.5 Small Data, Big Ideas | 34.99 Learning SQL by Doing | 29.0 Maps of Memory | 24.5 name Aiko Tanaka Daniel Okafor Maya Lindqvist name Lucas Meyer
EXISTS and correlated subqueries
EXISTS (subquery) is true if the subquery returns at least one row. In the last query, the subquery refers to c.id from the outer query, so it is re-evaluated for each customer: a correlated subquery. NOT EXISTS keeps the customers for whom no order exists. It gives the same answer as the LEFT JOIN ... IS NULL pattern from the previous chapter, and unlike NOT IN, it behaves sensibly when NULLs are involved. SELECT 1 is a convention: EXISTS only cares whether rows exist, not what they contain.
Common table expressions
When subqueries nest deeply, a common table expression (CTE) reads better. WITH gives a subquery a name, and the main query uses that name like a table:
WITH avg_price AS (SELECT avg(price) AS p FROM books) SELECT title FROM books, avg_price WHERE price > avg_price.p;
CTEs can be chained, one after another, so complex reports read from top to bottom.
Performance
Modern databases, SQLite included, often rewrite subqueries into joins internally, so choose the form that states the question most clearly. If a correlated subquery is slow on a large table, an index on the column it filters by, here orders.customer_id, usually fixes it.
Common mistakes
- A scalar subquery that returns several rows. SQLite quietly uses the first one; other databases raise an error.
NOT IN (subquery)when the subquery can returnNULL, which makes the whole condition unknown.- Forgetting the parentheses around the subquery.
Summary
- A scalar subquery returns one value and can be compared against.
IN (SELECT ...)filters by a list computed by another query.EXISTS/NOT EXISTStest whether related rows exist.WITHnames subqueries so complex queries stay readable.
Quiz: Subqueries