0% found this document useful (0 votes)
41 views38 pages

SQL-6 Subquery F22

Sql

Uploaded by

mz8640073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views38 pages

SQL-6 Subquery F22

Sql

Uploaded by

mz8640073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

(SQL)

Subqueries

Asif Sohail
University of the Punjab
Punjab University College of Information Technology (PUCIT)

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 1
Objectives

• After completing this lesson, you should be able


to do the following:
– Describe the types of problems that
subqueries can solve
– Define subqueries
– List the types of subqueries
– Write single-row and multiple-row subqueries

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 2
Using a Subquery
to Solve a Problem

•“Who has a salary greater than Jones’?”

Main Query

“Which employees have a salary greater


? than Jones’ salary?”

Subquery

?
“What is Jones’ salary?”

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 3
Subqueries
• Query within a query is called subquery.

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).
• Bottom-up or inward-outward parsing
• The subquery can also be paced in the HAVING, FROM clause
of the outer query.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 4
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

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 5
Exercise
• List all employees with salary greater than the average
salary of the employees.
• List all employees with salary greater than the average
salary of the employees of a certain job/department.
• Find the name of the highest paid employee.
• Find the name of the most senior employee.
• List all employees with the same job/department as that
of a given employee.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 6
Types of Subqueries
1. Single-row subquery
•Returns zero on one row to the outer SQL statement. A
special case called scalar subquery contains exactly one
column.
2. Multiple-row subquery
•Returns one or more rows to the outer SQL statement.
•In addition, there are three subtypes of subqueries that may
return single or multiple rows:
a)Multiple-column subqueries return more than one column
to the outer SQL statement.
b)Correlated subqueries reference one or more columns in
the outer SQL statement.
c)Nested subqueries are placed within another subquery.
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 7
Types of Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK

• Multiple-row subquery
Main query

Subquery
returns CLERK
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 8
Guidelines for Using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the
comparison operator.
• ORDER BY clause is mostly not required in a
subquery.
• Use single-row operators with single-row
subqueries.
• Use multiple-row operators (IN,ANY,ALL) with
multiple-row subqueries.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 9
Single-Row Subqueries
– Return only one row
– Use single-row comparison operators

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 10
Executing Single-Row Subqueries

SQL> SELECT ename, job


2 FROM emp
3 WHERE job = CLERK
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);

ENAME
ENAME JOB
JOB
----------
---------- ---------
---------
MILLER
MILLER CLERK
CLERK

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 11
Using Group Functions
in a Subquery (Scalar Subquery)
– Find the lowest paid employee

SQL> SELECT ename, job, sal


800
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);

ENAME
ENAME JOB
JOB SAL
SAL
----------
---------- ---------
--------- ---------
---------
SMITH
SMITH CLERK
CLERK 800
800

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 12
Finding second highest sal

SQL> SELECT MAX(sal) FROM emp


2 WHERE sal < (SELECT MAX(sal) FROM emp);

SQL> SELECT ename, job, sal


2 FROM emp
3 WHERE sal =
4 (SELECT MAX(sal) FROM emp
5 WHERE sal < (SELECT MAX(sal) FROM emp));

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 13
HAVING Clause with Subqueries
– The Oracle Server executes subqueries first.
– The Oracle Server returns results into the
HAVING clause of the main query.

SQL> SELECT deptno, MIN(sal)


2 FROM emp
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);

– Find the name of the department with the


highest/lowest number of employees.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 14
HAVING Clause with Subqueries
• List job, average salary of those jobs whose
average salary is greater than the minimum
average of different jobs.
SELECT JOB, AVG(SAL) FROM EMP
GROUP BY JOB
HAVING AVG(SAL) >
(SELECT MIN(AVG(SAL)) FROM EMP
GROUP BY JOB)

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 15
What Is Wrong
with This Statement?

SQL> SELECT empno, ename


2 FROM emp
3 WHERE sal =
4
w i t h(SELECT MIN(sal)
5 r at or FROM emp
6 ow op
e er y GROUP BY
-r q u deptno);
n g l e w sub
Si l e- r o
u l t ip
m
ERROR:
ERROR:
ORA-01427:
ORA-01427: single-row
single-row subquery
subquery returns
returns more
more than
than
one
one row
row

no
no rows
rows selected
selected

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 16
Will This Statement Work?

SQL> SELECT ename, job


2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE ename='SMYTHE');
l ues
o va
s n
no
no rows
rows selected
selected t ur n
r e
uery
ubq
S

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 17
Multiple-Row Subqueries
– Return more than one row
– Use multiple-row comparison operators
Operator Meaning

IN Equal to any member in the list

ANY Compare value to each value returned by the subquery.


The overall result is TRUE if it is TRUE for ANY of the
values returned by the subquery.

Compare value to every value returned by the subquery.


The overall result is TRUE only if it is TRUE for ALL of the
ALL values returned by the subquery.

– ANY, ALL must always be proceeded by any of the


relational operators (<, <=, >, >=, =, <>)
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 18
Using IN Operator
in Multiple-Row Subqueries

SQL> SELECT empno, ename, job


2 FROM emp
3 WHERE sal IN (SELECT MIN(sal)
4 FROM emp
5 GROUP BY deptno);

SQL> SELECT empno, sal, detpno


2 FROM emp
3 WHERE sal < IN (800, 950, 1300);

EMPNO
EMPNO ENAME
ENAME JOB
JOB
---------
--------- ----------
---------- ---------
---------
7369
7369 SMITH
SMITH CLERK
CLERK
7900
7900 JAMES
JAMES CLERK
CLERK
7934
7934 MILLER
MILLER CLERK
CLERK

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 19
Using ANY Operator
in Multiple-Row Subqueries

SQL> SELECT empno, ename, job 1300


2 FROM emp 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM emp
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

EMPNO
EMPNO ENAME
ENAME JOB
JOB
---------
--------- ----------
---------- ---------
---------
7654
7654 MARTIN
MARTIN SALESMAN
SALESMAN
7521
7521 WARD
WARD SALESMAN
SALESMAN

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 20
Using ALL Operator
in Multiple-Row Subqueries

SQL> SELECT empno, ename, job 1566.6667


2 FROM emp 2175
2916.6667
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);

EMPNO
EMPNO ENAME
ENAME JOB
JOB
---------
--------- ----------
---------- ---------
---------
7839
7839 KING
KING PRESIDENT
PRESIDENT
7566
7566 JONES
JONES MANAGER
MANAGER
7902
7902 FORD
FORD ANALYST
ANALYST
7788
7788 SCOTT
SCOTT ANALYST
ANALYST

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 21
Null Values in a Subquery
List all employees who do not have any subordinates.
SQL> SELECT e.ename
2 FROM emp e
3 WHERE e.empno NOT IN
4 (SELECT manager.mgr
5 FROM emp manager);
no rows selected.

– One of the values returned by the inner query is


NULL, and hence now rows are returned.
– NOT IN operator has issues with subqueries that
could return NULL values.
– NOT IN operator is equivalent to <>ALL.
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 22
Null Values in a Subquery
– List all employees who do not have any subordinates.
SELECT e.ename,e.job FROM emp e
WHERE e.empno NOT IN
(SELECT m.mgr FROM emp m
WHERE m.mgr IS NOT NULL);

ENAME JOB
SMITH CLERK
ALLEN SALESMAN
WARD SALESMAN
MARTIN SALESMAN
TURNER SALESMAN
ADAMS CLERK
JAMES CLERK
MILLER CLERK

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 23
Multiple-Column Subqueries

• After completing this lesson, you should be


able to do the following:
– Write a multiple-column subquery
– Describe and explain the behavior of
subqueries when null values are retrieved
– Write a subquery in a FROM clause

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 24
Multiple-Column Subqueries
Main query
MANAGER 10

Subquery
SALESMAN 30
MANAGER 10
CLERK 20

Main query Values from a multiple-row and


compares to
multiple-column subquery

MANAGER 10 SALESMAN 30
MANAGER 10
CLERK 20

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 25
Using Multiple-Column Subqueries

• Display the order number, product number, and


quantity of any item in which the product number
and quantity match both the product number and
quantity of an item in order 605.

SQL> SELECT ordid, prodid, qty


2 FROM item
3 WHERE (prodid, qty) IN
4 (SELECT prodid, qty
5 FROM item
6 WHERE ordid = 605)
7 AND ordid <> 605;

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 26
Column Comparisons

Pairwise Nonpairwise
PRODID QTY PRODID QTY
101863 100 101863 100
100861 100 100861 100
102130 10 102130 10
100890 5 100890 5
100870 500 100870 500
101860 50 101860 50

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 27
Nonpairwise Comparison Subquery
• Display the order number, product number, and
quantity of any item in which the product number
and quantity match any product number and any
quantity of an item in order 605.

SQL> SELECT ordid, prodid, qty


2 FROM item
3 WHERE prodid IN (SELECT prodid
4 FROM item
5 WHERE ordid = 605)
6 AND qty IN (SELECT qty
7 FROM item
8 WHERE ordid = 605)
9 AND ordid <> 605;

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 28
Nonpairwise Subquery
ORDID PRODID QTY
--------- --------- ---------
609 100870 5
616 100861 10
616 102130 10
621 100861 10
618 100870 10
618 100861 50
616 100870 50
617 100861 100
619 102130 100
615 100870 100
617 101860 100
621 100870 100
617 102130 100
. . .
16 rows selected.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 29
Main query
references
Correlated Subquery Subquery

• A correlated subquery references one or more columns


in the outer SQL statement.
• The inner query uses a table alias of outer query.
• Unlike a simple subquery that is executed only once, a
correlated subquery is execute for more than once.
• The inner query is evaluated against each row of the
outer query (Top-down or outward-inward parsing)
• A correlated subquery is also known as a repeating
subquery or a synchronized subquery.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 30
Correlated Subquery
– The EXISTS operator checks for the existence of a row
in the subquery.
– EXISTS typically offers better performance than IN.
– When a list of values contains a NULL value, NOT
EXISTS return TRUE, but NOT IN returns FALSE.
– List all employees who do not have any subordinates.
SELECT e.ename,e.job FROM emp e ENAME JOB
WHERE NOT EXISTS SMITH CLERK
(SELECT empno FROM emp m
ALLEN SALESMAN
WHERE m.mgr = e.empno);
WARD SALESMAN
MARTIN SALESMAN
TURNER SALESMAN
ADAMS CLERK
JAMES CLERK
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 MILLER CLERK Slide 31
Correlated Subquery
• Finding an employee with Nth highest salary

SELECT * FROM Emp Emp1


WHERE (N-1) = (
SELECT COUNT(DISTINCT Emp2.Sal)
FROM Emp Emp2
WHERE Emp2.Sal > Emp1.Sal);

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 32
Main query
references
Correlated Subquery Subquery

• Subquery in SELECT clause

SELECT ename,job,sal,
(SELECT ROUND(AVG(sal))from emp e2
WHERE e1.job=e2.job)"avg-job-sal"
FROM emp e1

ENAME JOB SAL avg-job-sal


KING PRESIDENT 5000 5000
BLAKE MANAGER 2850 2758
CLARK MANAGER 2450 2758
JONES MANAGER 2975 2758
SCOTT ANALYST 3000 3000
FORD ANALYST 3000 3000
SMITH CLERK 800 1038
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 33
Main query
references
Correlated Subquery Subquery

• Subquery in FROM clause (inline views)


SELECT e1.ename, e1.job, e1.sal, e2.salavg
FROM emp e1,
SELECT job, round(avg(sal)) salavg
FROM emp GROUP BY job) e2
WHERE e1.job = e2.job

ENAME JOB SAL avg-job-sal


KING PRESIDENT 5000 5000
BLAKE MANAGER 2850 2758
CLARK MANAGER 2450 2758
JONES MANAGER 2975 2758
SCOTT ANALYST 3000 3000
FORD ANALYST 3000 3000
SMITH CLERK 800 1038
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 34
Using a Subquery
in the FROM Clause

SQL> SELECT a.ename, a.sal, a.deptno, b.salavg


2 FROM emp a, (SELECT deptno, avg(sal) salavg
3 FROM emp
4 GROUP BY deptno) b
5 WHERE a.deptno = b.deptno
6 AND a.sal > b.salavg;

ENAME
ENAME SAL
SAL DEPTNO
DEPTNO SALAVG
SALAVG
----------
---------- ---------
--------- ---------
--------- ----------
----------
KING
KING 5000
5000 10
10 2916.6667
2916.6667
JONES
JONES 2975
2975 20
20 2175
2175
SCOTT
SCOTT 3000
3000 20
20 2175
2175
...
...
66 rows
rows selected.
selected.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 35
Exercise
• Find employees who work for the department in which employee ID 7369 is
employed.
• List all employees with salary less than the average salary of all the employees.
• List all employees with salary less than the average salary of any of the
departments.
• Find those employees whose salary matches the lowest salary of any of the
departments.
• List all employees with salary less than the average salary of their respective
departments.
• List all the departments with no employees.
• Find all those departments where at least one employee is employed.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 36
Exercise
• List all employees with salary greater than the average
salary of the respective departments.
select ename, job, sal,
(select avg(sal) from emp e
Where outer.deptno=e.deptno) "avg-sal"
from emp outer

where sal >(select avg(sal) from emp inner where


outer.deptno=inner.deptno)

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 37
Thank you for your attention.

Asif Sohail

Assistant Professor
University of the Punjab
Punjab University College of Information Technology (PUCIT)
Allama Iqbal (Old) Campus, Anarkali
Lahore, Pakistan
Tel: +92-(0)42-111-923-923 Ext. 154
E-mail: [email protected]

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 38

You might also like