Subqueries

Updated · 8 min read
mediumPostgreSQL 18sqlsubqueriesderived-tablescalar-subqueryinterview

A subquery is a complete SELECT written inside another query, in parentheses, whose result the outer query uses. "Which courses cost more than average?" takes two steps: work out the average, then compare each course to it. A subquery does both in one statement: WHERE fee_usd > (SELECT avg(fee_usd) FROM courses). This lesson covers the three shapes a subquery can return (one value, one column of values, or a whole table), where each one goes, and the errors that tell you a subquery returned the wrong shape.

In One Minute

  • A subquery is a SELECT in parentheses, used inside another statement.
  • A scalar subquery returns one value and can go wherever a single value can: WHERE fee_usd > (SELECT avg(fee_usd) FROM courses).
  • A list subquery returns one column, used with IN: WHERE student_id IN (SELECT student_id FROM payments).
  • A table subquery (derived table) goes in FROM and acts like a temporary table.
  • The inner query runs first, conceptually; its result feeds the outer query.

Scalar Subqueries: One Value

A subquery that returns exactly one row and one column can stand in for a single value. Courses that cost more than the average fee:

SQL▶ Try it
SELECT title, fee_usd
FROM courses
WHERE fee_usd > (SELECT avg(fee_usd) FROM courses)
ORDER BY fee_usd DESC;
Output
       title       | fee_usd
-------------------+---------
 Java Collections  |  550.00
 Java OOP          |  500.00
 Java Basics       |  450.00
 JavaScript Basics |  450.00
(4 rows)

The inner query works out the average, $433.33, and the outer query compares each course with it. You could run the two steps by hand, but then the 433.33 would be typed into the query and go stale the day a fee changed. The subquery recomputes it every time.

The inner query returns 433.33; the outer query keeps the four courses above it

A scalar subquery works in the SELECT list too. How far is each payment from the average payment?

SQL▶ Try it
SELECT payment_id, amount_usd,
       round(amount_usd - (SELECT avg(amount_usd) FROM payments), 2) AS vs_average
FROM payments
ORDER BY payment_id;
Output
 payment_id | amount_usd | vs_average
------------+------------+------------
          1 |     450.00 |     142.86
          2 |     250.00 |     -57.14
          3 |     250.00 |     -57.14
          4 |     550.00 |     242.86
          5 |     200.00 |    -107.14
          6 |     225.00 |     -82.14
          7 |     225.00 |     -82.14
(7 rows)

If a scalar subquery returns more than one row, the query fails, because a single value can't be several values:

SQL▶ Try it
SELECT title
FROM courses
WHERE fee_usd = (SELECT fee_usd FROM courses WHERE technology = 'Java');
Output
ERROR:  more than one row returned by a subquery used as an expression

There are three Java courses, so three fees came back. If the subquery returns no rows, it counts as NULL, so a comparison with it matches nothing. When several values are expected, use IN.

List Subqueries: IN

A subquery that returns one column can feed IN. Students who have paid by check at least once:

SQL▶ Try it
SELECT first_name
FROM students
WHERE student_id IN (SELECT student_id FROM payments WHERE method = 'check')
ORDER BY student_id;
Output
 first_name
------------
 Srihitha
 Navika
(2 rows)

The inner query returns the student_id of each check payment (101 and 103), and IN keeps the students whose id is in that list. Duplicates in the list don't matter to IN.

Table Subqueries: Derived Tables

A subquery in FROM returns a whole table, called a derived table, that the outer query reads like any other. It lets you work in two steps: first summarize, then query the summary. What's the average total paid per paying student?

SQL▶ Try it
SELECT round(avg(t.total), 2) AS average_per_student
FROM (
  SELECT student_id, sum(amount_usd) AS total
  FROM payments
  GROUP BY student_id
) AS t;
Output
 average_per_student
---------------------
             1075.00
(1 row)

The inner query makes one row per paying student, with their total ($1,700.00 and $450.00); the outer query averages those totals. You can't write avg(sum(amount_usd)) directly, because aggregates can't be nested, so the derived table is the natural way to aggregate an aggregate. The derived table can be filtered too:

SQL▶ Try it
SELECT t.student_id, t.total
FROM (
  SELECT student_id, sum(amount_usd) AS total
  FROM payments
  GROUP BY student_id
) AS t
WHERE t.total > 500;
Output
 student_id |  total
------------+---------
        101 | 1700.00
(1 row)

That's the same answer HAVING gave in HAVING, written another way. Give derived tables an alias (AS t): PostgreSQL 16 and later allow it to be left out, but MySQL, SQL Server and older PostgreSQL versions require it, so always naming it keeps the query portable.

Seven payments become two student totals in the derived table t; the outer query averages them

Where Subqueries Can Go

ShapeReturnsTypical placeExample
ScalarOne valueWHERE, SELECT, HAVINGfee_usd > (SELECT avg(fee_usd) FROM courses)
ListOne columnIN, ANY, ALLstudent_id IN (SELECT student_id FROM payments)
TableRows and columnsFROMFROM (SELECT ...) AS t

Every subquery so far ran once, independently of the outer query. A subquery that uses a value from the outer row, and so runs once per row, is a correlated subquery, the subject of the next lesson. Common Table Expressions show a tidier way to write the derived tables in this lesson.

A single value in WHERE, a list for IN, and a table in FROM, each with a real example

Common Mistakes

A scalar subquery that returns several rows. It fails with more than one row returned by a subquery used as an expression. Use IN, or make the subquery return one row (an aggregate, or LIMIT 1 with ORDER BY).

NOT IN with a nullable column. One NULL empties the result. Use NOT EXISTS.

Nesting aggregates directly. avg(sum(...)) fails. Aggregate in a derived table, then aggregate again outside.

No alias on a derived table. Fine in recent PostgreSQL, an error elsewhere. Always add one.

Interview Corner

What is a subquery?

A SELECT statement nested inside another statement, in parentheses. Its result is used by the outer query as a single value, a list, or a table.

What is a derived table?

A subquery in the FROM clause. It returns a result set that the outer query reads like a table, and it's usually given an alias.

What happens if a scalar subquery returns more than one row? No rows?

More than one row is an error. No rows makes the subquery's value NULL.

Practice

Challenge: List the payments larger than the average payment, with their amount, sorted by payment_id.

Show solution
SQL▶ Try it
SELECT payment_id, amount_usd
FROM payments
WHERE amount_usd > (SELECT avg(amount_usd) FROM payments)
ORDER BY payment_id;
Output
 payment_id | amount_usd
------------+------------
          1 |     450.00
          4 |     550.00
(2 rows)

The average payment is about $307.14, and two payments are above it: Srihitha's $450.00 for Java Basics and $550.00 for Java Collections.

Quick check: Subqueries

3 questions
1Where can a subquery that returns one value go?
2WHERE fee_usd = (SELECT fee_usd FROM courses WHERE technology = 'Java') fails. Why?
3How do you average each student's total payments?

Key Takeaways

You want toWrite
Compare with a computed valueWHERE fee_usd > (SELECT avg(fee_usd) FROM courses)
Match against a listWHERE student_id IN (SELECT student_id FROM payments)
Query a summaryFROM (SELECT student_id, sum(amount_usd) AS total FROM payments GROUP BY student_id) AS t

Was this tutorial helpful?

Lesson 45 of 115