x
login about faq Site discussion (meta-askssc)

When does a sub-query become a correlated sub-query?

Seeder question: I know how to use sub-queries, but I have seen the term 'correlated sub-query' used, and I don't know what they are for. What are they, and should I be using them?

more ▼

asked Oct 26 '09 at 06:37 AM in Default

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.2k 56 63 87

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

A correlated subquery refers to fields in the outer query, and therefore changes (potentially) for each row in the outer query.

A subquery that isn't correlated is self-contained and only needs to be run once.

Edited to provide an example:

The subquery here is non-correlated. It returns the same number every time.

SELECT *, (SELECT COUNT(*) FROM Production.Product AS p) AS NumProducts
FROM Production.ProductSubcategory AS s;

The subquery here is correlated, and will return the number of products in the relevant subcategory.

SELECT *, (SELECT COUNT(*) FROM Production.Product AS p 
           WHERE p.ProductSubcategoryID = s.ProductSubcategoryID) AS NumProducts
FROM Production.ProductSubcategory AS s;

One common mistake people often make with correlated subqueries is to provide that hook into the outer query (making it non-correlated). If you're do that with a WHERE EXISTS clause, you turn the WHERE EXISTS into an all-or-nothing predicate (rather than something which is evaluated separately, and thereby filtering only some rows).

more ▼

answered Oct 26 '09 at 07:15 AM

Rob Farley gravatar image

Rob Farley
5.7k 13 17 19

How about adding a short example, Rob?

Oct 26 '09 at 09:25 AM Bob Hovious
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x914
x45
x1

asked: Oct 26 '09 at 06:37 AM

Seen: 2000 times

Last Updated: Oct 26 '09 at 06:37 AM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.