You are on page 1of 51

Subqueries

Chapter 6

Objectives
After completing this lesson, you should be able to do the follovving:
Describe the types of problems that

subqueries can solve Define subqueries

List the types of subqueries Write single-row and multiple-row subqueries

Using a ubquery to olve a !roblem


"Who has a salary greater than #ones$%"

"Which employees have a salary greater than #ones$ salary%"


"What is #ones$ salary%"

ubqueries
SELECT select_list FROM table

WHERE expr operator ( SELECT FROM select_List table );

&he subquery 'inner query( e)ecutes

once before the main query*


&he result of the subquery is used by

the main query 'outerquery(*

A subquery is a SELECT statement that is embedded in a clause of another SELECT statement. You can build powerful statements out of simple ones by usin subqueries. They can be !ery useful when you need to select rows from a table with a condition that depends on the data in the table itself. You can place the subquery in a number of S"L clauses #$%E&E clauss #%A'()* clause #+&,- clause ln the synta./ operator includes a comparison operat0r such as >, 12 or ()

Note: Comparison operutors fall i33to two classes4 sin le5row operators ( > , = , 61 2 7 2 < > , <= ) and multiple5row operators 8 () 2 A)Y 2 ALL 9.

;sin a Subquery
SELECT ename +&,- E-< $%E&E sal 6 8 SELECT sal +&,- emp $%E&E empno1=>??9/
ENAME +,&@ SC,TT A()* +,&@

;sin a Subquery
SELECT ename2 sal2 deptno2 Cob +&,- E-< $%E&E Cob 1 8 SELECT Cob +&,- emp $%E&E empno1=:?D9/
ENAME A@A-S FA-ES -(LLE& S-(T% A@A-S FA-ES -(LLE& = rows selected. SAL 11EE D>E 1:EE GEE 11EE D>E 1:EE DEPTNO 2E :E 1E 2E 2E :E 1E CLE&A CLE&A CLE&A CLE&A CLE&A CLE&A CLE&A O!

>

SELECT ename2 sal2 deptno +&,- E-< $%E&E sal () 8 SELECT -()8sal9 +&,- emp *&,;< HY deptno 9/
ENAME FA-ES S-(T% -(LLE& SAL D>E GEE 1:EE DEPTNO :E 2E 1E

SELECT empno2 ename2 Cob +&,- emp $%E&E sal 7 A)Y 8 SELECT sal +&,- emp $%E&E Cob 1 ICLE&AI 9/
EMPNO =:?D =DEE =G=? =>21 =?>B ENAME S-(T% FA-ES A@A-S $A&@ -A&T() O! CLE&A CLE&A CLE&A SALES-A) SALES-A)

SELECT empno2 ename2 Cob +&,- emp $%E&E sal 7 A)Y 8 SELECT sal +&,- emp $%E&E Cob 1 ICLE&AI 9 A)@ Cob 76 ICLE&AI /
EMPNO ENAME =>21 $A&@ =?>B -A&T() O! SALES-A) SALES-A)

SELECT empno2 ename2 Cob +&,- emp $%E&E sal 6 ALL 8 SELECT sal +&,- emp $%E&E Cob 1 ICLE&AI 9 A)@ Cob 76 ICLE&AI /
EMPNO =BDD =>?? =?DG ==G2 ==GG =G:D =GBB =DE2 G rows selected. ENAME ALLE) F,)ES HLAAE CLA&A SC,TT A()* T;&)E& +,&@ O! SALES-A) -A)A*E& -A)A*E& -A)A*E& A)ALYST <&ES(@E)T SALES-A) A)ALYST

SELECT empno2 ename2 Cob +&,- emp $%E&E sal 6 ALL 8 SELECT A'*8sal9 +&,- emp *&,;< HY deptno 9 /
EMPNO =>?? ==GG =G:D =DE2 ENAME F,)ES SC,TT A()* +,&@ O! -A)A*E& A)ALYST <&ES(@E)T A)ALYST

1E

+uidelines for Using ubqueries


,nclose subqueries in parentheses*
!lace subqueries on the right side of the

comparison operator* subquery*

Do not add an -.D,. /0 clause to a Use single-row operators with single-

row subqueries*

Use multiple-row operators with

multiple-row subqueries*

11

&ypes of ubqueries
ingle-row subquery 1ultiple-row subquery 1ultiple-column subquery

Types of Subqueries Sin le5row sub ueries4 -uliple5row subqueries4 -uliple5column subqueries4 "ueries that return only one row from the inner SELECT stnten3ent ";E&(ES that return more than one rows from the inner SELECT statement ";E&(ES that return more than one column from the inner SELECT statement.

12

ingle-.ow ubqueries
.eturn only one row

Use single-row comparison operators

Operator

Meaning Equal to

2 3 32 4 <= <> " #$

Greater than
Greater than or equal to Less than Less than or equal to Not equal to

SELECT ename2 Cob +&,- E-< $%E&E Cob 1 8 SELECT Cob +&,- emp $%E&E empno1=:?D 9 / ENAME A@A-S FA-ES -(LLE& S-(T% A@A-S FA-ES -(LLE& = rows selected. CLE&A CLE&A CLE&A CLE&A CLE&A CLE&A CLE&A O!

1:

E.ecutin Sin le5&ow Subqueries

1B

Using +roup 5unctions in a ubquery


SELECT ename2 sal2 deptno +&,- E-< $%E&E sal () 8 SELECT -()8sal9 +&,- emp *&,;< HY deptno 9 / ENAME S-(T% FA-ES -(LLE& SAL GEE D>E 1:EE DEPTNO 2E :E 1E

1>

6A789+ :lause with ubqueries


&he -racle erver e)ecutes subqueries

first* &he -racle erver returns results into the 6A789+ clause of the main query*
SELECT Cob2 A'*8sal9 +&,- emp *&,;< HY Cob %A'()* A'*8sal9 1 8 SELECT -()8A'*8sal99 +&,- emp *&,;< HY Cob 9/ O! CLE&A A%&(SAL) 1E:=2>

1?

What 8s Wrong With &his tatement%


SELECT +&,$%E&E empno2 ename emp sal 1 8SELECT +&,- emp *&,;< HY deptno9/ -()8sal9

(SELECT *

MIN(sal)

E&&,& at line B4 ,&A5E1B2=4 sin le5row subquery returns more than one row

1=

$ill This Statement $orJK


SELECT ename2 Cob +&,emp $%E&E Cob 1 8 SELECT Cob +&,emp $%E&E ename 1 IS-YT%EI 9 /
no rows selected

1G

1ultiple-.ow ubqueries

.eturn more than one row

Use multiple-row comparison operators


-perator
89 A90 ALL

Meaning Equal to any member in the list Compare value to ea h value returne! by the subquery Compare value to every value returne! by the subquery

SELECT #$OM %&E$E

ename" sal" !eptno emp sal 'N (SELECT M'N(sal) #$OM emp G$O*+ ,- !eptno).
SAL GEE D>E 1:EE DEPTNO 2E :E 1E

ENAME S-(T% FA-ES -(LLE&

1D

Using A90 -perator in 1ultiple-.ow ubqueries


SELECT ename2 sal2 Cob +&,- emp $%E&E sal 7 A)Y 8 SELECT sal +&,- emp $%E&E Cob 1 ICLE&AI 9 A)@ Cob 76 ICLE&AI / ENAME $A&@ -A&T() SAL 12>E SALES-A) 12>E SALES-A) O!

2E

Using ALL -perator in 1ultiple-.ow ubqueries


SELECT ename" sal" /ob #$OM emp %&E$E sal 0 1LL ( SELECT 12G(sal) #$OM emp G$O*+ ,- !eptno ).
ENAME F,)ES SC,TT A()* +,&@ SAL 2D=> :EEE >EEE :EEE O! -A)A*E& A)ALYST <&ES(@E)T A)ALYST

21

ummary
ubqueries are useful when a query is based on un;nown values*

22

SELECT +&,- table $%E&E e.pr

select_list

8SELEECT +&,- table $%E&E e.pr 9/

select_list

2:

!ractice -verview
:reating subqueries to query values based on un;nown criteria Using subqueries to find out what values e)ist in one set of data and not in another

1. $rite a query to display the employee name and hiredate for all employees in the same department as HlaJe. E.clude HlaJe.
SELECT ename2 hiredate +&,- emp $%E&E deptno 1 8 SELECT deptno +&,- emp $%E&E ename 1 IHLAAEI9 A)@ ename 76 IHLAAEI/ 2. Create a query to display the employee number and name for all employees who earn more than the a!era e salary. Sort the results in descendin order of salary. SELECT empno2 ename +&,- emp $%E&E sal 6 8 SELECT A'*8sal9 +&,- emp 9/

:. $rite a query to display the employee number and name for all employees who worJ in a department with any employee whose name contains a T. Sa!e your S"L statemant in a file called p?q:.sql .
SELECT empno2 ename +&,- emp $%E&E deptno () 8 SELECT deptno +&,- emp $%E&E ename L(AE ILTLI 9/

2B

B. @isplay the employee name2 department number2 and Cob title for all

employees whose department location is @allas. Solution with subquery4


SELECT ename2 empno2 Cob +&,- emp $%E&E deptno 1 8SELECT deptno +&,- dept $%E&E loc 1I@ALLASI9 /

Solution with equiCoin4


SELECT ename2 empno2 Cob +&,- emp e2 dept d $%E&E e.deptno 1 d.deptno A)@ d.loc1I@ALLASI/ ENAME S-(T% F,)ES SC,TT A@A-S +,&@ EMPNO =:?D =>?? ==GG =G=? =DE2 CLE&A -A)A*E& A)ALYST CLE&A A)ALYST O!

>. @isplay the employee name and salary of all employees who report to

Ain . Solution with self Coin4 SELECT e.ename2 e.sal +&,- emp e 2 emp d $%E&E e.m r 1 d.empno A)@ d.ename 1IA()*I/ Solution with subquery4
2>

SELECT ename2 sal +&,- emp $%E&E m r 1 8SELECT empno +&,- emp $%E&E ename 1 IA()*I 9/ ?. @isplay the department number2 name22 and Cob for all employees in the Sales department. SELECT e.deptno2 e.ename2 e.Cob 2 d.dname +&,- emp e 2 dept d $%E&E e.deptno 1 d.deptno A)@ d.dname 1 ISALESI (f yo u ha!e time2 complete the followin e.ercises4
=. -odify p6q3.sql to display the employee number2 name2 and salary for all

employees who earn more than the a!era e salary and who worJ in a department with any employee with a T in their name. &erun your query.
SELECT empno2 ename 2 sal +&,- emp $%E&E sal 6 8SELECT A'* 8sal9 +&,- emp 9 A)@ deptno () 8 SELECT deptno +&,- emp $%E&E ename L(AE ILTLI9/
EMPNO =DE2 +,&@ ==GG SC,TT =>?? F,)ES =?DG HLAAE ENAME SAL :EEE :EEE 2D=> 2G>E

2?

Exists (n the pre!ious section2 we used 'N to linJ the inner query and the outer query in a subquery statement. 'N is not the only way to do so 55 one can use many operators such as 62 72 or 1. E('STS is a special operator that we will discuss in this section. E('STS simply tests whether the inner query returns any row. (f it does2 then the outer query proceeds. (f not2 the outer query does not e.ecute2 and the entire S"L statement returns nothin . The synta. for E('STS is4 SELECT )col*+,_,-+e.) FROM )t-ble_,-+e.) WHERE E('STS ( SELECT / FROM )t-ble_,-+e0) WHERE 1Co,2itio,3 )

2=

SELECT e,-+e" 2e4t,o FROM e+4 WHERE E('STS (SELECT / FROM e+4 WHERE s-l 56788 )
ENAME SM'TH ALLEN WARD ONES MART'N !LA9E CLAR9 SCOTT 9'N& T:RNER ADAMS AMES FORD M'LLER .; <o=s <et*<,e2 i, 8"8. seco,2s DEPTNO 08 68 68 08 68 68 .8 08 .8 68 08 68 08 .8

SELECT e,-+e" 2e4t,o FROM e+4 WHERE E('STS (SELECT / FROM e+4 WHERE s-l 56788 )
,o 2-t- >o*,2

2G

WHERE cl-*se
-ost often2 the subquery will be found in the $%E&E clause. These subqueries are also called ,este2 s*b?*e<ies.

select / ><o+ -ll_t-bles t-bs =@e<e t-bsAt-ble_,-+e i, (select colsAt-ble_,-+e ><o+ -ll_t-b_col*+,s cols =@e<e colsAcol*+,_,-+e # BENAMEB);
Li+it-tio,s: ,racle allows up to 2>> le!els of subqueries in the $%E&E clause.

2D

FROM cl-*se
A subquery can also be found in the +&,- clause. These are called i,li,e vie=s. +or e.ample4

select dept.deptno, subquery1.total_amt from dept, ( select emp.deptno, Sum(emp.sal) total_amt from emp group by deptno) subquery1 WHERE subquery1.deptno = dept.deptno

E!"#$ () 1) /)
( ro0s returned 1n ),)/ seconds

"$"%&_%'" *+)) ,-.) 1),-.

(n this e.ample2 weI!e created a subquery in the +&,- clause as follows4

( select emp.deptno, Sum(emp.sal) total_amt from emp group by deptno) subquery1


This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields. Li+it-tio,s: ,racle allows an unlimited number of subqueries in the +&,- clause.

:E

SELECT cl-*se
A subquery can also be found in the SELECT clause. +or e.ample4

select tblsAo=,e<" tblsAt-ble_,-+e" (select co*,t(col*+,_,-+e) -s tot-l_col*+,s ><o+ -ll_t-b_col*+,s cols =@e<e colsAo=,e< # tblsAo=,e< -,2 colsAt-ble_,-+e # tblsAt-ble_,-+e) s*b?*e<C0 ><o+ -ll_t-bles tbls;

,$)E& SYS SYS SYS SYS SYS SYSTESYSTECTOSYS CTOSYS CTOSYS -@SYS -@SYS -@SYS -@SYS -@SYS

TAHLEM)A-E @;AL SYSTE-M<&('(LE*EM-A< TAHLEM<&('(LE*EM-A< ST-TMA;@(TM,<T(,)M-A< A;@(TMACT(,)S @E+NMTE-<NL,H %EL< @&N,HFECTMATT&(H;TE @&N<,L(CYMTAH @&N);-HE&MSE";E)CE ,*(SMS<AT(ALM&E+E&E)CEMSYSTE-S ,*(SM*E,-ET&YMC,L;-)S S@,M;)(TSM,+M-EAS;&E S@,M<&(-EM-E&(@(A)S S@,MELL(<S,(@S

S;H";E&Y2 1 : 2 : 2 : : 1B 2 1 > 1E 12 ? 1E

-ore than 1> rows a!ailable. (ncrease rows selector to !iew more rows. 1> rows returned in E21> seconds CS' E.port

(n this e.ample2 weI!e created a subquery in the SELECT clause as follows4

(select co*,t(col*+,_,-+e) -s tot-l_col*+,s ><o+ -ll_t-b_col*+,s cols =@e<e colsAo=,e< # tblsAo=,e< -,2 colsAt-ble_,-+e # tblsAt-ble_,-+e) s*b?*e<C0

:1

The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields. The tricJ to placin a subquery in the select clause is that the subquery must return a sin le !alue. This is why an a re ate function such as S;-2 C,;)T2 -()2 or -AO is commonly used in the subquery.

:2

Steppin throu h Sub5"ueries in ,racle


8<a e 1 of > 9 This is the first article in a series concentratin on worJin with sub5queries in ,racle. Sub5 queries really ha!e tremendous depth. (n this series ( will show you se!eral scenarios where they can be efficiently used to retrie!e information from ,racle databases. As this is the first in series2 ( will be concentratin on the followin topics4

%ow to worJ with a PdualQ table. %ow to analyRe and identify the steps needed to deal with a sub5query. %ow to frame queries for each of the identified steps. %ow to combine all the framed queries and desi n a sin le command to retrie!e the final output.

A 4<i+e< o, t@e D2*-lE t-ble i, O<-cle This section mainly e.plains the PdualQ table in ,racle. ( shall use this table in a creati!e manner where!er required in this article as well as upcomin articles. (f you are already familiar with the SdualQ table2 feel free to sJip to the ne.t section. $hat is a PdualQ tableK (t is a simple table which is createdTinstalled automatically durin the installation of the ,racle database. To understand it2 let us consider the followin SELECT statement4 SELECT 123 FROM dual; The abo!e statement simply returns 12:. Let us worJ with another statement4 SQL> SELECT 10,20,Veri Taban Ynetim Sistemleri,3400 FROM dual; Results Explain Describe Saved SQL History

10 10

20 20

'VERITABANI YNETIMSISTEMLERI' Veri Taban Ynetim Sistemleri

3400 3400

1 rows returned in 0,00 seconds

CSV Export

This returns any constant !alues you pro!ide as columns. So PdualQ is Cust a con!enience table. (t is simply a one column and one row table that e.ists as part of SYS user. You can use the @ESC command to display the structure of a PdualQ table as follows4

::

DESC dual;
The abo!e statement returns the followin output4

&esultsE.plain

@escribe

Sa!ed S"L

%istory

Table @;AL

Column @;--Y

@ata Type 'archar2

Len th 1

<recision 5

Scale 5

<rimary Aey 5

)ullable

@efault 5

Comment 5

You can obser!e that there e.ists only one column named PdummyQ in the SdualS table. Similarly2 you can e!en display all the rows in the SdualS table as follows4

SELECT * FROM dual;


DUMMY ----X 1 rows selected +rom the abo!e2 you can obser!e that there e.ists only one row with a dummy !alue of S..S You donIt really need to use the PdualQ table at all. (t is only used when you want to addTinclude any constant !alues in your queries. You can e!en do calculations as follows4 SQL> SELECT 12 * 13 + 14 FROM dual; 12*13+14 ---------------------170 1 rows selected

:B

Ste44i,F t@<o*F@ S*bGH*e<ies i, O<-cle G T@e si+4lest s*bG?*e<C i, O<-cle 8<a e 2 of > 9 Hefore e.plainin sub5queries2 let us consider the followin scenario4 SQL> SELECT empno,ename,sal,deptno FROM emp WHERE sal = 5000; EMPNO ENAME SAL DEPTNO

--------- ---------- ----------- -----------7839 KING 5000 10

1 rows selected Let us modify the abo!e statement as follows4 SQL> SELECT empno,ename,sal,deptno FROM emp WHERE sal = (SELECT 5000 FROM dual); ( already e.plained the PdualQ table in the pre!ious section. (n the abo!e statement2 ( ha!e two SELECT statements as part of a sin le command. The followin is the order in which the abo!e statement ets e.ecuted4

The innermost query ets e.ecuted first. (n this case2 the query Pselect >EEE from dualQ ets e.ecuted first. ,nce the innermost query ets e.ecuted2 it returns a !alue to the immediate outer query. (n this case2 it is >EEE. The entire innermost query ets replaced with the new !alue returned by it. (n this case2 the outer query !irtually becomes Pselect empno2 ename2 sal2 deptno from emp where sal 1 >EEE.Q And finally2 the outer query ets e.ecuted2 which retrie!es A()*Us details.

(n the abo!e case2 ( used a SELECT query as part of another SELECT query/ thus it is called a Psub5query.Q You can e!en modify the abo!e statement to include an e.pression as follows4 SQL> SELECT empno,ename,sal,deptno FROM emp WHERE sal = (SELECT 2000+3000 FROM dual); The abo!e statement first e!aluates P2EEEV:EEEQ 8which results in >EEE9 as part of e.ecutin the inner query. Hased on the returned !alue 8which is >EEE92 the outer query ets e.ecuted. The ne.t section will show you a few simple and practically used sub5queries.

:>

Ste44i,F t@<o*F@ S*bGH*e<ies i, O<-cle G A s*bG?*e<C =it@ -FF<eF-te >*,ctio,s (o< F<o*4 >*,ctio,s) i, O<-cle 8<a e : of > 9 ( already introduced sub5queries in the pre!ious section. (n this section2 ( shall start i!in you some practical e.amples. Let us consider that ( would liJe to retrie!e the details of the hi hest paid employee. Let us write the question in a meanin ful manner and identify the steps as follows4

+rom the abo!e fi ure2 you ha!e two steps to worJ with for the query. The followin is the order you must follow 8based on the abo!e fi ure94

+ind the hi hest salary from the table 819 Hased on the !alue you et2 retrie!e the employee details liJe empno2 ename2 etc. belon in to that salary. 829

The followin is the statement which retrie!es the hi hest salary4 SELECT MAX(sal) FROM emp To retrie!e an employeeIs details based on a i!en salary 8say >EEE92 the query would be as follows4 SELECT empno,ename,sal,deptno FROM emp WHERE sal = 5000 Fust replace the !alue >EEE with the query that i!es you the hi hest salary. The complete statement would be as follows4 SQL> SELECT empno,ename,sal,deptno FROM emp WHERE sal = (SELECT MAX(sal) FROM emp); )ow2 let us walJ throu h its e.ecution4

The innermost query ets e.ecuted first. (n this case2 the query Pselect ma.8sal9 from empQ ets e.ecuted first. (t retrie!es the hi hest !alue in the column PsalQ from the table Pemp.Q ,nce the innermost query ets e.ecuted2 it returns a !alue to the immediate outer query. (n this case2 it is >EEE. The entire innermost query ets replaced with the new !alue returned by it. (n this case2 the outer query !irtually becomes Pselect empno2 ename2 sal2 deptno from emp where sal 1 >EEE.Q :?

And finally2 the outer query ets e.ecuted2 which retrie!es A()*Us details.

Let us end this section with a final touch. $hy canUt ( write the abo!e query as followsK SQL> SELECT empno,ename,sal,deptno FROM emp WHERE sal = MAX(sal) Or even the following: SQL> SELECT empno,ename,sal,deptno FROM emp WHERE MAX(sal) = sal )one of the abo!e two queries et e.ecuted successfully. The reason is that a condition in a $%E&E clause cannot contain any a re ate function 8or roup function9 without a sub5 queryW

:=

Ste44i,F t@<o*F@ S*bGH*e<ies i, O<-cle G DesiF,i,F s*bG?*e<ies to 2e-l =it@ +o<e t@-, o,e t-ble (o< 2i>>e<e,t t-bles) 8<a e B of > 9 Let us consider that ( would liJe to retrie!e A()*Is department name. All department names are a!ailable in the table Pdept2Q which is quite different from PempQ table. Let us write the question in a meanin ful manner and identify the steps as follows4

+rom the abo!e fi ure2 you ha!e two steps to o throu h with the query. The followin is the order you must follow 8based on the abo!e fi ure94

+ind A()*Is department number 819. Hased on the !alue you et2 retrie!e the department details liJe dname2 loc. etc belon in to that department number 829

The followin is the statement which retrie!es A()*Is department number4 SELECT deptno FROM emp WHERE ename = KING To retrie!e department details based on a i!en department number 8say :E92 the query would be as follows4 SELECT dname FROM dept WHERE deptno = 30 Fust replace the !alue :E with the query that i!es you A()*Is department number. The complete statement would be as follows4 SQL> SELECT dname FROM dept WHERE deptno = (SELECT deptno FROM emp WHERE ename=KING); )ow2 let us walJ throu h its e.ecution4

The innermost query ets e.ecuted first. (n this case2 the query Pselect deptno from emp where ename1UJin UQ ets e.ecuted first. (t retrie!es A()*Is department number. ,nce the innermost query ets e.ecuted2 it returns a !alue to the immediate outer query. (n this case2 it is 1E. The entire innermost query ets replaced with the new !alue returned by it. (n this case2 the outer5query !irtually becomes Pselect dname from dept where deptno 1 1E.Q And finally2 the outer query ets e.ecuted2 which retrie!es A()*Us department details

:G

Ste44i,F t@<o*F@ S*bGH*e<ies i, O<-cle G A, eI-+4le o> - ,este2 s*bG?*e<C (o< +*ltiG level s*bG?*e<C) 8<a e > of > 9 Let us consider that ( would liJe to retrie!e the department name of the hi hest paid employee. Let us write the question in a meanin ful manner and identify the steps as follows4

+rom the abo!e fi ure2 you ha!e three steps to o throu h with the query. The followin is the order you must follow 8based on the abo!e fi ure94

+ind the hi hest salary 819. Hased on the !alue you et2 retrie!e the department number belon in to that salary 829. Hased on the !alue you et2 find the department name belon in to that department number 8:9.

The followin is the statement which finds the hi hest salary4 SELECT MAX(sal) FROM emp To retrie!e a department number based on a i!en salary 8say 2EEE92 the query would be as follows4 SELECT deptno FROM emp WHERE sal = 2000 To retrie!e a department name based on a i!en department number 8say 2E92 the query would be as follows4 SELECT dname FROM dept WHERE deptno = 20 Combinin all of the abo!e queries accordin to the order i!en abo!e2 the new query would be as follows4 SQL> SELECT dname FROM dept WHERE deptno = (SELECT deptno FROM emp WHERE sal = (SELECT MAX(sal) FROM EMP)); You can obser!e the followin fi ure to understand how the e.ecution taJes place. You can also obser!e the underlined columns on how they relate lo ically4 :D

)ow2 let us walJ throu h its e.ecution4


The innermost query ets e.ecuted first. (n this case2 the query Pselect ma.8sal9 from empQ ets e.ecuted first. (t retrie!es the hi hest salary. (n this case it would be >EEE. The entire innermost query ets replaced with the new !alue returned by it. (n this case2 the immediate outer query !irtually becomes Pselect deptno from emp where sal 1 >EEE.Q ,nce this query ets e.ecuted2 it returns a department number2 which is 1E in this case. And finally2 the outermost query !irtually becomes Pselect dname from dept where deptno 1 1E2Q which retrie!es A()*Us department details.

Any bu s2 doubts2 su estions2 feedbacJ etc. are hi hly appreciated at @tt4:JJj-Fc@-tAs4-cesAliveAco+

BE

S*bGH*e<ies =it@ +*lti4le col*+,s i, O<-cle


Let us try to worJ with the followin query4

SELECT * FROM emp WHERE (sal,mgr) = (3000,7566)


,&A5EED2E4 in!alid relational operator

The abo!e would ne!er worJ and results in i!in you the Pin!alid relational operatorQ error. This is because you can compare only one !alue at a time and not more than one. The followin is a small tricJ to o!ercome the problem4

SELECT * FROM emp WHERE (sal,mgr) = (SELECT 3000,7566 FROM dual)


E-<), ==GG =DE2 E)A-E SC,TT +,&@ F,H -*& A)ALYST =>?? A)ALYST =>?? %(&E@ATE SAL EDT12T1DG2 :EEE E:T12T1DG1 :EEE CS' E.port C,-5 5 @E<T), 2E 2E

2 rows returned in E2EE seconds

( Cust made both of those two !alues part of the sub5query and it worJs fineW Hoth of those !alues are not from any table2 so ( used Pdual.Q )ow you can obser!e the power of the PdualQ table. (f you want to learn more about Pdual2Q please refer to my first article in this series. Let us worJ with a more practical sub5query rather than with a PdualQ table as follows4 SELECT * FROM emp WHERE (sal,mgr) = (SELECT sal,mgr FROM emp WHERE sal = (SELECT MIN(sal) FROM EMP WHERE sal > (SELECT MIN(sal) FROM emp)))

B1

E-<), =DEE

E)A-E FA-ES

F,H CLE&A

-*& =?DG

%(&E@ATE SAL E:T12T1DG1 D>E CS' E.port

C,-5

@E<T), :E

1 rows returned in E2EE seconds

The abo!e returns all the employees who are earnin the same salary and worJin under the same mana er of the employee earnin the second least salaryW

B2

',se<ti,F S*bGH*e<ies i, SELECT St-te+e,ts i, O<-cle G S*bG H*e<ies <et*<,i,F si,Fle -,2 +*lti4le v-l*es i, O<-cle
Let us consider the followin statement4

SELECT * FROM emp WHERE sal = 800


$hen you e.ecute the abo!e statement2 the condition in the $%E&E clause worJs with only a sin le !alue. Let us rewrite the abo!e statement with a plain sub5query as follows4

SELECT * FROM emp WHERE sal = (SELECT MIN(sal) FROM emp)


+rom the abo!e statement you can understand that the sub5query returns one and only one !alue 8or sin le !alue9 and the query worJs fine. (f we would liJe to worJ with more than one !alue in a condition 8of equality92 you may need to worJ somethin liJe the followin 4

SELECT * FROM emp WHERE empno IN (7902,7788)


Let us frame the abo!e with a sub5query as follows4

SELECT * FROM emp WHERE empno IN (SELECT empno FROM emp WHERE sal = (SELECT MAX(sal) FROM EMP

B:

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


E-<), ==GG =DE2 E)A-E SC,TT +,&@ F,H -*& A)ALYST =>?? A)ALYST =>?? %(&E@ATE SAL EDT12T1DG2 :EEE E:T12T1DG1 :EEE CS' E.port C,-5 5 @E<T), 2E 2E

2 rows returned in E2E: seconds

The abo!e query i!es us all the employees earnin the second hi hest salaryW (n the abo!e case2 the second le!el sub5query returns more than one !alue 8or two employee numbers9. Therefore2 ( pro!ided the () operator as part of the condition. (f you replace the () with P1Q in the abo!e query2 it will return with an error statin Psin le row sub5query returns more than one row.Q $hen you recei!e such an error2 try to replace P1Q with P()Q where!er appropriate.

BB

(nsertin Sub5"ueries in SELECT Statements in ,racle 5 Sub5"ueries as part of the HET$EE) operator in ,racle
!ETWEEN is - *,i?*e o4e<-to< i, O<-cleA Let +e s@o= Co* - s+-ll eI-+4le o> t@is:

SELECT * FROM emp WHERE sal BETWEEN 1000 and 3000


(t is !ery easy to understand the abo!e query as it returns all the employees who earn salaries between 1EEE and :EEE 8both inclusi!e9. Let us rewrite the abo!e query as follows4

SELECT * FROM emp WHERE sal BETWEEN (SELECT 1000 FROM dual) AND 3000
( Cust replaced 1EEE with a simple sub5query usin Pdual.Q (f you are new to the PdualQ table2 please refer to my first article in this series. Let us worJ a bit more practically as follows4

SELECT * FROM emp WHERE sal BETWEEN (SELECT MIN(sal) FROM emp) and 2000
$e can e!en worJ a bit differently. Let us o throu h the followin query4

SELECT Grade FROM salgrade WHERE (SELECT MAX(sal) FROM emp) BETWEEN losal AND hisal
The abo!e i!es you the salary rade of the hi hest salaryW

B>

(nsertin Sub5"ueries in SELECT Statements in ,racle 5 @eri!ed tables 8or inline !iews9 with Sub5"ueries in ,racle
Can we write sub5queries in 8or as part of9 the +&,- clauseK The answer is YES and you can use it !ery efficiently in some scenarios. Let us consider the followin statement4

SELECT empno,ename,sal,sal*12 AS AnnSal FROM emp WHERE AnnSal > 30000


(f ( e.ecute the abo!e statement2 it will result in an error sayin that PAnnSalQ is an P(n!alid (dentifier.Q The reason is that PAnnSalQ is not a column e.istin in the table Pemp.Q (t is simply an alias 8or some reasonable name9. $e are not allowed to worJ with a column alias in any of the conditions present in $%E&E clause. Let us modify the abo!e statement to maJe it worJ. Try the followin now4

SELECT empno,ename,sal,AnnSal FROM ( SELECT empno,ename,sal,sal*12 AS AnnSal FROM emp ) WHERE AnnSal > 30000
The abo!e statement is totally different from the pre!ious one. $ithin the abo!e statement2 the outer query doesnUt rely on any specific physical table. The output 8or result set9 of the inner query is considered as a table for the outer queryW The inner query is !ery similar to that of a !iew which doesnUt ha!e any physical !iew name2 and it ets created and destroyed on the fly. So2 accordin to the inner query2 it retrie!es four columns 8empno2 ename2 sal2 AnnSal9. The outer query can worJ with all four columns as if they are directly from a physical table. As you are tryin to defineTderi!e your own table of information from an e.istin physical table2 you call it as a deri!ed table 8or inline !iew9. E!en the deri!ed tables can be nested to any number of le!els with further sub5deri!ed tables as part of +&,- clauses.

B?

',se<ti,F S*bGH*e<ies i, SELECT St-te+e,ts i, O<-cle G S*bG H*e<ies =it@ CASE st<*ct*<e i, O<-cle SELECT st-te+e,ts
)ow let us o throu h an interestin topic on CASE structure. Let us see how a CASE structure worJs. Consider the followin statement4

SELECT empno, ename, CASE job WHEN 'SALESMAN' THEN 'SALES' WHEN 'MANAGER' THEN 'MGMT' ELSE job END AS jobfunction, sal FROM emp
E-<), =:?D =BDD =>21 =>?? =?>B =?DG ==G2 ==GG =G:D =GBB =G=? =DEE =DE2 =D:B E)A-E S-(T% ALLE) $A&@ F,)ES -A&T() HLAAE CLA&A SC,TT A()* T;&)E& A@A-S FA-ES +,&@ -(LLE& F,H+;)CT(,) CLE&A SALES SALES -*-T SALES -*-T -*-T A)ALYST <&ES(@E)T SALES CLE&A CLE&A A)ALYST CLE&A SAL GEE 1?EE 12>E 2D=> 12>E 2G>E 2B>E :EEE >EEE 1>EE 11EE D>E :EEE 1:EE

1B rows returned in E2E1 seconds

CS' E.port

$hen the abo!e query is e.ecuted2 it returns four columns 8empno2 ename2 Cobfunction2 sal9. The only eye5catchin issue from the abo!e is the followin structure4

CASE job WHEN 'SALESMAN' THEN 'SALES' WHEN 'MANAGER' THEN 'MGMT' ELSE job END AS jobfunction
B=

The abo!e dictates somethin !ery similar to the followin 4


(f the !alue of PCobQ is PsalesmanQ return Psales.Q (f the abo!e condition fails and if the !alue of PCobQ is Pmana erQ return Pm mt.Q (f both of the abo!e conditions fail then return the same !alue of PCob.Q All the !alues must be returned in a new column with the headin PCobfunction.Q

You need to obser!e that ( specified the column 8Cob9 alon with CASE. The conditions of $%E) worJ with the !alues a!ailable within that column. $e can e!en worJ with different relational 8and S"L9 operators within the $%E) condition as shown in the followin e.ample4

SELECT empno, ename, CASE WHEN comm IS NULL OR comm=0 THEN '-NA-' ELSE TO_CHAR(comm) END AS comm, sal FROM emp
E-<), =:?D =BDD =>21 =>?? =?>B =?DG ==G2 ==GG =G:D =GBB =G=? =DEE =DE2 =D:B E)A-E S-(T% ALLE) $A&@ F,)ES -A&T() HLAAE CLA&A SC,TT A()* T;&)E& A@A-S FA-ES +,&@ -(LLE& C,-5)A5 :EE >EE 5)A5 1BEE 5)A5 5)A5 5)A5 5)A5 5)A5 5)A5 5)A5 5)A5 5)A5 CS' E.por SAL GEE 1?EE 12>E 2D=> 12>E 2G>E 2B>E :EEE >EEE 1>EE 11EE D>E :EEE 1:EE

1B rows returned in E2E1 seconds

(n the abo!e case2 the conditions are directly used within the $%E) statement and you need not specify any column with the CASE. +inally2 you can e!en worJ with sub5queries within the CASE structure as follows4

BG

SELECT empno, ename, CASE WHEN sal >= (SELECT avg(sal) FROM emp) THEN 'HIGH' ELSE 'LOW' END AS pay, sal FROM emp
The abo!e returns a new column named Ppay2Q which contains either P%(*%Q or PL,$Q based on their salary compared to the a!era e salary of all employees.

BD

',se<ti,F S*bGH*e<ies i, SELECT St-te+e,ts i, O<-cle G S*bG H*e<ies -s (o< 4-<t o>) col*+,s i, O<-cle SELECT st-te+e,ts
Hefore ettin into sub5queries as part of columns2 let us looJ at the followin small query4

SELECT MAX(sal) MIN(sal) COUNT(*) SUM(sal) FROM emp

AS AS AS AS

highest, least, employees, total

E!eryone can easily understand that the abo!e query returns only one row containin four !alues of a re ation. Let us rewrite the abo!e query usin sub5queries to et the same output.

SELECT (SELECT (SELECT (SELECT (SELECT FROM dual

MAX(sal) MIN(sal) COUNT(*) SUM(sal)

FROM FROM FROM FROM

emp) emp) emp) emp)

AS AS AS AS

highest, least, employees, total

You can obser!e that ( replaced all a re ate functions with sub5queriesW Another important issue to concentrate on in the abo!e query is the PdualQ table. As the sub5queries in the abo!e statement are worJin indi!idually by themsel!es2 ( need not worJ with any table and thus ( used the PdualQ table. (f you want to learn more about the PdualQ table2 please o throu h my first article in this same series. )ow2 let us looJ at an interestin query which deals with sub5queries at both the column le!el and the CASE le!el. The followin is the query4

>E

SELECT empno, ename, sal AS salary, ROUND((sal -(SELECT AVG(sal) FROM emp)),2) AS avgcompare, CASE WHEN sal >= (SELECT AVG(sal) FROM emp) THEN 'HIGH' ELSE 'LOW' END AS paying FROM emp
The followin is the sample output of the abo!e query4 E-<), E)A-E SALA&Y A'*C,-<A&E <AY()* 5555555 5555555555 55555555 555555555555 555555 =G:D A()* >EEE 2D2?.=D %(*% =?DG HLAAE 2G>E ==?.=D %(*% . . =?>B -A&T() 12>E 5G2:.21 L,$ =BDD ALLE) 1?EE 5B=:.21 L,$ Any bu s2 doubts2 su estions2 feedbacJ etc. are hi hly appreciated at @tt4:JJj-Fc@-tAs4-cesAliveAco+

>1

You might also like