Ask the Expert

What is a correlated subquery?

What is subquery and correlated subquery? What is the difference between them?
 

    Requires Free Membership to View

If you do a search for "correlated subquery" on the Web, you will find several sites suggesting that:

A correlated subquery is a subquery that is evaluated once for each row of the outer query.

It may indeed be convenient to imagine a correlated subquery as being "evaluated" or "executed" once for each row of the outer query; do not, however, be misled into thinking that the database optimizer actually executes it in that fashion, because this will lead you to believe that it's not very efficient, when in fact most optimizers will process a correlated subquery very efficiently, as a join.

Okay, with that out of the way, what's the difference between an ordinary subquery and a correlated subquery? The correlated subquery makes an actual reference, using a correlation variable, to the outer query. For example, here's a query with two subqueries:

 select studentname , studentmark , ( select avg(studentmark) from students where class = t1.class ) as classaverage , ( select avg(studentmark) from students ) as schoolaverage from students t1

In the above example, t1 is the correlation variable that lets the correlated subquery refer to the table in the outer query. For each student, two averages are calculated: the average mark of all students in the same class, and the overall average of all students in all classes.

Here's another example of a correlated subquery, this time in the WHERE clause:

 select category , articletitle , articlepubdate from articles zz where articlepubdate = ( select max(articlepubdate) from articles where category = zz.category )

In this example, only the most recent article in each category is selected.

 

For More Information


 

This was first published in March 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: