Reading preferences
Concept

Asking Questions with Subqueries

Use an inner query to compare each book with the average known page count.

database, sql, postgresql, subquery, average, nulls

One question inside another

A subquery is a query inside another SQL expression or query. Here the inner query finds the average page count, and the outer query finds books above that average. This scalar subquery returns one value because AVG without GROUP BY produces one aggregate row.

SQL illustration

Use the fictional authors and books setup in the same session:

SELECT id, title, pages
FROM books
WHERE pages > (SELECT AVG(pages) FROM books)
ORDER BY id;

Prepared result — not live execution:

idtitlepages
3Tide200

The known counts are 120, 200, and 120: their average is 440 / 3, about 146.67. Tide's 200 is greater; Kite and Fern's 120 are not. Oak's NULL does not contribute to the average, and its own comparison is unknown. The query compares against the unrounded average; 146.67 is only a readable approximation.

See the reasoning

Follow the example one step at a time

Use the inner average to evaluate the outer condition. This is a prepared teaching demonstration, not live code execution.

Gather known page counts

books.pages
120, NULL, 200, 120
          ↓ AVG ignores NULL
120 + 200 + 120 = 440

The three known values sum to 440. The missing value is not included in the average.

Subquery boundaries

If there are no non-NULL page counts, AVG returns NULL and this comparison does not select any row. A scalar subquery returning more than one row raises an error; zero rows yield NULL. Other subquery forms, including EXISTS and IN, answer different questions and have their own NULL behaviour. A correlated subquery refers to an outer row; this one does not. The visual is a way to reason about the result, not a guarantee of how the database executes the query.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does the inner query calculate?
2. Which book is above the average known page count in this data?
3. Why is Oak not returned?
4. What if there are no non-NULL page counts?

References and further reading