Subqueries using SQL derived tables  Correlated subqueries containing Transact-SQL outer joins

Chapter 5: Subqueries: Using Queries Within Other Queries

Using correlated subqueries

You can evaluate many of the previous queries by executing the subquery once and substituting the resulting values into the where clause of the outer query; these are noncorrelated subqueries. In queries that include a repeating subquery, or correlated subquery, the subquery depends on the outer query for its values. The subquery is executed repeatedly, once for each row that is selected by the outer query.

This example finds the names of all authors who earn 100 percent royalty on a book:

select au_lname, au_fname 
from authors 
where 100 in 
   (select royaltyper 
    from titleauthor 
    where au_id = authors.au_id) 
au_lname        au_fname 
--------------  ---------- 
White           Johnson               
Green           Marjorie              
Carson          Cheryl                
Straight        Dick                  
Locksley        Chastity              
Blotchet-Hall   Reginald   
del Castillo    Innes                 
Panteley        Sylvia                
Ringer          Albert                

(9 rows affected) 

Unlike most of the previous subqueries, the subquery in this statement cannot be resolved independently of the main query. It needs a value for authors.au_id, but this value is a variable—it changes as Adaptive Server examines different rows of the authors table.

This is how the preceding query is evaluated: Transact-SQL considers each row of the authors table for inclusion in the results, by substituting the value in each row in the inner query. For example, suppose Transact-SQL first examines the row for Johnson White. Then, authors.au_id takes the value “172-32-1176,” which Transact-SQL substitutes for the inner query:

select royaltyper 
from titleauthor 
where au_id = "172-32-1176" 

The result is 100, so the outer query evaluates to:

select au_lname, au_fname 
from authors 
where 100 in (100) 

Since the where condition is true, the row for Johnson White is included in the results. If you go through the same procedure with the row for Abraham Bennet, you can see how that row is not included in the results.





Copyright © 2005. Sybase Inc. All rights reserved. Correlated subqueries containing Transact-SQL outer joins

View this book as PDF