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

SQL-II

The document provides an overview of querying multiple tables in SQL, focusing on various types of joins such as Equi Joins, Cartesian Joins, Outer Joins, and Self Joins. It explains the syntax for joining tables, the use of table aliases, and the concept of nested queries and SET operators. The document also includes examples and objectives for students to understand how to collate information from different tables effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL-II

The document provides an overview of querying multiple tables in SQL, focusing on various types of joins such as Equi Joins, Cartesian Joins, Outer Joins, and Self Joins. It explains the syntax for joining tables, the use of table aliases, and the concept of nested queries and SET operators. The document also includes examples and objectives for students to understand how to collate information from different tables effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

.

u
Querying M ltiple Tables

..- Snapshots

• Collating Information

• Equi Joins
• Cartesian Joins
• Outer Joins
• Self Joins
• Non-equi Joins
• SET Op~ators
• Union
• Intersect
• Minus
• Nested Queries

• Objectives

After studying this ch


apter, the student shou
ld be able to:
• Understand how to
colla
Joins, Self Joins, Non te information using Equi Joins, Carte
-equi Joins sian Joins, Outer
• Understand the di
fferent SET Operato
rs
• Understand what
are Nested Queries
Collating Informatio
n
• Joins are us ~ to comb
• The connection betwee ine columns from different tables
n
Types of Joins: Equi·Jo tables is established th
ins , Cartesian Joins
OutrougJ~ the WHERE
cla
One of th~ most i~po .
rtant features of SOL • er oms. Self Joins use
and draw information is the . .
from them in terms of
nships between muftip ~
th at>t hty to defin e re latio .
ese relationships , aJI l~
Within a single com
mand· \/(l u•

3
oracle tor Database Management Administrations [ Oracle s;] Querying Multiple Tables
;;.--

joins, the information from any number of tables can be accessed. .

TO join two t~bles, the re~rieval crit~ria will typically spec.ify the c~~dition that a column in the _first table
(which is defined as f~re1gn key ) 1.s .e~ual to a column in the second table ( which is the pm~a~ key
eferenced by the foreign key.) . A Joins where clause may contain additional conditions. In a JOln, the
~able names are listed in the FROM clause, separated by commas.

The syntax for.the select statement where we join two tables:


SELECT <select-list>
FROM' <tablel~, <table2>, . . .... , <tableN>
WHERE <tablel.columnl> = <table2 . column2> and
. . . . . . . .. .
~

<table2.column3> = <tableN.columnN>

additional -conditions

The variables are defined as follows:

• <select-list> is the set of columns and expressions from <tablel> through <tableN>.
• <tablel> through <tableN> are the tables from which column values are retrieved .
• <Columnl> through <columnN> are the columns in <tablel> through <tableN> that are
related.

• Additional conditions are optional query criteria.

We introduce another table, INCR, which holds the information about the salary increments of the
employee. The structure of the INCR table is:


EMPNO NUMBER(4)
AMT
DATEINCR

Equi Joins
NUMBER(7 ,2)
DATE J
When two tables are joined together using equality of values in one or more columns, they make an
Equi Join. Table prefixes are utilized to prevent ambiguity and the WHERE clause specifies the
columns being joined. ·

Examples:

/,? • List the employee numbers, names, department numbers and the department name:
SELECT empno, enam?, [ emp.deptno / dn~e FROM emp, dept
WHERE emp _. deptno = dept.deptno; ·

Here, the deptno column exists in both the tables. To avoid ambiguity, the column name should be
qualified with the table nam~ (or with an alias of table name).

Both the tabl~ names need to be specified ( emp and dept). The WHERE clause defines the joining
condition i.e., joining the deptno of emp table to the dept.no of dept table. Here, it checks for the
equality of values in these columns.
The output will be:

EMPNO. ENAME EMP.DEPTNO DNAME

7369
.------
SMITH 20 RESEARCH
7499 ALLEN 30 SALES

3.2 © STG Intl. ltd.


--
. { oracle Bi 1
Oracle for Database Ma •nis
na gement Adml trat1ons

sALES, ·
75 21 WARD 30 RESEARCH
75 66 JONES 20 sALES .
· 7654 MA RT IN 30 sALES
76 98 BLAKE 30 AccotJNT~NG
77 82 CLARK 10 RESEARCH'
77 88 SCOTT 20 AccotJNTING
78 39 KING 10
78 44
sALES
TURNER 30 RESEARCH
78 76 .ADAMS 20
79 00
sALES
JAMES 30 RESEARCH
79 02 FORD 20 ACCOUNTING
79 34 MILLER 10
79 45
RESEARCH
ALLEN 20
75 26 RESEARCH
MARTIN 20
79 85 SCOTT 30 sALES
t'/ v 0 \.--- -
14 ro ws se le ct ed .

• Using Table Aliases


It can be very tedious
to type in table names di Temporary labels ( 1·
repea or a 1ases)_ca n be
the FROM clause . Th te 1·dy .only for the cu
names are va I rrent select staterne ntus
aliases should also be ese temporary Table aliases can be 1~
spec ified in the select cla
us e. up tO 30 c haracter in· ·
but the shorter they are 1
the better. el'r?:
Note: · The advantage f . table aliases is that it
s o usmg effectively speeds up
the query .
SELECT e.e rn pn o, e.e
na rn e, e. de pt no , d. dn am e FROM amp e,
WHERE e . de pt no a de pt d
d. de pt no ;
✓ Classroom Exercise
Why -do we need to spec
ify the table prefix when
using equi-join ?
• Cartesian Joins
When no join cond ition
clause is specified in WH
row of the other table. Th ERE clause, each row
is results in a Cartesian of one table matches
A product. ev~
SELECT empno, enam
. e, dname, lo c FROM
. . em p, de pt ;
If the num?er of rows are
'
. .
produced Is 56 . 14 and 4 in emp and de
· pt tab les respectively
then the total number
' ol ro,11:
Cartesian product is us
eful in finding out all the
possible comb ·inat·
Example: ion of co1umns from ·tt
dt eren t taUI~
..,.1

~ Cons ide
T b1 r· the
a
following tables and the
. Ho1ds the pri.ncipal am
Tab2 : Holds year an ou nt.
dat
- a present··
d rate of interest
Tab1
PRINCIPAL ·
Tab 2
-- ---- --- YEAR
10 00 - ---- RATE
20 00
l
----
30 00 2 10 ·
3 11
F' d' 4 11 .S
in ing the possible co
mbination · 12
s of calculation of am
ount .
' a Carte sian join of the bi ~
Tab1 and 1'3
oracle for Database Management Administrations [ Oracle Bi] Querying Multiple Tables
.:---

required. The formula for calculation of Amount is Principal*(1 +(rate/1 00))Yea,_

YEAR, RATE, PRINCIPAL*POWER(l+(RATE/lOO) ,YEAR) FROM


SELECT PRINCIPA L,
~ , TAB2; . .

/ \JV.ill produce the following output

pRINCIPAL YEAR RATE PRINCIPA L*POWER (l+(RATE/1 0~) ,YEAR)


---- ----- ---------1 --------- --------------------------
lOOQ 1,0 1100
2600 1 10 2200
3000 1 10 3300
1000 2 11 1232.1
2000 2 11 2464.2
3000 2 11 3696.3
1000 3 11.5 1386.1959
2000 3 11.5 2772. 3918
3000 3 11. 5 4158.5876
1000 4 12 1573.5194
2000 4 12 3147.0387
3000 4 12 4720. 5581
-~
•.

Outer Joins
equi join
If there are any values in one table that do not have corresponding value(s) in the other, in an
that row will not be selected . Such rows can be forcefully selected by using the outer join symbol (+) .
The correspond ing columns for that row will have NULLs.

Example:

In the emp table , no record of the employees belonging to the department 40 is present.
Therefore, in the example above for equi join, the row of department 40 from the dept table
will not be displayed.

~ Display the list of employees working in each department. Display the departmen
t information
. even if no employee belongs to that department:

SELECT empno, ename, emp.dept no, dname, loc FROM ernp, dept
WHERE emp.dept no ( + ' = d~p~.dep tno;

EMPNO. ENAME EMP . DEPTNO DNAME


------ ------ ----------·
---------- RESEARCH
7369 SMITH 20
7499 ALLEN 30 SALES
7521 WARD 30 SALES
7566 JONES 20 RESE'ARCH
7654 MARTIN 30 SALES
7698 BLAKE 30 SALES
7782 CLARK 10 ACCOUNTING
7788 SCOTT 20 RESEARCH
7839 KING 10 ACCOUNTING
7844 TURNER 30 SALES
7876 ADAMS 20 RESEARCH
7900 JAMES 30 SALES
7902 FORD 20 RESEARCH
7934 MILLER 10 ACCOUNTING
7945 ALLEN 20 RESEARCH

3.4 © STG Intl. ltd.


r _::O:.:.r.::
ac:::.:l.:::

752 6
798 5
e....:.f~
or~ D~a:':
ta~b~a~s~

MARTIN
e ~M~a~n~a~g!!:e~m

20
~e:!n~t.!_A~d~m~i~n~is:!!tr!a~tio~n~s~[~O~ra~c~le~8~,~

RESEARCH
-1__ __ __;::.
a:-u_e~ry::....i_
n -=-g_M_u_l-'
t1P
'~
-

SCOTT
30 SAL ES
40 OPERATIONS
14 row s sel ect
ed .

l
If the sym bol ( + ) Is plac ed on
the othe r side of the equ atio n then
detalls with no corr esp ond ing dep
artm ent name and loca tion , will
b:lld!=e1:mptoyee
NULL values In DNAME and LOC p Yed Ytltti
colu mn.
• Rules to place (+) ope rato r:

• The outer join symbol ( + ) can not


be
• We can not "out er join" the sam on both the sides .
e table to more than one other tabl
statement. e in a sing le SELECi
• A. condition involving an outer join may
not use the IN operator or be linked
the OR operator. to ano ther condition by

• Self Join

To join a table to itself means that


each row of the table is combined with
row of the t~ble. The self join can be itse lf a nd wi th eve ry Other
viewed as a join of two copies of the
actually copied , but SQL performs same table. The tabl e is not
the command as though it were .
T_
h e syntax of the command for joini
ng a table to itself is almost the sam
diffe rent tables. To distinguish the e as that for join ing two
column names from one another, alias
are use d, since both the tables have es for the actu al tabl e name
clau se of the que ry. the same name. Table name aliases
are defi ned in the FROM
·
To defi ne the alias, one space is iett
after the table name and the alias.
Example:

• EMP TAB LE

EMPNO ENAME MGR


7839 KING
7566 JONES 7839
7876 ADAMS 7788
7934 MILLER 7782

Con side r the emp tabl e sho wn


above. Primary key of the emp
emp loye e's man age r is just ano ther table is em .
row in the EMP table whose EMPNO
som e othe r row. So e~r y emp loye is stor~~o_- ~ etai ls of each
e exce pt man age r has a Manage r.
that refe renc es emp no . To list out The refo re in . GR col_ u mn of
the nam es of the man age r with the
join EMP with itself. employee MGR is a f~re1gn key
.
reco rd one will hav e to
SELECT WORKER.ename, MANAGE
R.ename 'Ma nag er •
FROM e~p WO ~R ,'" emp MANAGE
R
WHERE WORKER. mgr = MAN A~E R. emp no;. .
Whe re WO RKE R and MAN AGE
R are two aliases for the EMP tabl
tabl es.
, e a nd acts as a virtual
_ a_
as_e_M m_in_is_t_
na_,g:....e_m_e_n_t _A_d_ .:::..:..::
ns~ [ O
ra_ti___o___ .::.=
le:...:8~i.1.J_ _ _ _ _~Q~u~e~ry~in~g~M
ra:.:::c:::: le~s
pl..:..e_T_a_b-..:
ul~ti!:..
r =-
cle f,~o::.. at_a_b_
D::...
~
EMP TABLE
EMPNO ENAME MGR
7839 KING
7566 JONES 7839
7876 ADAMS 7788
7934 MILLER 7782·

WORKER

rB Sf ~/Hr,
7 ~-'lb -:;aNb-'3 7 L

en/. /4 D.Atv!S ..., ~ j


7
; q 3 q.. MILLE (.. 1 t'

The output will be:


Manager /; NA M ~
ENAME
= -'JON ~
SCOTT JONES
FORD JONES ,A-DAj\11. )
ALLEN BLAKE
WARD BLAKE rvt Jt.)_€/..._
JAMES BLAKE
TURNER BLAKE
MARTIN BLAKE
MILLER CLARK
ADAMS SCOTT
KING
JONES
CLARK
BLAKE
KING
KING
II
SMITH

13 rows selecte d.
FORD
1/ ~
I Classroom Exercise
In the previous query, only 13 rows (Not 14) have been retrieved. Why ?

\ / List all emp~oyees who joined the company before their manager .
./.,ELECT e.ename , e . hiredat e, m. ename manager , m.hired ate
FROM emp e, emp m
WHERE e.mgr = m.empno
and e.hired ate < m..ftired ate

ename hiredat e manager Hiredat e


------- - ------- --------
ALLEN 15-AUG-83 BLAKE ll-JUN-8 4
WARD 26-MAR-84 BLAKE ll-JUN-8 4
MARTIN 05-DEC- 83 BLAKE ll-JUN-8 4
TURNER 04-JUN- 84 BLAKE ll-JUN-8 4
MILLER 21 - NOV-83 CLARK 14-MAY-84
JONES 31-0CT- 83 KING 09-JUN- 84
BLAKE ll-JUN-8 4 KING 09-JUL- 84
CLARK 14-MAY-84 KING 09-JUL- 84
.SMITH 13-JUN- 83 FORD 05-DEC- 83

3.6 © STG Intl. Ltd.

J
• i i.
~ . [ oracle Bi J
mi n1stra t1ons

j Oracle for Database Management Ad

SET Operators . . type from one or more than one t


. information of s1m11ar able
• SET Operators are used to combine t be the same
• oatatype of corresponding columns ~tare :
• The types of SET operators in ORA ond query, less duplicate rows
. lus rows of sec
• UNION : Rows of first query p II the queries
.C on rows from a
• INTERSECT · ornrn . the first query
• .MINUS : Rows unique to
. . . to one result.
SET operators combine more queries 1n
two or
Suppose we want following three deta1·1s from dept table
. . . d rtment 20 and 30
• List of all the different designations in ep~
• List the jobs common to department 20 30
an
• List the jobs·uniqueto departm!:)nt 20. NTERSE CT and MINUS
. T O erators UNION, I are
To get tt~se combination of information the SE P
used.

UNION

• The UNION clause merges the outputs of two or more q ueries into a single set of rows and
columns .

The syntax of UNION operator is

select <stmtl>
UNION
select <stmt2>
[order-b y-claus e]

'
The variables are defined as follows :

• select stmtl and sele~t stmt2 are valid SELECT statemen ts.
• o rder-by -clause is optional and it references the columns by number rather
than by name.
The queries are all executed independently, but their output is merged. Only the
final query ends with
a semicolon .

Example s:

Display the different designations in department 20 and 30 :


SELECT job.FROM emp
WHERE deptno = 20
UNION
SELECT job FROM e~p
WHERE deptho 3 0;

The output will be:

JOB

CLERK ·
SALESMAN
MANAGER
ANALYS T

cie t()( Oataba10 M,.1Mger,M,nt Admin,s1rat,0na I Or~c,;Jo a, I-


Of! --- - . - -

point• to bt kept In mind wh ll(J using UNION operato r.


the final result of the
, The two select statement may not contain an ORDER BY Clause, howev 6 r.
entire UNION operation can be ordered
columns retrieved by
• The number of columns retri&ved by first s~lect mu6t be equal to number of
second select.
• n,e data types of columns rctneved b, the ael<:ct &Latamenla should be same
, The optional ordor /Jy c/auso differs from tho usual ORDER BY clause 1n
a SELECT statement
for orcl1::rmg mu6t bo referenced by a number rather tha n name. The
i,ecause the column& used
not requ,re that the
reason 1hat the columns must bo r&f orenced by number 15 the SOL does
names re trieved by second
column name rotneved by first !>elect be Ident1col to the columns
select

Example

,elect ompno , onomo fro m emp


where deptno •l0
UNI ON
ael act o.mpno, a na.me f rom amp
where dep t no• 30
o rdor by l

E.HPNO. EN.AME

749 9 ALLEN
7521 WAAO
7654 HARTIN \
7698 BLAKE
7839 KING
78 4 4 TORNER
790 0 J AMES
7934 MILLER

. INTERSECT

• The intersect operator returns the rows that are common between two sets of rows.
key word is replaced by
The synlax of INTERSECT operator is same as UNION operator . Only UNION
INTERSECT.

select atmtl
INTERSECT
select stmt2
[order- by-clau se]

Example

,. ~ • )d$tthe jobs common to department 20 and 30:


~ SELECT j ob FROM emp WHERE deptno =- 20
INTERSECT
SELECT job FROM emp WHERE deptno = 30;
JOB

CLERK
MANAGER

3.8 © STG Intl. Ltd.


~
0
~ e for Database Man arJe rnen t Admin1st Querying Mult iple
-- ~ 7
-- rat1ons [ Or~ - 1
1
MINUS

• Minus operator returns the rows unique


to first query . t .
The syntax for using the MIN US oper ti f r the union opera or.
ator rese mbles 1 e synt ax o
s olo ct o tmt l
INTERSECT
s ele ct s t.m t2
l ord ar - by - o lau so)

The requ irement s and considerati ons ator are essentia lly the same as th
tor using the MINUS oper
for the INTER SEC T and UNI ON oper ose
a tors.
To illus trate th e use of the MINUS oper . h following example .
ator , consider t 8
List the Jobs unique to department 20:
SEL ECT J Ob FROM a mp
WHERE dep tno ::: 20 ✓
MINUS
SELECT job FROM amp
WHERE dep tno .. 10 /
MIN US
SELECT job FROM emp
WRERE dep tno = 30;
Job

ANALYST
/
✓ Clas sroo m Exercise

Can we rewrite the query to find jobs


that are unique to department 20 as :
SELECT job FROM emp WHERE dep
tno = 20
MINUS
SELECT job FROM emp WHERE dep
tno IN( l0,3 0);
4 ested Queries
• The result of inner query is dynamica
lly substituted in the condition of oute
• There is no practical limitation to the r query
level of nesting of queries in Oracle Bi
• When using relational operators , ensu
re that the sub query returns a single
• In some cases , the DISTINCT clause column output
can be used to ensure single valued
outp ut
SOL has an ability to nest queries
with in one another. A subquery is a
nested within another SELECT state SEL ECT statement that is
ment and-which returns intermediate
the inner query (or sub query) within results. SQL first evaluates
the WH~~E clause. The inner query
tested in the pred ict of the outer quer generat es values that are
y, dete rmining when it will be true . The
is then substituted in the condition of return value of inner querf
the outer query.

• Advantages of Nested queries

• Subqueries allow a de~eloper to build


powerful comminds out of simple one
• The nested subquery is ~ery useful s. ..
that dep end s on the data 1n the table "."'hen you need to select rows from a tabl
itself. e ·with a conditlOll

3.9
© STG Intl. Ltc
(I

_a
~t_ab_a_s_e_M
~a _ dm
_n_a~g~e_m_e_n_tA ~r~a~cl~e~8~i L]_ _ _ _~Q~u~e~~i~n~g~M~u~lt~ip~le~T
~n2 s~[~O
_ in_is_tr~a~tio s
~a~b~le~
08 m,r~D
~

E,aunple:
List the employees belonging to the department of MILLER:

Here, we do not know the department to which MILLER belong~ So h t determine


the department of MILLER and use that department number to find out'·t~: ot~~~ e~ployees of
that department.
SELECT deptno FROM amp
WHERE ename = 'MILLER' ;
DEPTNO

10
SELECT ename FROM amp
WHERE deptno = 10;
ENAME

KING
CLARK
MILLER

Combining the above two queries:

SELECT ename FROM emp


WHERE deptno = (SELECT deptno FROM emp WHERE ename ='MILLER ');

List the names of the employee drawing the highest salary:


SELECT ename FROM emp
WHERE sal = · (S~~ECT MAX (sal) FROM emp);

Using Aggregate Functions In Subqueries

Aggregata function produces single value for any number of rows. We want to see all employee details
whose salary is greater than average salary of employees whose hiredate is before '01-04-81'. For
this we need to use aggregate function in inner query.

/ SELECT* from em~


where Sal>
(select avg(sal) fom emp
where hiredate< '0l-APR-8 1');

Subqueries in Having

We can also use subqueries within the Having clause. These subqueries can use their own aggregate
functions as long as they do not produce multiple values .or use GROUP BY or HAVING tt,emselves.
'
List the employee number, name, total number of increments and total increment amount for
the employee who has got maximum number of increments:
SELECT incr.empn o, ename, COUNT(*), SUM (amt) FROM emp, incr
WHERE_in ct.empho = emp~empno . .
GROUP BY ·incr.empn o, ename
HAVING COUNT(*) = (SELECT ~(COgNT_ (*)) from incr
- GROUP BY empno);

The output will be:

r
3.10 © STG Intl. Ltd.
~
~,1
Oracle for Dat abase Man ageme . istrations [ Oracle Bi 1 Qu erying Multipl
nt Admin e ' ab1

coUNT C * ) sUM (AM T)


EMPNO ENAME
--- --
736 9 SMI TH 3 500

List the job with highest ave rag


e salary.
SELECT job , AV G(s al)
FROM amp
GROUP BY job
HAV ING AVG (sa l) (SELECT MA X(A V~ (sa l))
FROM emp
GROUP BY j-ob ) ;

The output will be:

JOB AVG(SAL)

PRESIDENT 500 0 .
.
The !nner_query fir~t finds the
function picks the h1ghe~t ave
average
The GROUP BY clause in therag~ salary. .
1
s~~it
for each diff ere nt job gro up,
value (5000) is use d in _the
eded because the main que
and the MAx
HAVING clause.
main query 1s ne ry's SELECT list
contains both an aggregate and
non-aggregate column .
/ Distinct Clause with Subque
ries
/ Distinct clause is used in som
e cases to force a subquery
want to find the details of the to generate a single value.
department whose manager's Suppose we
shown below . empcode '76 98' · Th e query
for this is
Se lec t* fro m dep t
wh ere de ptn o= (Se lec t di
sti nc t dep tno fro m em
p wh ere mg r=• 7~ 98 ') ;
The inner query will give the
deptno whose manager's em
. -=-
inner query would have retu pcode is '7698'. W itho ut dis
rned more than one row as tinct cl!u se the
ma nager's empcode is '7698'. the re are mo re tha n one emplo
yee whose
• Su bqu erie s that retu rn mo
re than one row
When a subquery returns mo
re than one row we need to use
multiro w com par iso n ope rat
Example or.

List the nam es of the emplo yee


s , who have got an increm ent
• I :
SEL EC T erlame FROM emp
WHERE emp no IN ( SEL
EC T empno FRO~ i~c r);
He re, the inner query returns
relational ope rato r(= ). multiple values
'
hence, the
IN ope rat or is use d instead
of a
Lis t the names of the employee
s, who earn lo t .
- wes sal ary in eac h dep art me
SE LEC T ena me , sa l , nt:
d ep tno
FROM em
WHERE sa l I N ( SELEC
T MIN ( sal ) FROMP
. '
He re the inn er query has a e mp GROUP BY de pt no );
. GROUP BY
val ue . In t h1s cas e, th e IN ope 1 se Th·
rato r must becau ·
on e
- ts me ans it ma y retu rn mo
re than
use~ bec aus e it exp ect s a
li st of val ues .
l •
_i_n_is_tr_a_tio_n_s_[~O
_en_t_A_d_m
as_e_M_a_n_ag=-e_m :: M
:.:i.2.l_ _ _ _ _....,:O~u~e:::.ryLi:n~g...:.
ra:..:c~le~8
.:....:..: tip:.-l_
~u:._l~ s
le..:..
e_T_a...::.b-=
r =-
1 fo.:... at:._a_b_
D.:..
~

The following points should be kept in mind while wrltting subqueries:

The inner query must be enclosed in parentheses.


1
· The inner query must be on the right hand side of the condition .
2
· The subquery may not have an order by clause .
3 t.
· The ORDER BY clause appears at the end of the main select statemen
4 nested to the least deeply nested unless
s are always executed from the most deeply
5 · Subquerie '
· they are correlated subqueries.

correlated Subquer y
'candidate row'
A correlated subquery is a nested subquery which is executed once for each
the outer query.
considered by the main query and which on execution uses a value from a column in
value present
In a correlated subquery , the column value used in inner sub query refers to the column
. The subquery is executed repeatedly, once for each
in the outer query forming a correlated subquery
row of the main (outer) query table .

List the employee numbers and names, who have got more than 1 increments:
SELECT mpnQ, ename FROM emp
WHERE 1 ~ ~ - - - - - - -- ~ - - - - - - - -_ _
Correlated,
( SELECT COUNT ( *) FROM same column
WHERE empno = mp.empn o
EMPNO ENAME .

7369 SMITH
7788 SCOTT
7900 JAMES
7934 MILLER
nt.
List employee details who earn salary greater than the average salary for their departme

SELECT empno, ename, sal, deptno


FROM emp e
WHERE sal > (Select AVG(sa l) FROM emp WHERE deptno= e.deptn o)

empno Ename sal deptno


------
7839 KING 5000 10
7566 JONES 2975 20
7788 SCOTT 3000 20
7902 FORD 1600 30
7698 BLAKE 2850 30

5 rows seleted .
alias
Remember, a correlated subquery is'·signaled by a column name, a table name or table
to the value of a column in each candidate row of the outer
in the WHERE clause that refers
the main
select. Also the correlated subquery executes repeatedly for each candidate row in
query.
on the
Correlated subquery is used to answer multi-part questions whose answer depends
is normally executed once for each
value of each row of th~ parent query. The inner select
candidate row.

✓ Classroom Exercise

How are nested queries different from joined queries ?

3.12 © STG Intl. Ltd .


Querying Multip
. [ orac le Bi]
0 racle for Data base Management Admt.n 15
· trat1ons

Using Spec ial Oper ators in Subq uerie 5

Some Special operators used in subqueries are:

• EXI STS
• ANY
• SOME
• ALL Operators
• EXISTS

• Th is operator is used to check for the exiS tence


of values
• This operator produces a Boolean result
·t to True if the subq uery produces any
It tak es a subquery as an argument and evalu
ate: ~n output.
output and False , if the subquery does not produ
c Y
• ANY , SOME and ALL

• Used along with the relational operators


.
• Similar to IN operator, but only used in subquene
• s
The SOME and ANY operator can be used interc
hang eably

EXISTS operator
The EXISTS operator is frequently used with
correlated subqueries. It _tests whe ther a
(NOT EXISTS ensure for nonexistence of ~al_ue is there
values). If the value exist s 1t retur ns TRU
exists it returns FALSE. E; if t does not
1

NOT EXISTS operator is more reliable if the


subquery returns any NULL value s.
Examples:

List all employees who have atleast one perso


n reporting to them.
SELECT empn o, enam e, job, dept no
FROM emp e
WHERE EXISTS (SELECT empno from emp
WHERE emp. mgr = e.em pno)
ORDER BY empn o;

Empno enam e Job dept no


7566 JONES MANAGER
------
20
7698 BLAKE MANAGER 30
7782 CLARK MANAGER
7788 10
SCOTT ANALYST
7839 20
KING PRESIDENT
7902 10
FORD ANALYST 20
List the employee details if and only if
num ber 10: more than 10 em lo
P yees are present in depa rtment
SEL ECT * FROM emp
WHERE DEPTNO = 10
AND EXISTS (SELECT
WHERE dept no = 10 COUNT ( *)
FROM emp
GROUP BY dept no
HAVING COUNT(*)
> 10);

3.13
[o
on__s::.....L
_ in_is_tr_a_ti_ ra:.::c~le~·a:'. ';..!.
=-:...:: p~
lti!'..
. J_ _ _ _ _~Q~u~e:t~in~gL:M~u~ '.:~b~le~s
le~T'.. a
_dm
_a_n_a"""'g_e_m_e_n_tA
iefo::,:.r_D_a_ta_b_a_s_e_M
~

the increment amount is greater


• List the names of employees from the employee table where
increment is greater than s:
than 1000 and the number of employees receiving the same
SELECT anama FROM amp
WHERE ampno IN (SELECT empno FROM incr
WHERE amt> 1000
AND EXISTS (SELECT COUNT(*)
FROM incr GROUP BY amt
HAVING coun t(*) > 5));

List all the employees details who do not manage any one.
SELECT ename , job FROM emp e
mgr=e .empn o);
WHERE NOT EXIST S (SELECT mgr FROM emp where

The output is

Enama Job
-------- ----- ---
SMITH CLERK
AD.AMS CLERK
ALLEN SALESMAN
WARD SALESMAN
MARTIN SALESMAN
TURNER SALESMAN
JAMES CLERK
MILLER CLERK

✓ Classroom Exercise
NOT EXISTS in the above query ?
What will be the output if we use NOT IN operator instead of

• ANY operator

The ANY operator compares the lowest value from the set
lowest salary of an employee
List the employee names whose salary is greater than the
belonging to department number 20:

SELECT ename FROM emp


o = 20);
WHERE sal > ANY (SELECT sal FROM amp WHERE deptn
-
List the employee details of those employees whose salary
is greater than any of the
managers:

SELECT EMPNO, EN.AME , SAL FROM EMP WHERE SAL >


~

SELECT SAL FROM EMP WHERE JOB = 'MANAGER' ) ;

ALL Operator
selected by the subquery satisfies the
In case of ALL operator the predicate is true if every value
condition in the predicate of the outer query.

Examples
highest salary of all employee
List the employee names whose salary is greater than the
belonging to department number-20:

3.14 © STG Intl. Ltd ..


Quer ying Multiple
. [ oracl e Bi l 1ab1~
Oracle for Database Management Adl'T1 I•nistrat1ons

RE dept no =
20);
SELECT ena me FROM amp l FROM emP WffE
WHE RE s a l > ALL ( SELECT sa
o belong to depa ~men t number 20. 1h
mployees wh hose salary 1s greater than
Th e inner query returns salary of al ~f that empl
1
oye~ w
au e
outer query selects employee name rtment numb the
er 2 ·
em ployees· salary who belong to depa
highest paid MANAGER:
. more than the
List the detail s of the employee earning
> ALL (
SELECT empn o , enam e , sal FROM emp WHERE sal
AGER')·
SELECT sal FROM emp WHERE J· ob = •MAN '

✓ Class room Exercise

What is the special feature of a sub-query?

Flashback

• Joins are used to combine columns from different


tables
. . .
The different types of joins are: equ1 Joins , Carte • ·oins outer joins , self joins and non-equi
• sian J ·
joins

• Joining condition is speci.fied .in the WHERE claus f the SELE CT state ment
eo
• · equa 11ty
When two tables are joined together using · of va Iu es in one or more colum ns, they make
an Equi Join

• Without any joining condition the join becomes a


Cartesian join
• Joining a table with itself is known as Self Join

• Self Join is possible by providing table name aliase


s for the table
• With joins, the names of all the tables to be joined
, need to be spec ified
• To select a row forcefully which cannot be selec
ted using equi join outer join symbol (+).is
used ·

• Set operators are used to combine results from


different queri es. The oper ators used are
UNION , INTERSECT and MINUS

• The UNION clause merges the outputs of two


or more queri es into a s·
columns with all the common elements t f rows and
mg 1e se 0

• The intersect operator returns the rows that are


common betwe tw
en o sets of rows
• Minus operator returns the rows unique to first query

• Nested queries are used in a situation where


the cond T
outcome of an inner query I
ion of the quer y is depe nden t on the
• Subqueries can also used within the HAVING Claus
e
• A correlated subquery is a nested subquery which
is
cons idered by the main query and which on exec ,
ur executed once for each 'cand idate row
query . ion uses a value from a colum n in the outer

You might also like