Skip to content
We areTOP 1%

What is a correlated subquery, and when would you use a join instead of a subquery?

MediumConceptSQL: Joins
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

A subquery is a query nested inside another query. A regular subquery is independent and can run once, while a correlated subquery refers to a column of the outer query, so it is logically re-evaluated for every outer row.

  • Use a join when the output needs columns from both tables.
  • Use IN or EXISTS with a subquery when you only need to test whether related rows exist; NOT EXISTS is a clean way to find rows without a match.
  • Modern optimizers (MySQL 8, PostgreSQL, SQL Server) often rewrite subqueries as joins, so write the clearest form first and check the plan with EXPLAIN if it is slow.
  • Avoid NOT IN when the subquery can return NULL: a single NULL makes it return no rows.

Example: Employees who earn more than the average of their own department:

SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
                  FROM employees x
                  WHERE x.dept = e.dept);   -- correlated: uses e.dept

More in SQL: Joins

SQL: Joins questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1What are the different types of joins in SQL?
EasyConcept
ConceptEasy Read the answer to What are the different types of joins in SQL?
2What is the difference between UNION and UNION ALL, and how is UNION different from a JOIN?
EasyConcept
ConceptEasy Read the answer to What is the difference between UNION and UNION ALL, and how is UNION different from a JOIN?
3Combine Two TablesLeetCodeEasy Solve Combine Two Tables on LeetCode (opens in a new tab)
4Employees Earning More Than Their ManagersLeetCodeEasy Solve Employees Earning More Than Their Managers on LeetCode (opens in a new tab)
5Customer Who Visited but Did Not Make Any TransactionsLeetCodeEasy Solve Customer Who Visited but Did Not Make Any Transactions on LeetCode (opens in a new tab)
6Students and ExaminationsLeetCodeEasy Solve Students and Examinations on LeetCode (opens in a new tab)
7What is the difference between an equi join, a natural join, a theta join and a self join?
MediumConcept
ConceptMedium Read the answer to What is the difference between an equi join, a natural join, a theta join and a self join?
8What is a correlated subquery, and when would you use a join instead of a subquery?
MediumConcept
ConceptMedium Read the answer to What is a correlated subquery, and when would you use a join instead of a subquery?
9Managers with at Least 5 Direct ReportsLeetCodeMedium Solve Managers with at Least 5 Direct Reports on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account