sql3.ppt

Putting tables together
Joins in SQL
In regular SAS -- MERGE
proc sort data=left ; by key ; run ;
proc sort data=right ; by key ; run ;
data both ;
merge left (in=inleft) right (in=inright) ;
by key ;
< if … inleft, inright … then action >
run ;
Three types of ‘Outer Joins’
Occasionally
• Key is unique in both tables (keys/are)
• Key is only variable in common (keys/are)
 Then do ‘natural join’
More typically
• One table (left) is bigger than the other
• Key is unique in smaller (right) table
 Then do ‘left join’
Outer Joins
Occasionally
• Key may not be unique
• Mismatches do not trigger corrective action
Then do ‘full join’
Natural, left, and full joins are ‘outer joins’
Tables do not need to be sorted
Inner Joins
• Can join multiple tables at once
• Subsetted by WHERE conditions
• Naturally constructs Cartesian product of all
entries of one table with all of another table
(and with any others…)
*** Cartesian products can get very big, very
fast, so if WHERE conditions not correct, the
resulting query can be astronomically large***