S10 Correlated SubQuery
S10 Correlated SubQuery
Information Management
Session 10
Correlated Sub-Query
PGCBA | IM | CJK | 4
Objectives
After completing this session you will be able to
Define Correlated Sub-Query
Understand the execution structure of correlated sub-query
PGCBA | IM | JK | 4
9/1/2015
Review
Sub-Query
A select query that is used inside another query is called as a subquery
Sub-query usually appears inside the where clause or in the
select clause
Executes only once
Also known as inner query / nested query
Can be nested till 32 levels
PGCBA | IM | JK | 4
Correlated SubQuery
Definition
If the sub-query depends on the outer query for its
values, then it is called as a correlated sub-query
The correlated sub-query is executed once for every row
selected by the outer query
Correlated sub-query cannot be executed independently
without the outer query
PGCBA | IM | JK | 4
9/1/2015
Execution Structure
The query execution is similar to the nested loop
structure used in programming language
For I in 1 to 10 do
For J in 1 to 5 do
<instructions>
End for J
End for I
PGCBA | IM | JK | 4
Sample Tables
SALES
PRODUCT
PID
SOLD
PID
Name
Price
P99
P99
Plate
80
P77
P98
Cup
45
P99
P77
Bowl
60
P77
P33
Fork
20
P33
PGCBA | IM | JK | 4
9/1/2015
Simple Sub-query
1. Find the product that has not been sold
select pid, name, price from product where pid not in
(select distinct pid from sales)
PGCBA | IM | JK | 4
Structure of Execution
for each pid from product select pid,
for all matching pids in sales
sum(sold) for the product
end sales
end product
PGCBA | IM | JK | 4
9/1/2015
PGCBA | IM | JK | 4
PGCBA | IM | JK | 4
9/1/2015
PGCBA | IM | JK | 4
PGCBA | IM | JK | 4