What is a Correlated Subquery?
The correlated subquery is a form of a subquery that cannot be run independently of the outer query, because it contains one or more columns from the outer query. The correlated subquery, just like a normal subquery, is sometimes referred to as the inner query. If the correlated subquery (inner query) is run independently of the outer query it will return an error. Because the execution of the inner query depends on values from the outer query, it is called a correlated subquery.
The correlated subquery may be executed many times. It will be run once for each candidate row selected in the outer query. The column values of each candidate row will be used to supply values for the outer query columns in the inner for each execution of the correlated subquery. The final results of a statement that contains a correlated subquery will be based on results of each execution of the correlated subquery.
SELECT CustomerID FROM Sales.SalesOrderHeader OH
WHERE (SELECT COUNT(*) FROM Sales.SalesOrderDetail
WHERE SalesOrderID = OH.SalesOrderID) > 70;
There are times when you might want to constrain a HAVING clause by different values from outer query. This is when you can use a correlated subquery in your HAVING clause. Suppose you have to write a query that will calculate rebate amounts for those customer that have purchased more than $150000 worth of products before taxes in the year 2008. The code in Listing 3 calculates the rebate amount for those valued customers by using a correlated subquery in the HAVING clause.
SELECT Outer_H.[CustomerID]
, SUM(Outer_H.[SubTotal]) AS TotalPurchase
, SUM(Outer_H.[SubTotal]) * .10 AS Rebate
FROM [Sales].[SalesOrderHeader] AS Outer_H
WHERE YEAR(Outer_H.[OrderDate]) = '2008'
GROUP BY Outer_H.[CustomerID]
HAVING (SELECT SUM(Inner_H.[SubTotal]) FROM [Sales].[SalesOrderHeader] AS Inner_H
WHERE Inner_H.[CustomerID] = Outer_H.[CustomerID]
AND YEAR(Inner_H.[OrderDate]) = '2008') > 150000
ORDER BY Rebate DESC;
Source
Plagiarism is the copying & pasting of others work without giving credit to the original author or artist. Plagiarized posts are considered spam.
Spam is discouraged by the community, and may result in action from the cheetah bot.
More information and tips on sharing content.
If you believe this comment is in error, please contact us in #disputes on Discord
Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://www.sqlservercentral.com/steps/stairway-to-t-sql-beyond-the-basics-level-3-building-a-correlated-subquery