Subqueries
Subqueries
select department_name,city
from DEPARTMENTS
natural join (select l.location_id, l.city, l.country_id
from locations l
join countries c
on(l.country_id= c.country_id)
join regions using (region_id)
where region_name= 'Europe');
• A subquery in the from clause of a select
statement is called an inline view.
• A subquery in the from clause of a select
statement define the data source of that
particular select statement .
• When a database view is created , the associated
select statement is stored in the data dictionary.
• With inline views all the code needed the support
the query is in one place.
Multiple columns subqueries
• Each row of the main query is compared to
values from a multiple-row and multiple-
column subquery.
Non pairwise Comparison Subqueries
Correlated Subqueries
• Correlated subqueries are performed when,
the subquery references a column from a
table referred in the parent statement.
• A correlated subquery is evaluated once for
for each row processed by the parent
statement.
• Parent statement can be select, update or
delete.
Nested v/s correlated subqueries
• In nested subquery: the values returned by
the inner select are used by the outer query.
• A correlated subquery executed once for each
candidate row considered by the outer query.
i.e outer query drives inner query.
– Any and all are used in correlated subqueries.
Correlated subquery
Using correlated subquery
ALL & ANY
All exists and any
• select * from employee where salary > all(select salary from boss);
• select * from employee where salary > any(select salary from boss);
• insert into boss values (7,'Mike','Ross', 10000);