Subqueries

Topic 1 of 4 in Combining queries11 min readBeginnerFree course

Overview

Because every query returns a table, the result of one query can be used inside another. A query inside a query is called a subquery (or inner query). Subqueries let you answer questions in steps — first find the average price, then find the products above it — without running two queries by hand.

Three shapes of subquery. Scalar, one value: one row and one column, used like a value, as in SELECT name, price FROM products WHERE price > (SELECT avg(price) FROM products). List, one column: many rows and one column, used with IN, ANY or ALL, as in SELECT first_name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = ‘pending’). Table, rows and columns: a derived table in FROM, which needs an alias, as in SELECT avg(order_total) FROM (SELECT order_id, sum(quantity * unit_price) AS order_total FROM order_items GROUP BY order_id) AS t. The inner query runs first, conceptually, and the outer query uses its result. Many subqueries can also be written as joins — use whichever reads more clearly.

Scalar subqueries: a single value

Which products cost more than average? You could find the average first:

SQL
SELECT avg(price) FROM products;
Text
         avg         
---------------------
 26.3250000000000000
(1 row)

…and then type WHERE price > 26.325 into a second query. But the number would go stale as soon as a price changed. Instead, put the first query inside the second, in brackets:

SQL
SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products)
ORDER BY price DESC;
Text
      name       | price 
-----------------+-------
 Burr Grinder    | 89.00
 Electric Kettle | 59.90
 Glass Teapot    | 32.00
(3 rows)

The inner query runs (conceptually) first, produces one number, and the outer query uses it like a constant. A subquery that returns exactly one row and one column is called a scalar subquery, and it can go anywhere a single value can — in WHERE, in the select list, even in a calculation:

SQL
SELECT name, price,
       round(price - (SELECT avg(price) FROM products), 2) AS vs_average,
       round(100.0 * price / (SELECT max(price) FROM products)) AS pct_of_dearest
FROM products
WHERE category_id = 2
ORDER BY price DESC;
Text
          name          | price | vs_average | pct_of_dearest 
------------------------+-------+------------+----------------
 Darjeeling First Flush | 18.00 |      -8.33 |             20
 Jasmine Green          | 12.75 |     -13.58 |             14
 Assam Breakfast        |  9.50 |     -16.83 |             11
 Chamomile Calm         |  8.00 |     -18.33 |              9
(4 rows)

If a “scalar” subquery returns more than one row, PostgreSQL stops with an error; if it returns no rows, the value is NULL:

SQL
SELECT name FROM products
WHERE category_id = (SELECT id FROM categories WHERE name LIKE '%e%');
Text
ERROR:  more than one row returned by a subquery used as an expression

All four category names contain an “e”, so the subquery returned four rows where one was required.

List subqueries: IN

A subquery that returns one column of many rows can be used with IN. Customers who have a pending order:

SQL
SELECT first_name, city
FROM customers
WHERE id IN (SELECT customer_id
             FROM orders
             WHERE status = 'pending')
ORDER BY first_name;
Text
 first_name | city  
------------+-------
 Asha       | Pune
 Dee        | Lagos
(2 rows)

Read it inside out: the inner query lists the customer ids with pending orders (1 and 4); the outer query keeps customers whose id is in that list. Unlike a join, IN never duplicates rows — a customer with three pending orders would still appear once.

NOT IN finds the opposite — products that appear in no order:

SQL
SELECT name
FROM products
WHERE id NOT IN (SELECT product_id FROM order_items);
Text
     name     
--------------
 Glass Teapot
(1 row)

That works here, but NOT IN has a nasty trap when the subquery can return NULL. The next lesson explains it and shows the safer NOT EXISTS.

ANY and ALL

IN is shorthand for = ANY. The general forms compare a value with every row of a one-column subquery:

  • x > ANY (subquery) — greater than at least one of them;
  • x > ALL (subquery) — greater than every one of them.

Products more expensive than every tea:

SQL
SELECT name, price
FROM products
WHERE price > ALL (SELECT price FROM products WHERE category_id = 2)
ORDER BY price;
Text
       name        | price 
-------------------+-------
 Pour-Over Dripper | 24.00
 Gift Card         | 25.00
 Glass Teapot      | 32.00
 Electric Kettle   | 59.90
 Burr Grinder      | 89.00
(5 rows)

That’s the same as price > (SELECT max(price) …), and the max version is usually clearer. ANY and ALL come into their own with operators that have no simple aggregate equivalent.

Derived tables: subqueries in FROM

A subquery can also produce a whole table that the outer query reads from. This is called a derived table, and it must have an alias. It’s the natural way to aggregate in two steps — for example, the average order value, where each order’s value must first be added up from its items:

SQL
SELECT count(*)                   AS orders,
       round(avg(order_total), 2) AS avg_order_value,
       max(order_total)           AS biggest_order
FROM (SELECT order_id,
             sum(quantity * unit_price) AS order_total
      FROM order_items
      GROUP BY order_id) AS t;
Text
 orders | avg_order_value | biggest_order 
--------+-----------------+---------------
     24 |           50.58 |        113.00
(1 row)

You can’t write avg(sum(...)) directly — aggregates can’t be nested — so the inner query produces one row per order and the outer query aggregates those rows. You saw the same technique in the previous lesson, joining a pre-aggregated subquery to avoid fan-out.

Derived tables can be joined like any table. Each customer’s biggest order:

SQL
SELECT c.first_name, max(t.order_total) AS biggest_order
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN (SELECT order_id, sum(quantity * unit_price) AS order_total
      FROM order_items
      GROUP BY order_id) AS t ON t.order_id = o.id
GROUP BY c.id, c.first_name
ORDER BY biggest_order DESC
LIMIT 3;
Text
 first_name | biggest_order 
------------+---------------
 Ben        |        113.00
 Hugo       |         89.00
 Elena      |         77.50
(3 rows)

Subqueries in the select list

A scalar subquery in SELECT adds a value to each row. Each category with its number of products and its cheapest price:

SQL
SELECT c.name,
       (SELECT count(*)   FROM products AS p WHERE p.category_id = c.id) AS products,
       (SELECT min(price) FROM products AS p WHERE p.category_id = c.id) AS cheapest
FROM categories AS c
ORDER BY c.name;
Text
    name     | products | cheapest 
-------------+----------+----------
 Accessories |        0 |         
 Coffee      |        3 |    11.25
 Equipment   |        4 |    24.00
 Tea         |        4 |     8.00
(4 rows)

Notice that these subqueries refer to c.id from the outer query — they’re re-evaluated for each category. That makes them correlated subqueries, the subject of the next lesson. Here the same result could come from a LEFT JOIN with GROUP BY; which one you write is a matter of clarity.

Subquery or join?

Many questions can be written either way. Customers with a pending order, as a join:

SQL
SELECT DISTINCT c.first_name, c.city
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'pending'
ORDER BY c.first_name;
Text
 first_name | city  
------------+-------
 Asha       | Pune
 Dee        | Lagos
(2 rows)

Same result as the IN version, but it needs DISTINCT to undo the duplicates the join could create. Some guidelines:

  • Need columns from both tables in the result? Use a join.
  • Only filtering by another table (“customers who have…”)? IN or EXISTS often reads more naturally and can’t duplicate rows.
  • Aggregating in two steps? Use a derived table — or a CTE, which you’ll meet at the end of this chapter and which makes multi-step queries much easier to read.

PostgreSQL’s planner often turns subqueries into joins internally, so performance is usually similar; write for clarity first.

Tip: when building a query with a subquery, run the inner query on its own first and check its output. If the inner part is right, the outer part is usually easy.

Exercise

Above average, and waiting

Two questions, one subquery each. First: which products cost more than the average product price? Return name and price, most expensive first, using a scalar subquery in WHERE (you should get three products). Second: which customers currently have a pending order? Return their first_name and email, sorted by first name, using IN with a subquery on orders — no join.

SQL
-- 1. Products above the average price
SELECT name, price
FROM products
WHERE price > ___
ORDER BY price DESC;

-- 2. Customers with a pending order

Summary

  • A subquery is a complete SELECT inside brackets, used inside another query.
  • A scalar subquery returns one row and one column and can be used anywhere a single value can.
  • A subquery returning one column can feed IN, or ANY / ALL comparisons.
  • A subquery in FROM acts as a temporary table (a derived table) and must be given an alias.
  • Many subqueries can be rewritten as joins; choose whichever expresses the question more clearly.