Subquery
Subquery
A
A subquery
subquery is
is aa SELECT
SELECT statement
statement
embedded
embedded inin aa clause
clause of
of another
another SQL
SQL
statement.
statement.
Main SELECT . . .
Query FROM . . .
WHERE . . .
(SELECT . . . Subquery
FROM . . .
WHERE . . .)
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list
FROM table);
•• The
The subquery
subquery (inner
(inner query)
query) executes
executes
once
once before
before the
the main
main query.
query.
•• The
The result
result of
of the
the subquery
subquery is
is used
used by
by
the
the main
main query
query (outer
(outer query).
query).
ENAME
ENAME
----------
----------
KING
KING
FORD
FORD
SCOTT
SCOTT
The
The subquery
subquery references
references aa column
column from
from
aa table
table in
in the
the parent
parent query.
query.
EMPNO
EMPNO SAL
SAL DEPTNO
DEPTNO
--------
-------- ---------
--------- ---------
---------
7839
7839 5000
5000 10
10
7698
7698 2850
2850 30
30
7566
7566 2975
2975 20
20
...
...
66 rows
rows selected.
selected.
6-5 Copyright Oracle Corporation, 1998. All rights reserved.
Using the EXISTS Operator
•• If
If aa subquery
subquery row
row value
value is
is found:
found:
–– The
The search
search does
does not
not continue
continue inin the
the
inner
inner query.
query.
–– The
The condition
condition is
is flagged
flagged TRUE.
TRUE.
•• If
If aa subquery
subquery row
row value
value is
is not
not found:
found:
–– The
The condition
condition is
is flagged
flagged FALSE.
FALSE.
–– The
The search
search continues
continues in
in the
the inner
inner
query.
query.
DEPTNO
DEPTNO DNAME
DNAME
---------
--------- ----------
----------
40
40 OPERATIONS
OPERATIONS
UPDATE
UPDATE table1
table1 alias1
alias1
SET
SET column
column == (SELECT
(SELECT expression
expression
FROM
FROM table2
table2 alias2
alias2
WHERE
WHERE alias1.column
alias1.column == alias2.column);
alias2.column);
Use
Use aa subquery
subquery toto update
update rows
rows in
in one
one table
table
based
based onon rows
rows from
from another
another table.
table.
DELETE
DELETE FROM
FROM table1
table1 alias1
alias1
WHERE
WHERE column
column operator
operator
(SELECT
(SELECT expression
expression
FROM
FROM table2
table2 alias2
alias2
WHERE
WHERE alias1.column
alias1.column == alias2.column);
alias2.column);
Use
Use aa subquery
subquery toto delete
delete only
only those
those rows
rows
that
that also
also exist
exist in
in another
another table.
table.