SQL · Module 8 · Lesson 21 min read

Correlated Subqueries

Regular vs correlated subquery

  • Regular (non-correlated): runs once, independent of the outer query WHERE amount > (SELECT avg(amount) FROM expenses) → compares with the global average
  • Correlated: references a column from the outer query, so it is evaluated for each outer row WHERE amount > (SELECT avg(amount) FROM expenses e2 WHERE e2.user_id = e.user_id) → compares with that user's average

How to read it

"For each expense e, compute the average of expenses e2 that belong to the same user as e, and keep e if it's bigger."

Common uses

  • Compare each row with its group: above the user's average, the most recent per user, the biggest per category
  • EXISTS / NOT EXISTS checks (these are almost always correlated)
  • A per-row calculated value in SELECT
  • Correlated UPDATE: UPDATE users u SET total = (SELECT sum(…) WHERE e.user_id = u.id)

Performance

  • Conceptually it runs once per outer row → can be slow on big tables
  • PostgreSQL often transforms them into joins automatically, especially EXISTS
  • Alternatives that are usually faster and clearer:
    • Window functions: avg(amount) OVER (PARTITION BY user_id) (Unit 9)
    • JOIN to a pre-aggregated subquery or CTE
    • DISTINCT ON / LATERAL for "top N per group"

LATERAL joins (PostgreSQL)

A subquery in FROM that can reference earlier tables — a "correlated subquery that returns rows":

SQL
FROM users u
CROSS JOIN LATERAL (SELECT … FROM expenses e WHERE e.user_id = u.id ORDER BY amount DESC LIMIT 2) top2

Perfect for top-N per group.

Example

SQL
-- Expenses above THAT user's own average (correlated)
SELECT e.user_id, e.title, e.amount
FROM expenses e
WHERE e.amount > (
  SELECT avg(e2.amount)
  FROM expenses e2
  WHERE e2.user_id = e.user_id          -- ← refers to the outer row
)
ORDER BY e.user_id, e.amount DESC;

-- Each user's most recent expense (correlated with max)
SELECT u.name, e.title, e.spent_on
FROM users u
JOIN expenses e ON e.user_id = u.id
WHERE e.spent_on = (SELECT max(spent_on) FROM expenses x WHERE x.user_id = u.id);

-- The same idea with a window function (Unit 9) — usually faster on big tables
SELECT user_id, title, amount
FROM (
  SELECT user_id, title, amount, avg(amount) OVER (PARTITION BY user_id) AS user_avg
  FROM expenses
) t
WHERE amount > user_avg
ORDER BY user_id, amount DESC;

-- LATERAL: top 2 expenses for every user (including users with none)
SELECT u.name, top2.title, top2.amount
FROM users u
LEFT JOIN LATERAL (
  SELECT title, amount
  FROM expenses e
  WHERE e.user_id = u.id
  ORDER BY amount DESC
  LIMIT 2
) top2 ON true
ORDER BY u.id, top2.amount DESC;
-- Asha: Running shoes, Monthly groceries | Ravi: Paragliding, Jacket | ... | Maya: NULL | Hari: NULL