x

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.4k 61 65 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 15 18 20

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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

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

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x977
x46
x1

asked: Oct 26 '09 at 06:37 AM

Seen: 2455 times

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