Entering content frame

Correlated Subquery 

Certain predicates can contain subqueries. These subqueries, in turn, can contain other subqueries, etc. A subquery with further subqueries is the higher-level subquery of the subqueries it contains.

·        The search condition of a subquery can contain column names that belong to tables that are contained in higher levels in the FROM clause. This type of subquery is called a correlated subquery.

·        Tables that are used in subqueries in this way are called correlated tables. No more than 16 correlated tables are allowed within an SQL statement.

·        Columns that are used in subqueries in this way are called correlated columns. A total of 64 correlated columns can be used in an SQL statement.

If the qualifying table name or reference name does not clearly identify a table at a higher level, the table at the lowest level is taken from these non-unique tables.

If the column name is not qualified by the table name or reference name, the tables at higher levels are searched. The column name must be unique in all tables of the from clause to which the table found belongs.

If a correlated subquery is used, the values of one or more columns in a temporary result row at a higher level are included in the searchcondition of a subquery at a lower level, whereby the result of the subquery is used to uniquely qualify the higher-level temporary result row.

Example tables hotel and room.
For every city, the names of all hotels are searched which have single room prices less than the average price of the city concerned.

SELECT name, city FROM hotel X, room

WHERE X.hno = room.hno AND room.roomtype = 'SINGLE' AND room.price <

(SELECT AVG(room.price) FROM hotel, room

WHERE hotel.hno = room.hno AND hotel.city = X.city AND room.roomtype = 'SINGLE' )

Name

City

Eight Avenue

Los Angeles

Sunshine

Los Angeles

Atlantic

New York

 

 

Leaving content frame