Subqueries and CTEs: Multi-Step Queries

Scalar subqueries: one value from an inner query

37 min

Chapter 5 — “Nested Rooms”

The seams from Chapter 4 are holding: Kotomarket's tables no longer break apart into separate islands. users, orders, order_items, products, and events are stitched together by foreign keys. The archive now reads as one connected whole.

But K.'s message is more complicated. One seam won't be enough to unravel it.

QUERY leads you to a distant compartment of Vault-9. The door opens, and beyond it, another door glows in the amber gloom.

A room inside a room.

QUERY: Nested rooms. There's only one rule: enter the inner room, get the answer, then return to the outer one. And try not to get lost in the parentheses.

A scalar subquery is an inner room that returns exactly one value to the outer query.

What is a subquery?

A is a SELECT inside another SQL query.

You write it in parentheses:

SELECT
  name,
  price
FROM products
WHERE price > (
  SELECT AVG(price)
  FROM products
)
ORDER BY price DESC, id
LIMIT 5;

The inner query:

SELECT AVG(price)
FROM products

first calculates the average product price.

Then the outer query uses that value as a threshold:

WHERE price > average_price

You can think of the outer query as asking the inner room:

What's the average price across the catalog?

It gets one number back and compares every product against it.

Scalar subquery

The simplest type of is a scalar subquery.

Scalar means that it returns exactly one value.

That is:

one row + one column

For example:

SELECT AVG(price)
FROM products

returns one number: the average price.

You can use this kind of subquery anywhere SQL expects a regular value such as a number, string, or date.

For example:

WHERE price > (SELECT AVG(price) FROM products)

On the right side of >, SQL needs one threshold for the comparison. The subquery must therefore return one value, rather than a list of products or several columns.

Why use a subquery if you can type the number yourself?

You could first calculate the average price, say 31.60, and then write:

WHERE price > 31.60

But that's a bad idea.

The average price changes as products are added, prices are updated, and the catalog changes.

A subquery makes the threshold dynamic:

WHERE price > (SELECT AVG(price) FROM products)

Now the query calculates the current average price each time and compares the products against it.

This is especially useful in analytics:

  • products priced above the average;
  • orders above the average order value;
  • users with more orders than average;
  • categories whose revenue is above the average across categories.

Where can you use a scalar subquery?

You can use a scalar subquery in different parts of a query.

In WHERE

The query above filters rows against a dynamic threshold.

Meaning:

Show products whose price is above the catalog's average price.

In SELECT

You can add another calculation next to every row:

SELECT
  name,
  price,
  ROUND(price - (SELECT AVG(price) FROM products), 2) AS diff_from_avg
FROM products;

Meaning:

Show the product, its price, and the difference between its price and the catalog's average price.

There is only one average price, but it is used in the calculation for every row of the outer query.

In HAVING

You can compare group against one overall threshold.

For example, you can find categories whose average price is above the average price across the whole catalog:

SELECT
  category,
  AVG(price) AS avg_category_price
FROM products
GROUP BY category
HAVING AVG(price) > (
  SELECT AVG(price)
  FROM products
);

Meaning:

First calculate the average price within each category. Then keep only the categories whose average is above the overall catalog average.

How does this kind of query run?

Logically, you can picture it like this:

  1. The inner query runs.
  2. It returns one value.
  3. The outer query uses that value in its condition or calculation.

For example:

WHERE price > (SELECT AVG(price) FROM products)

can be thought of as:

WHERE price > 31.60

The number 31.60 isn't typed by hand; the inner room calculates it each time.

The subquery must return exactly one value. If it returns a list, the outer query won't know what to compare price with.

SELECT … WHERE price >valuesubquery(SELECT AVG(price) …)one valueouter querysubquery runs first
Subquery nesting: the outer query opens the inner query, takes its result, and continues working with its own rows.
Practice: write the query
Find the products whose stock is above the average across the entire catalog: return name and stock from products. Don't type the average as a number; the inner query must calculate it.
Column names and their order are not checked — the values are compared.
SELECT name, stock
FROM products;

You can put a scalar directly in the SELECT list.

The same reference value can then be used in the calculation for every row.

For example, you can show how far each product's price is above or below the catalog average:

SELECT
  name,
  price,
  ROUND(price - (SELECT AVG(price) FROM products), 2) AS diff_from_avg
FROM products
ORDER BY diff_from_avg DESC, id;

Here the subquery:

SELECT AVG(price)
FROM products

returns one number: the average price.

For every product, the outer query then calculates:

product price - catalog average price

If diff_from_avg is positive, the product costs more than average. If it's negative, the product costs less than average.

Practice: write the query
For products in the Home category (the category column), return name, price, and gap: the difference between the price of the most expensive product in the entire catalog and the current product's price. Calculate the maximum from price in products.
Column names and their order are not checked — the values are compared.
SELECT name, price
FROM products
WHERE category = 'Home';

When the inner room breaks its promise

A scalar promises the outer query one value.

SQL checks that promise at runtime, rather than when you write the query.

PostgreSQL can't always know in advance how many rows the inner SELECT will return. It finds out only when it runs the query.

The scalar subquery contract

A scalar subquery has a strict contract:

Subquery returnsWhat the outer query gets
0 rowsNULL
1 row and 1 columna value
more than 1 rowruntime error
more than 1 columnerror: the subquery can't be used as a single value

We'll look at each case in turn.

If the subquery returns one row

This is the normal case.

For example:

SELECT AVG(price)
FROM products;

An without GROUP BY returns one row.

Even if there are no products in the table, the aggregate still returns one row, although its value may be NULL.

That kind of subquery is safe to use as a scalar subquery:

WHERE price > (
  SELECT AVG(price)
  FROM products
)

If the subquery returns zero rows

Zero rows is not an error.

In that case, a scalar subquery evaluates to NULL.

For example:

SELECT
  name,
  price
FROM products
WHERE price > (
  SELECT price
  FROM products
  WHERE name = 'Product That Does Not Exist'
);

The inner query won't find any rows.

So the right side of > becomes NULL:

WHERE price > NULL

An ordinary comparison with NULL produces neither TRUE nor FALSE; its result is unknown.

WHERE keeps only rows where the condition is TRUE. So those rows are quietly filtered out.

This can be tricky: the query doesn't fail, but the result may be empty.

If you need to handle the zero-row case explicitly, use COALESCE:

WHERE price > COALESCE((
  SELECT price
  FROM products
  WHERE name = 'Product That Does Not Exist'
), 0)

Here, if the subquery returns NULL, 0 is used instead.

If the subquery returns more than one row

That causes an error.

For example:

SELECT
  name,
  price
FROM products
WHERE price > (
  SELECT price
  FROM products
  WHERE category = 'Books'
);

If the Books category contains several products, the inner query returns several prices.

The outer query expects one threshold:

WHERE price > one_price

But instead it gets a list:

12.90
14.90
16.90

PostgreSQL stops with an error:

more than one row returned by a subquery used as an expression

This is a runtime error. A query might work on a small test when there is only one book, then fail on real data as soon as a second one appears.

How to guarantee one value

There are several valid ways to do this.

1. Use an aggregate

Aggregates without GROUP BY return one row:

SELECT MAX(price)
FROM products
WHERE category = 'Books'

or:

SELECT AVG(price)
FROM products

That kind of subquery is safe to use as a scalar subquery:

WHERE price > (
  SELECT AVG(price)
  FROM products
)

But the aggregate must match the meaning of the task. MAX(price) is the maximum price, AVG(price) is the average, and MIN(price) is the minimum.

Don't choose an aggregate simply to make the query stop failing.

2. Use ORDER BY ... LIMIT 1

If you need the highest, lowest, earliest, or latest row according to a clear rule, sort the rows and use LIMIT 1.

For example, a product priced above the cheapest product in the Books category:

WHERE price > (
  SELECT price
  FROM products
  WHERE category = 'Books'
  ORDER BY price ASC, id
  LIMIT 1
)

Here the selection rule is explicit:

  • cheapest product first;
  • if prices are tied, the smaller id comes first.

This subquery returns one row predictably.

3. Don't use a scalar subquery if you actually need a list

If the inner query is supposed to return many rows, this isn't a scalar case.

For example, if you need to find products from categories that had sales, don't try to put a list into =.

For lists, SQL has IN, EXISTS, and other constructs. We'll cover them next.

Anti-pattern: bare LIMIT 1

Here's a bad attempt to “fix” the error:

WHERE price > (
  SELECT price
  FROM products
  WHERE category = 'Books'
  LIMIT 1
)

Technically, the subquery now returns one row.

But which one?

Without ORDER BY, the database doesn't have to return rows in a stable or meaningful order. Today it might return one book, tomorrow another. The result can also change after the data, an index, or the changes.

This is especially dangerous because the query stops failing but can silently return the wrong result.

Rule:

LIMIT 1 without ORDER BY doesn't choose the “first” row. From the task's point of view, it chooses an arbitrary one.

If you need one row, tell the database exactly which one:

ORDER BY price DESC, id
LIMIT 1
Practice: write the query
Return all orders from the customer who placed the most recent order at Kotomarket: id, created_at, and total_amount from orders. Identify the customer using the order with the latest created_at; if several orders have the same timestamp, choose the one with the smaller id. The subquery must return that order's user_id.
Column names and their order are not checked — the values are compared.
SELECT id, created_at, total_amount
FROM orders;
Interview question

Interview question: What does a scalar return if it finds no rows? What if it finds two?

Strong answer: If a scalar subquery finds no rows, it returns NULL. That's not an error. But if the outer query compares a value with that NULL, the result of the comparison is unknown, so WHERE won't keep that row.

For example:

WHERE price > (
  SELECT price
  FROM products
  WHERE name = 'nonexistent product'
)

if the subquery returns 0 rows, the condition becomes a comparison with NULL, and rows may quietly disappear from the result.

If a scalar subquery returns two or more rows, that's a runtime error. PostgreSQL reports:

more than one row returned by a subquery used as an expression

The right safeguard depends on what the task requires:

  • if you need an average, maximum, or minimum threshold, use an : AVG, MAX, MIN;
  • if you need one specific row, use ORDER BY ... LIMIT 1;
  • if you need a list of values, this is no longer a scalar subquery; use IN or EXISTS.

A strong extra point: LIMIT 1 without ORDER BY is a bad safeguard. It removes the error but doesn't specify which row should be chosen.

Check yourself
What must a scalar subquery return for the comparison price > (...) to be valid?
Practice: solve the tasks
Solved 0 of 3 · any 2 is enough to pass