Professional Documents
Culture Documents
Chapter 9
Chapter 9
Subqueries
Objectives
Describe
Using a Subquery
to Solve a Problem
Who
Main Query
Subqueries
SELECT
FROM
WHERE
The
select_list
table
expr operator
(SELECT
FROM
select_list
table);
Using a Subquery
Who has a GPA higher than Owens?
SELECT LastName, GPA
from Student
3.34
where GPA >
(Select GPA from Student
Where LastName = 'Owen');
LastName
GPA
Lee
3.82
Tham
3.89
subqueries in parentheses.
Place subqueries on the right side of the
comparison operator.
Do not add an ORDER BY clause to a
subquery.
Use single-row operators with single-row
subqueries.
Types of Subqueries
Single-row subquery
Main query
Subquery
returns
DIC
Multiple-row subquery
Main query
Subquery
returns
DIC
DCS
Single-Row Subqueries
Return
Meaning
Equal to
>
Greater than
>=
<
Less than
<=
<>
Not equal to
CourseID
Lewis
DICT
Nicosia
DICT
Maser
DICT
GroupLeader
Mikulski
S010
Faga
S010
Williams
S010
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
GPA
Ng
1.88
Roche
1.88
1.88
Multiple-Row Subqueries
Return
LastName
GPA
CourseID
Mikulski
1.89
DCS
Faga
2.22
DIC
Ng
1.88
DIT
Maser
Roche
1.88
DICT
DIT
Display all students who enrolled the same course as Law and Lewis.
CourseID
Maser
DICT
Nicosia
DICT
Lewis
DICT
Roche
DIT
Ng
DIT
Law
DIT
Lee
DIT
Summary
A subquery