Sams Teach Yourself Microsoft SQL Server 7 in 21 Days

Sams Teach Yourself Microsoft SQL Server 7 in 21 Days

By Richard Waymire and Rick Sawtell

Correlated Subqueries

A correlated subquery references a table from the outer query and evaluates each row for the outer query. In this aspect, a correlated subquery differs from a normal subquery because the subquery depends on values from the outer query. A normal subquery is executed independently of the outer query.

In the following example, the join query is rewritten as a correlated subquery. The queries will return the same information. The queries answer the following instruction: Show me authors who live in the same city and zip code.

inputoutput.gif SQL Server JOIN Syntax


   SELECT au1.au_fname, au1.au_lname,

   au2.au_fname, au2.au_lname,

   au1.city, au1.zip

   FROM authors au1, authors au2

   WHERE au1.city = au2.city

   AND au1.zip = au2.zip

   AND au1.au_id < au2.au_id

   ORDER BY au1.city, au1.zip

au_fname    au_lname    au_fname    au_lname    city    zip
-------    -------    -------    -------    ----------    ------
Cheryl    Carson    Abraham    Bennet    Berkeley    94705
Dean    Straight    Dirk    Stringer    Oakland    94609
Dean    Straight    Livia    Karsen    Oakland    94609
Dirk    Stringer    Livia    Karsen    Oakland    94609
Ann    Dull    Sheryl    Hunter    Palo Alto    94301
Anne    Ringer    Albert    Ringer    Salt Lake City    84152

(6 row(s) affected)

SQL Server Correlated Subquery Syntax


   SELECT au1.au_fname, au1.au_lname, au1.city, au1.zip

   FROM authors au1

   WHERE zip IN

   (SELECT zip

   FROM authors au2

   WHERE au1.city = au2.city

   AND au1.au_id <> au2.au_id)

   ORDER BY au1.city, au1.zip

au_fname    au_lname    city    zip
--------    ------------    ---------------    ---------
Abraham    Bennet    Berkeley    94705
Cheryl    Carson    Berkeley    94705
Livia    Karsen    Oakland    94609
Dirk    Stringer    Oakland    94609
Dean    Straight    Oakland    94609
Sheryl    Hunter    Palo Alto    94301
Ann    Dull    Palo Alto    94301
Albert    Ringer    Salt Lake City    84152
Anne    Ringer    Salt Lake City    84152

(9 row(s) affected)

Notice that the same data is returned; it's just formatted differently and is more readable.

Share ThisShare This

Informit Network