AdvancedAdvanced PostgreSQL
Theory: Correlated vs Uncorrelated Subqueries
The query
SQL
-- Q: What is the difference between correlated and uncorrelated subqueries?
-- A: Uncorrelated subquery: Evaluates exactly once, independently of the outer query.
-- (e.g., SELECT * FROM t WHERE id IN (SELECT id FROM x))
-- Correlated subquery: Relies on data from the outer query. It executes once
-- FOR EVERY ROW evaluated by the outer query.
-- (e.g., SELECT * FROM t1 WHERE t1.val > (SELECT AVG(val) FROM t2 WHERE t2.id = t1.id))Note
“Correlated subqueries can be major performance bottlenecks (N+1 query problem at DB level).