libname sql 'SAS-library';
proc sql outobs=5;
title 'Populations of NonMajor Oil Producing Countries';
select name 'Country', Population format=comma15.
from sql.countries
where Name not in
(select Country from sql.oilprod);
Output 3.27 Multiple-Value Subquery Using NOT IN
Correlated Subqueries
The previous subqueries have been simple subqueries that are self-contained and that
execute independently of the outer query. A correlated subquery requires a value or
values to be passed to it by the outer query. After the subquery runs, it passes the results
back to the outer query. Correlated subqueries can return single or multiple values.
This example selects all major oil reserves of countries on the continent of Africa.
libname sql 'SAS-library';
proc sql;
title 'Oil Reserves of Countries in Africa';
select * from sql.oilrsrvs o
where 'Africa' =
(select Continent from sql.countries c
where c.Name = o.Country);
The outer query selects the first row from the OilRsrvs table and then passes the value of
the Country column, Algeria, to the subquery. At this point, the subquery internally
looks like this:
(select Continent from sql.countries c
where c.Name = 'Algeria');
The subquery selects that country from the Countries table. The subquery then passes the
country's continent back to the WHERE clause in the outer query. If the continent is
Africa, then the country is selected and displayed. The outer query then selects each
subsequent row from the OilRsrvs table and passes the individual values of Country to
the subquery. The subquery returns the appropriate values of Continent to the outer
query for comparison in its WHERE clause.
98 Chapter 3 • Retrieving Data from Multiple Tables