Professional Documents
Culture Documents
Chapter 9
Chapter 9
Subqueries
Objectives
Subquery
The subquery (inner query) executes once before the main query.
The result of the subquery is used by the main query (outer query).
Using a Subquery
“Who has a GPA higher than Owen’s?”
GPA
LastName
Lee 3.82
Tham 3.89
Guidelines for Using Subqueries
Single-row subquery
Main query
returns
Subquery DIC
Multiple-row subquery
Main query
Subquery
returns DIC
DCS
Single-Row Subqueries
Return only one row
Use single-row comparison operators
Operator Meaning
= Equal to
OUTPUT:
LastName CourseID
Lewis DICT
Nicosia DICT
Maser DICT
Retrieving data using Single-Row Subqueries
Who has the same group leader as Williams?
SELECT LastName,GroupLeader S010
from Student
where GroupLeader = (Select GroupLeader from Student
Where LastName = 'Williams');
OUTPUT:
LastName GroupLeader
Mikulski S010
Faga S010
Williams S010
Retrieving data using Single-Row Subqueries
Who have been enrolled earlier than student S009?
SELECT LastName,DateEnrolled 01-Feb-02
from Student
where DateEnrolled < (Select DateEnrolled from Student
Where StudID = 'S009');
OUTPUT: LastName DateEnrolled
Kebel 23-Jun-01
Lee 05-Jan-02
Lewis 03-Mar-00
Law 01-Apr-01
Faga 25-Jun-01
Owen 17-Sep-01
Ng 01-Apr-01
Roche 30-Mar-00
Jann 01-Apr-01
Retrieving data using Single-Row Subqueries
with GROUP functions
Display all the students that earn the minimum GPA
OUTPUT:
LastName GPA
Ng 1.88
Roche 1.88
Multiple-Row Subqueries