Correlated Subqueries

Updated · 8 min read
mediumPostgreSQL 18sqlcorrelated-subquerysubqueriesinterview

A correlated subquery refers to a column of the outer query's current row, so it's evaluated again for each outer row. "Each student's latest payment" can't be answered with one fixed number, because "latest" means something different for Srihitha and for Navika. A correlated subquery asks, for every payment, "is this the latest one for this payment's student?" This lesson shows how correlation works, walks through it row by row, and covers the alternatives that are often clearer or faster.

In One Minute

  • A correlated subquery uses a value from the outer row, such as p2.student_id = p.student_id.
  • Conceptually it runs once per outer row, with that row's values plugged in.
  • It works in WHERE, in the SELECT list, and with EXISTS.
  • Use different aliases for the inner and outer copies of a table.
  • Joins, DISTINCT ON and window functions often answer the same question more simply.

The Idea: A Subquery That Depends on the Row

The inner query refers to the outer query's alias, so its answer changes from row to row. Each student's latest payment:

SQL▶ Try it
SELECT p.payment_id, p.student_id, p.paid_on
FROM payments AS p
WHERE p.paid_on = (
  SELECT max(p2.paid_on)
  FROM payments AS p2
  WHERE p2.student_id = p.student_id
)
ORDER BY p.student_id;
Output
 payment_id | student_id |  paid_on
------------+------------+------------
          5 |        101 | 2026-01-05
          7 |        103 | 2025-12-19
(2 rows)

p is the outer payment and p2 the inner one. For each outer payment, the subquery finds the latest paid_on among payments of the same student (p2.student_id = p.student_id), and the outer WHERE keeps the payment if it's that latest one. Without the different aliases, student_id = student_id would compare the inner row with itself and always be true.

Row by Row

Here's what the database works out for each outer row, conceptually:

Outer paymentIts studentSubquery: latest paid_on for that studentKept?
1 (2025-08-28)1012026-01-05No
2 (2025-10-30)1012026-01-05No
3 (2025-12-03)1012026-01-05No
4 (2025-12-29)1012026-01-05No
5 (2026-01-05)1012026-01-05Yes
6 (2025-11-14)1032025-12-19No
7 (2025-12-19)1032025-12-19Yes

The subquery's answer depends only on the student, so it's the same for all of Srihitha's rows and for both of Navika's. PostgreSQL doesn't have to rerun it naively for every row; the planner often turns a correlated subquery into a join behind the scenes. But "once per row" is the right way to read it.

For each payment, the inner query finds that student's latest date; only payments 5 and 7 match it

Comparing Each Row with Its Own Group

Correlation is natural for "compared with others like it" questions. Payments larger than the same student's average payment:

SQL▶ Try it
SELECT p.payment_id, p.student_id, p.amount_usd
FROM payments AS p
WHERE p.amount_usd > (
  SELECT avg(p2.amount_usd)
  FROM payments AS p2
  WHERE p2.student_id = p.student_id
)
ORDER BY p.payment_id;
Output
 payment_id | student_id | amount_usd
------------+------------+------------
          1 |        101 |     450.00
          4 |        101 |     550.00
(2 rows)

Srihitha's average payment is $340.00, so her $450.00 and $550.00 payments are above it. Navika's two payments are both $225.00, exactly her average, so neither is above it. Compared with the overall average instead, the answer would mix the two students' habits together.

Srihitha's average is 340.00, so 450.00 and 550.00 are above it; Navika's payments equal her 225.00 average

In the SELECT List

A correlated subquery in SELECT computes one value per row. Each student's number of payments:

SQL▶ Try it
SELECT s.first_name,
       (SELECT count(*) FROM payments AS p WHERE p.student_id = s.student_id) AS payments
FROM students AS s
ORDER BY s.student_id;
Output
 first_name | payments
------------+----------
 Srihitha   |        5
 Advitha    |        0
 Navika     |        2
(3 rows)

Advitha gets 0, because count(*) over no rows is 0. This gives the same numbers as a LEFT JOIN with GROUP BY, without the grouping. It must return a single value per row, like any scalar subquery.

For each student, count the payments whose student_id matches: 5, 0 and 2

When Something Else Is Better

The same questions often have simpler or faster answers. "Each student's latest payment" in PostgreSQL's DISTINCT ON, from SELECT DISTINCT:

SQL▶ Try it
SELECT DISTINCT ON (student_id) student_id, payment_id, paid_on
FROM payments
ORDER BY student_id, paid_on DESC;
Output
 student_id | payment_id |  paid_on
------------+------------+------------
        101 |          5 | 2026-01-05
        103 |          7 | 2025-12-19
(2 rows)

Same two payments. DISTINCT ON is PostgreSQL only; the portable alternative is a window function, row_number(), covered in Ranking Functions. One difference: if a student had two payments on their latest date, the correlated subquery would return both, while DISTINCT ON returns one.

QuestionCorrelated subqueryOften simpler
Latest row per groupWHERE date = (SELECT max(...) ... WHERE inner.key = outer.key)DISTINCT ON, or row_number()
Count per row(SELECT count(*) ... WHERE inner.key = outer.key)LEFT JOIN + GROUP BY
Compare with own group> (SELECT avg(...) ... WHERE inner.key = outer.key)avg(...) OVER (PARTITION BY key)
Has any matchEXISTS (SELECT 1 ... WHERE inner.key = outer.key)This is already the best way

Common Mistakes

Same alias inside and out. WHERE student_id = student_id inside the subquery compares the inner row with itself. Give each copy its own alias and qualify every column.

Forgetting the correlation. Without p2.student_id = p.student_id, the subquery computes the latest payment overall, the same for every row.

Returning several rows from a scalar correlated subquery. It must return one value per outer row.

Interview Corner

What is a correlated subquery?

A subquery that refers to a column of the outer query, so its result depends on the current outer row. It's conceptually evaluated once for each outer row.

What's the difference between a correlated and a non-correlated subquery?

A non-correlated subquery is independent and can run once on its own. A correlated subquery uses values from the outer row and can't run by itself.

How would you find each customer's most recent order?

A correlated subquery (WHERE order_date = (SELECT max(order_date) FROM orders o2 WHERE o2.customer_id = o.customer_id)), DISTINCT ON in PostgreSQL, or row_number() OVER (PARTITION BY customer_id ORDER BY order_date DESC) = 1.

Practice

Challenge: For each course that has payments, show the course title and its single largest payment, using a correlated subquery in the SELECT list. Sort by course_id. Hint: start from courses, and keep only courses that appear in payments.

Show solution
SQL▶ Try it
SELECT c.title,
       (SELECT max(p.amount_usd) FROM payments AS p WHERE p.course_id = c.course_id) AS largest_payment
FROM courses AS c
WHERE c.course_id IN (SELECT course_id FROM payments)
ORDER BY c.course_id;
Output
       title       | largest_payment
-------------------+-----------------
 Java Basics       |          450.00
 Java OOP          |          250.00
 Java Collections  |          550.00
 SQL Basics        |          200.00
 JavaScript Basics |          225.00
(5 rows)

For each course, the subquery looks only at that course's payments. Git Basics has no payments, so the IN filter leaves it out; without the filter it would appear with NULL.

Quick check: Correlated subqueries

3 questions
1What makes a subquery correlated?
2In WHERE p.paid_on = (SELECT max(p2.paid_on) FROM payments p2 WHERE p2.student_id = p.student_id), what does the subquery compute for payment 6 (Navika's)?
3Why does the inner query need its own alias?

Key Takeaways

You want toWrite
Latest row per studentWHERE p.paid_on = (SELECT max(p2.paid_on) FROM payments p2 WHERE p2.student_id = p.student_id)
Above own averageWHERE p.amount_usd > (SELECT avg(p2.amount_usd) FROM payments p2 WHERE p2.student_id = p.student_id)
A count per row(SELECT count(*) FROM payments p WHERE p.student_id = s.student_id)

Was this tutorial helpful?

Lesson 46 of 115