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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jaish MathewsPosted Jan 22, 2025, 7:52 AM
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:
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:
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 KumarPosted Jan 23, 2025, 5:28 AM
Hello Kiran,
Key differnce between these two :
Co-related Query
You can see below example :
e1.DepartmentIDfrom the outer queryNested SubQuery:
You can see below example :
SELECT DepartmentID FROM Departments) runs independently and retrieves department IDs for New York.Final Conclusion :