Professional Documents
Culture Documents
Oracle Part6
Oracle Part6
Writing Correlated
Subqueries
Copyright
Objectives
After completing this lesson, you should be
able to do the following:
Describe the types of problems that can
be solved with correlated subqueries
Write correlated subqueries
Use the EXISTS and NOT EXISTS
operators
Update and delete rows using correlated
subqueries
6-2
Copyright
What Is a Subquery?
A subquery is a SELECT statement
embedded in a clause of another SQL
statement.
Main
Query
6-3
SELECT . . .
FROM . . .
WHERE . . .
Copyright
(SELECT . . .
FROM . . .
WHERE . . .)
Subquery
Subqueries
The subquery (inner query) executes once before the main query.
SELECT
FROM
WHERE
select_list
table
expr operator (SELECT
FROM
The result of the subquery is used by the main query (outer query).
6-4
Copyright
select_list
table);
Using a Subquery
SQL> SELECT ename
2 FROM
emp
2975
3 WHERE sal >
4
(SELECT sal
5
FROM
emp
6
WHERE empno = 7566);
ENAME
ENAME
------------------KING
KING
FORD
FORD
SCOTT
SCOTT
6-5
Copyright
Correlated Subqueries
Used to affect row-by-row processing,
each subquery is executed once for every
row of the outer query.
GET
candidate row
EXECUTE
inner query using candidate row value
USE
value(s) from inner query to qualify
candidate row
6-6
Copyright
Correlated Subqueries
SELECT outer1, outer2, ...
FROM
table1 alias1
WHERE outer1 operator
(SELECT inner1
FROM
table2 alias2
WHERE
alias1.outer2 =
alias2.inner1);
6-7
Copyright
Copyright
inner query.
The condition is flagged TRUE.
query.
6-9
Copyright
Copyright
JOB
DEPTNO
--------- --------PRESIDENT
10
MANAGER
30
MANAGER
10
MANAGER
20
DEPTNO
DEPTNO
----------------40
40
6-11
deptno, dname
dept d
NOT EXISTS (SELECT '1'
FROM
emp e
WHERE d.deptno = e.deptno);
DNAME
DNAME
------------------OPERATIONS
OPERATIONS
Copyright
Correlated UPDATE
UPDATE
UPDATE
SET
SET
table1
table1
column
column
alias1
alias1
== (SELECT
(SELECT
FROM
FROM
WHERE
WHERE
expression
expression
table2
table2 alias2
alias2
alias1.column
alias1.column == alias2.column);
alias2.column);
6-12
Copyright
Correlated DELETE
DELETE
DELETE
WHERE
WHERE
FROM
FROM table1
table1 alias1
alias1
column
column operator
operator
(SELECT
(SELECT expression
expression
FROM
table2
FROM
table2 alias2
alias2
WHERE
WHERE alias1.column
alias1.column == alias2.column);
alias2.column);
6-13
Copyright
Summary
Correlated subqueries are useful
whenever a subquery must return a
different result for each candidate row.
The EXISTS operator is a Boolean
operator, testing the presence of a
value.
Correlated subqueries can be used with
SELECT, UPDATE, and DELETE
statements.
6-14
Copyright
Practice Overview
Writing correlated subqueries
Using the EXISTS operator
6-15
Copyright