subqueries in sql
subqueries in sql
OBJECTIVES
Main
Query:
Which employees have salaries greater
?
than Abel’s salary?
Subquer
y
?
What is Abel’s salary?
SUBQUERY SYNTAX
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
◼ 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
SELECT last_name
FROM employees 11000
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');
GUIDELINES FOR USING SUBQUERIES
◼ Enclose subqueries in parentheses.
◼ Place subqueries on the right side of the comparison
condition.
◼ The ORDER BY clause in the subquery is not needed unless
you are performing Top-N analysis.
◼ Use single-row operators with single-row subqueries and
use multiple-row operators with
multiple-row subqueries.
TYPES OF SUBQUERIES
• Single-row subquery
Main
query returns
Subquer ST_CLERK
y
• Multiple-row subquery
Main
query returns ST_CLERK
Subquer
y SA_MAN
SINGLE-ROW SUBQUERIES
◼ Return only one row
◼ Use single-row comparison operators
Operator Meaning
= Equal to
ERROR
ERROR at
at line
line 4:
4:
ORA-01427:
ORA-01427: single-row
single-row subquery
subquery returns
returns more
more than
than
one
one row
row
Single-row
Single-row operator
operator with
with multiple-row
multiple-row subquery
subquery
WILL THIS STATEMENT RETURN ROWS?
no
no rows
rows selected
selected
Subqueryy returns
Subquer no values
returns no values
MULTIPLE-ROW SUBQUERIES
◼ Return more than one row
◼ Use multiple-row comparison operators
Operator Meaning
(SELECT salary
FROM employees
WHERE job_id =
'IT_PROG')
AND job_id <> 'IT_PROG';
…
USING THE ALL OPERATOR
IN MULTIPLE-ROW SUBQUERIES
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);
no rows selected
EXCERCISE