SQL-II
SQL-II
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
3
oracle tor Database Management Administrations [ Oracle s;] Querying Multiple Tables
;;.--
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.
<table2.column3> = <tableN.columnN>
additional -conditions
• <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.
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:
7369
.------
SMITH 20 RESEARCH
7499 ALLEN 30 SALES
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 .
~ 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
.:---
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;
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:
• Self Join
• EMP TAB LE
WORKER
rB Sf ~/Hr,
7 ~-'lb -:;aNb-'3 7 L
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
J
• i i.
~ . [ oracle Bi J
mi n1stra t1ons
UNION
• The UNION clause merges the outputs of two or more q ueries into a single set of rows and
columns .
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:
JOB
CLERK ·
SALESMAN
MANAGER
ANALYS T
►
Example
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
CLERK
MANAGER
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
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:
10
SELECT ename FROM amp
WHERE deptno = 10;
ENAME
KING
CLARK
MILLER
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.
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);
r
3.10 © STG Intl. Ltd.
~
~,1
Oracle for Dat abase Man ageme . istrations [ Oracle Bi 1 Qu erying Multipl
nt Admin e ' ab1
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.
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
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
• EXI STS
• ANY
• SOME
• ALL Operators
• EXISTS
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
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
~
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:
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:
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 '
Flashback
• 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