0% found this document useful (0 votes)
6 views

SQL-6 Subquery F22

This document provides an overview of subqueries in SQL, including their definition, types, and usage. It covers single-row and multiple-row subqueries, guidelines for their use, and examples of practical applications. Additionally, it discusses handling null values and multiple-column subqueries, along with exercises to reinforce learning.

Uploaded by

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

SQL-6 Subquery F22

This document provides an overview of subqueries in SQL, including their definition, types, and usage. It covers single-row and multiple-row subqueries, guidelines for their use, and examples of practical applications. Additionally, it discusses handling null values and multiple-column subqueries, along with exercises to reinforce learning.

Uploaded by

Amna Noor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

(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
----------
KING
FORD
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
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 7
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 8
Types of Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK

• Multiple-row subquery
Main query
returns CLERK
Subquery
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 9
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 10
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 11
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 JOB
---------- ---------
MILLER CLERK

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


---------- --------- ---------
SMITH CLERK 800

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 13
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 14
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 15
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 16
What Is Wrong
with This Statement?

SQL> SELECT empno, ename


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

ERROR:
ORA-01427: single-row subquery returns more than
one row

no rows selected

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

SQL> SELECT ename, job


2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE ename='SMYTHE');

no rows selected

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


ALL subquery. The overall result is TRUE only if it is TRUE
for ALL of the 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 19
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 ENAME JOB


--------- ---------- ---------
7369 SMITH CLERK
7900 JAMES CLERK
7934 MILLER CLERK

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


--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN

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


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

© 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.
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.
– The comparison with a NULL results in NULL.
– NOT IN operator is equivalent to <>ALL.
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 23
Null Values in a Subquery
– List all employees who do not have any subordinates.
SELECT e.ename,e.job FROM emp e ENAME JOB
WHERE e.empno NOT IN SMITH CLERK
(SELECT m.mgr FROM emp m
ALLEN SALESMAN
WHERE m.mgr IS NOT NULL);
WARD SALESMAN
MARTIN SALESMAN
SELECT e.ename,e.job FROM emp e TURNER SALESMAN
WHERE NOT EXISTS ADAMS CLERK
(SELECT empno FROM emp m JAMES CLERK
WHERE m.mgr = e.empno);
MILLER CLERK

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 24
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 25
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
SALESMAN 30
MANAGER 10
MANAGER 10
CLERK 20

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 26
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 27
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 28
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 29
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 30
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
• select * from dept where not exists
(select * from emp where emp.deptno = dept.deptno)

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 31
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 32
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 33
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 SAL DEPTNO SALAVG


---------- --------- --------- ----------
KING 5000 10 2916.6667
JONES 2975 20 2175
SCOTT 3000 20 2175
...
6 rows selected.

© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 34
Correlated Subquery
• Finding a department without an employee
SELECT * from dept
WHERE NOT EXISTS
(SELECT * from emp where emp.deptno=dept.deptno)

• 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 35
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 36

You might also like