Explain the difference between a correlated subquery and a nested subquery
Loading
Explain the difference between a correlated subquery and a nested subquery
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jaish MathewsRank #225 · 11K reputationPosted Jan 22, 2025, 2:52 AM EST
A correlated subquery and a nested subquery are two types of subqueries in SQL, but they differ in how they interact with the main query. Here's a detailed explanation:
1. Correlated Subquery
A correlated subquery is a subquery that depends on values from the outer query. It is executed repeatedly, once for each row evaluated by the outer query.
Key Characteristics:
Example:
SELECT e.EmployeeID, e.Salary FROM Employees e WHERE e.Salary > (SELECT AVG(s.Salary) FROM Employees s WHERE s.DepartmentID = e.DepartmentID);e.DepartmentID).Employeestable.Performance:
2. Nested Subquery
A nested subquery (also called a simple subquery) is executed independently of the outer query. The result of the subquery is passed to the outer query as input.
Key Characteristics:
Example:
SELECT EmployeeID, Salary FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);Salarycolumn of each row in the outer query.Performance:
Comparison Table
Which One to Use?
In general, where possible, avoid correlated subqueries for performance reasons and consider alternatives like
JOINorWITH(Common Table Expressions).Jignesh KumarRank #91 · 22.9K reputationPosted Jan 23, 2025, 12:28 AM EST
Hello Kiran,
Key differnce between these two :
Co-related Query
You can see below example :
e1.DepartmentIDfrom the outer querySELECT e1.EmployeeID, e1.Salary FROM Employees e1 WHERE e1.Salary > ( SELECT AVG(e2.Salary) FROM Employees e2 WHERE e2.DepartmentID = e1.DepartmentID );Nested SubQuery:
You can see below example :
SELECT DepartmentID FROM Departments) runs independently and retrieves department IDs for New York.SELECT EmployeeID, Salary FROM Employees WHERE DepartmentID IN ( SELECT DepartmentID FROM Departments WHERE Location = 'New York' );Final Conclusion :