Subqueries and CTEs · Lesson 51 of 64

SQL Correlated Subqueries

What you will learn

  • What makes a subquery correlated
  • How to compare each row with its own group
  • How to find the latest row per group
  • Why a correlated subquery can be slow

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. The inner query looks outside

In lesson 7.1 the inner query was independent: it ran once. A correlated subquery refers to a column of the outer row, so conceptually it runs once per outer row. You already used the idea in EXISTS. Give the outer table an alias so the inner query can name it:

Products priced above the average of their own category:

SELECT p.name, p.category_id, p.price
FROM products AS p
WHERE p.price > (SELECT AVG(p2.price) FROM products AS p2 WHERE p2.category_id = p.category_id)
ORDER BY p.category_id, p.price DESC
LIMIT 6;
name           category_id  price
-------------  -----------  -----
Tea kettle               2   79.0
Ceramic mug              2   44.1
Plant pot                3   42.9
Garden gloves            3   39.0
Seed tray                3   39.0
Watering can             3   35.1
(6 rows)

Accounts with a balance above the average of their own branch:

SELECT a.account_id, a.branch_id, a.balance_cents
FROM accounts AS a
WHERE a.balance_cents > (SELECT AVG(a2.balance_cents) FROM accounts AS a2 WHERE a2.branch_id = a.branch_id)
ORDER BY a.branch_id, a.balance_cents DESC
LIMIT 6;
account_id  branch_id  balance_cents
----------  ---------  -------------
       243          1         432800
       165          1         428004
       418          1         337200
       425          1         325400
       204          1         311947
       221          1         305213
(6 rows)

Courses with more credits than the average of their own department:

SELECT c.code, c.department_id, c.credits
FROM courses AS c
WHERE c.credits > (SELECT AVG(c2.credits) FROM courses AS c2 WHERE c2.department_id = c.department_id)
ORDER BY c.department_id, c.credits DESC, c.code
LIMIT 6;
code     department_id  credits
-------  -------------  -------
MATH101              1        4
MATH301              1        4
SCI101               2        4
SCI201               2        4
SCI202               2        4
LANG101              3        3
(6 rows)

For each outer row the inner query computes the average of that row's group (p2.category_id = p.category_id). A plain scalar subquery could only give one overall average.

2. The latest row per group

"The most recent order of every customer" is a classic:

SELECT o.customer_id, o.order_id, o.order_date
FROM orders AS o
WHERE o.order_date = (SELECT MAX(o2.order_date) FROM orders AS o2 WHERE o2.customer_id = o.customer_id)
ORDER BY o.customer_id, o.order_id
LIMIT 5;
customer_id  order_id  order_date
-----------  --------  ----------
          1       135  2025-10-01
          1       289  2025-10-01
          1       328  2025-10-01
          1       554  2025-10-01
          1       952  2025-10-01
(5 rows)
SELECT t.account_id, t.txn_id, t.txn_date
FROM transactions AS t
WHERE t.txn_date = (SELECT MAX(t2.txn_date) FROM transactions AS t2 WHERE t2.account_id = t.account_id)
ORDER BY t.account_id, t.txn_id
LIMIT 5;
account_id  txn_id  txn_date
----------  ------  ----------
         1    7390  2026-09-27
         2    7177  2026-08-29
         3    7055  2026-08-12
         4    3263  2024-05-10
         5    7296  2026-09-15
(5 rows)
SELECT e.student_id, e.section_id, e.enrolled_on
FROM enrollments AS e
WHERE e.enrolled_on = (SELECT MAX(e2.enrolled_on) FROM enrollments AS e2 WHERE e2.student_id = e.student_id)
ORDER BY e.student_id, e.section_id
LIMIT 5;
student_id  section_id  enrolled_on
----------  ----------  -----------
         1          19  2026-01-18
         2           4  2026-01-16
         3          25  2026-01-26
         4           7  2025-01-24
         5          16  2025-08-06
(5 rows)

If two rows of one group share the latest date, both are returned. Lesson 8.7 shows a way to keep exactly one.

3. A correlated subquery in SELECT

It can also compute a value for each row, such as a count of related rows:

SELECT c.customer_id, c.first_name,
       (SELECT COUNT(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS orders
FROM customers AS c
ORDER BY orders DESC, c.customer_id
LIMIT 4;
customer_id  first_name  orders
-----------  ----------  ------
         72  Hugo            17
        292  Tara            17
        134  Quinn           15
         42  Isla            14
(4 rows)
SELECT c.customer_id, c.full_name,
       (SELECT COUNT(*) FROM accounts AS a WHERE a.customer_id = c.customer_id) AS accounts
FROM customers AS c
ORDER BY accounts DESC, c.customer_id
LIMIT 4;
customer_id  full_name     accounts
-----------  ------------  --------
         96  Rosa Kumar           7
        142  Ibrahim Abdi         6
        230  Arjun Das            6
        236  Uma Garcia           6
(4 rows)
SELECT s.student_id, s.first_name,
       (SELECT COUNT(*) FROM enrollments AS e WHERE e.student_id = s.student_id) AS enrollments
FROM students AS s
ORDER BY enrollments DESC, s.student_id
LIMIT 4;
student_id  first_name  enrollments
----------  ----------  -----------
        37  Vera                  8
        16  Bela                  7
        74  Vera                  7
        81  Farid                 7
(4 rows)

A customer with no orders gets 0, like a LEFT JOIN with COUNT(column) (lesson 4.3), and without a GROUP BY.

4. The same result with a join

Many correlated subqueries can be rewritten with a join and GROUP BY. The result is the same:

SELECT c.customer_id, c.first_name, COUNT(o.order_id) AS orders
FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.first_name
ORDER BY orders DESC, c.customer_id
LIMIT 4;
customer_id  first_name  orders
-----------  ----------  ------
         72  Hugo            17
        292  Tara            17
        134  Quinn           15
         42  Isla            14
(4 rows)
SELECT c.customer_id, c.full_name, COUNT(a.account_id) AS accounts
FROM customers AS c LEFT JOIN accounts AS a ON a.customer_id = c.customer_id
GROUP BY c.customer_id, c.full_name
ORDER BY accounts DESC, c.customer_id
LIMIT 4;
customer_id  full_name     accounts
-----------  ------------  --------
         96  Rosa Kumar           7
        142  Ibrahim Abdi         6
        230  Arjun Das            6
        236  Uma Garcia           6
(4 rows)
SELECT s.student_id, s.first_name, COUNT(e.section_id) AS enrollments
FROM students AS s LEFT JOIN enrollments AS e ON e.student_id = s.student_id
GROUP BY s.student_id, s.first_name
ORDER BY enrollments DESC, s.student_id
LIMIT 4;
student_id  first_name  enrollments
----------  ----------  -----------
        37  Vera                  8
        16  Bela                  7
        74  Vera                  7
        81  Farid                 7
(4 rows)

5. Speed

A correlated subquery may run once for every outer row. With an index on the linking column (lesson 6.6) each run is quick; without one, the work grows with the square of the table size. On big tables, check the plan (EXPLAIN QUERY PLAN), index the linking column, or use a join or a WITH query (lessons 7.5-7.6).

Worked example: reading a correlated query

SELECT ... FROM products AS p WHERE p.price > (SELECT AVG(p2.price) FROM products AS p2 WHERE p2.category_id = p.category_id)

Step What happens
1 take one product p
2 the inner query averages the prices of products in p's category
3 keep p if its price is above that average
4 repeat for the next product

Read it as a loop over the outer rows. The tables are from the Shop sample.

Common mistakes

  • Forgetting the alias, so the inner query compares a column with itself.
  • Expecting one row per group when ties return several.
  • No index on the linking column of a big table.
  • Using a correlated subquery where a simple join would be clearer.

Key takeaways

  • A correlated subquery uses a column of the outer row and conceptually runs once per outer row.
  • It compares a row with its own group, finds the latest row per group, or counts related rows.
  • Many can be rewritten as a join with GROUP BY.
  • Index the linking column on big tables.

Practice

1. What makes a subquery correlated?

Show answer

It refers to a column of the outer query's row.

2. Why do you give the outer table an alias?

Show answer

So the inner query can tell its own columns from the outer row's columns.

3. What does the latest-row query return when two rows tie for the latest date?

Show answer

Both rows.

4. What does a correlated COUNT(*) give for a customer with no orders?

Show answer

0.

5. Why can a correlated subquery be slow?

Show answer

It may run once for every outer row, and without an index each run scans a table.

6. Name an alternative to a correlated subquery.

Show answer

A join with GROUP BY, or a WITH query.