dbms introduction to sql
TRANSCRIPT
-
8/10/2019 DBMS Introduction to SQL
1/45
DBMS ( CS 592)
Introduction to SQL
WEEK 1:
In This Course ou !i"" "e#rn:
B#sic SQL
$d%#nced SQL
&L'SQL Concets
$ roect on *r#c"e usin+ SQL #nd
&L'SQL(With ,B -ront end)
Structured Quer L#n+u#+e ( SQL ) is # co.uter "#n+u#+e /or co..unic#tion !ithd#t#0#se
SQL is # oen "#n+u#+e de%e"oed 0 IBM !hose ru"es h#%e 0een set 0 # st#nd#rds
co..ittee
SQL h#s .#n c##0i"ities 0ut the .ost co..on needs in 0usiness #re to:
3e#d e4istin+ d#t#
Cre#te ne! records ho"din+ d#t#
Ch#n+e e4istin+ d#t#
De"ete d#d#
SQL is not # ro+r#. or # de%e"o.ent en%iron.ent such #s $ccess or ,B SQL is #
ure "#n+u#+e
-rontend so/t!#re inter/#ces !ith the user B#c6end so/t!#re ho"ds d#t# SQL is the
st#nd#rd "#n+u#+e /or the t!o ieces o/ so/t!#re to co..unic#te !ith e#ch other
D#t#: A set of information with some aspect in common.
For example data for employees might include social security numbers:
7 1285;1 n#.e? E."oeeID te? inte+er si@e? 11 di+its ( e4#ct" )
-ie"d >2 n#.e? A#.e-irst te? strin+ si@e? ?8= ch#r#cters
-
8/10/2019 DBMS Introduction to SQL
2/45
-ie"d >1 n#.e? n#.eL#st te? strin+ si@e? ?8= ch#r#cters
This .et#d#t# descri0es th#t !e h#%e # set o/ d#t# #0out e."oees th#t is or+#ni@ed
into # t#0"e Within th#t t#0"e !e ho"d three 6inds o/ in/or.#tion #0out e#ch e."oee
their ID nu.0er #nd their /irst #nd "#st n#.e
D#t#0#se: $ d#t#0#se is the d#t# #nd the .et#d#t# in other !ords # d#t#0#se is # set
o/ re"#ted in/or.#tion #s !e"" #s # descrition o/ ho! th#t in/or.#tion is or+#ni@ed $
d#t#0#se /or e."oees !ou"d 0e the .et#d#t# !e ust "oo6ed #t "us the in/or.#tion
descri0ed #0o%e under d#t#
E."oee ID A#.e-irst A#.eL#st
1285;
-
8/10/2019 DBMS Introduction to SQL
3/45
A#.in+ 3u"es /or t#0"es #nd co"u.ns
Must 0e+in !ith # "etter
Must 0e 1G8= ch#r#cters "on+
Must cont#in on" $GH #G@ =G9 J #nd >
Must not du"ic#te the n#.e o/ #nother o0ect o!ned 0 the s#.e user
Must not 0e #n *r#c"e ser%er reser%ed !ord
1 C3E$TE
SQLCre#te t#0"e e.( Eno nu.0er(5) En#.e %#rch#r2(2=)
E#dd %#rch#r2(8=)
Eoind d#te)
Constr#ints
1. Not Null, 2. Check
1. Primary key, 2. Unique key
Foreign key
1 SQLCre#te t#0"e e."
Eno nu.0er(5) constr#int enonotnu"" Aot Au""
En#.e %#rch#r2(2=)
E#dd %#rch#r2(8=)
Eoind d#te)
2 SQLCre#te t#0"e e.(
Eno nu.0er(5) constr#int enochec6 Chec6 ( eno 1== )
)
8 SQLCre#te t#0"e e." Eno nu.0er(5) constr#int unieno niFue
)
or
SQLCre#te t#0"e e."
Eno nu.0er(5) En#.e %#rch#r2(2=)
E#dd %#rch#r2(8=) Eoind d#te constr#int unieno niFue(eno))
SQLCre#te t#0"e e."
Eno nu.0er(5) constr#int eno &ri.#r 6e
)
or
SQLCre#te t#0"e e."
Eno nu.0er(5)
En#.e %#rch#r2(2=)
sercre#ted
Co"u.n n#.e
-
8/10/2019 DBMS Introduction to SQL
4/45
E#dd %#rch#r2(8=)
Eoind d#te constr#int eno &ri.#r 6e( eno))
5 SQLCre#te t#0"e e.1(
#no number"$% constr#int /6eno re/erences e.(eno),
#&type char"'%,
#&salary number"(,'%%)
*r
SQLCre#te t#0"e e.1(
#no number"$%,
#&type char"'%,
#&salary number"(,'%,constr#int /6eno /orei+n 6e(eno) re/erences e.(eno))
2 $LTE3
Adding columns in an exiting table.
1 S*+$"ter t#0"e e. #dd ( Eincode ch#r() E te"ehone ch#r(;) )
Modifying columns in an exiting table.
2 S*+$"ter t#0"e e. .odi/ ( Eno nu.0er() E#dd %#rch#r2(2=) )
-o add onstraints after creating a table.
8 SQL $"ter t#0"e e. #dd constr#int enochec6 Chec6 ( eno 1== ))
SQL $"ter t#0"e e. #dd constr#int eno &ri.#r 6e (eno)
5 SQL $"ter t#0"e e. #dd constr#int unieno niFue (eno)
SQL $"ter t#0"e e.1 #dd constr#int /6eno /orei+n 6e(eno)
re/erences e.(eno)%)
/nly for 0ot 0ull constraint it will be
; SQL $"ter t#0"e e. .odi/ eno constr#int enonotnu"" Aot Au""
For delete the constraints
-
8/10/2019 DBMS Introduction to SQL
5/45
$SSIAMEAT1
1ou should create the following table with your class roll number li2e emp&'3 where class roll number 4 '3.
5. reate table #M6 with the following structure.
'. 7isplay the structure of #M6 table.
3. Modify the #M6 table add a new column named !7#6-0/8 with data type integer
9. reate table 7#6- with the following structure.
$. Modify the #M6 table add referential integrity on !7#6-0/8 with the parent 2ey 7#6-"7eptno%.
. Modify the 7#6- table delete column !ity8.
;. Modify the #M6 table delete the constraint from s#".
(. create a duplicate table of 7ept with the name !7#6-&7
-
8/10/2019 DBMS Introduction to SQL
6/45
WEEK 2:
DML( D$T$ M$AI&L$TI*A L$A$E )
1 IASE3T
The Insert co..#nd is used to #dd one or .ore ro!s to # t#0"eWhi"e usin+ this co..#nd the %#"ues
#re se#r#ted 0 co..#s #nd the d#t#tes ch#r%#rch#r2 #nd d#te #re enc"osed in #ostrohes The
%#"ues .ust 0e entered in the s#.e order #s the #re de/ined in the t#0"e
1 SQL Insert into e. %#"ues ( 1 $3A C$LCTT$ 12$A9
-
8/10/2019 DBMS Introduction to SQL
7/45
Co.#tison oer#tors #re used in conditions to co.#re one e4ression !ith #nother The co.#rison
oer#tors #re ? ? ? ? 0et!een ( to chec6 0et!een #n t!o %#"ues)
In ( to .#tch !ith #n o/ the %#"ues in the "ist ) "i6e ( to .#tch # ch#r#cter #ttern )
; SQL Se"ect O /ro. orderin/o !here tot#" ;===
-
8/10/2019 DBMS Introduction to SQL
8/45
$SSIAMEAT2
5. Insert all the following data into #M6 table.
'. 7isplays all columns and all rows of the #M6 table.
3. 7isplay specific columns of the #M6 table li2e employee name, salary B department number.
9. alculate a salary increase of 3>> for all employees and displays a new SalC3>> column in the output.
$. insert a new record and gie the data into empno, ename, sal and deptno columns only
. 7isplays the employee name B annual compensation of employees. It calculates the annual
compensation as 5' multiplied by the monthly salary, plus a one time bonus of 5>>.
;. 7isplays employee details as DI0E is a 6#SI7#0- with column heading #mployee 7etails. " usingconcatenation operator, GG B column alias %
(. 7isplays distinct department number from #M6 table.
=. 7isplays employee name, Hob title B department number of all employees whose Hob title is +#D.
5>. 7isplays name, salary B commission from the #M6 table except MA0AE#.55. 7isplays name B salary whose salary is between 5>>> and '>>>.
5'. 7isplays employee number, name, salary B managers employee number of all the employees whose
managers employee number are ;=>', ;$ or ;;((.
53. 7isplays all employee names starting with S.
59. 7isplays all employee names ending with .
5$. Increase the salary of all employees with $J of sal.5. Increase the salary of all managers with 5$J of sal.
5;. update all the comm. Kith '>> whose comm. Are 0>> 5>;=( +AD# MA0AE# ;(3= >5LMA1L(5 '($> 3>
;;(' +AD MA0AE# ;(3= >=LN
;$9 MA-I0 SA+#SMA0 ;=( '(LS#6L(5 5'$> 59>> 3>
$9== A++#0 SA+#SMA0 ;=( '>LF#L(5 5>> 3>> 3>
;(99 -(LS#6L(5 5$>> > 3>
;=>> NAM#S +#D ;=( >3L7#L(5 =$> 3>
;$'5 KA7 SA+#SMA0 ;=( ''LF#L(5 5'$> $>> 3>
;=>' F/7 A0A+1S- ;$ >3L7#L(5 3>>> '>
;3= SMI-O +#D ;=>' 5;L7#L(5 (>> '>
;;(( S/-- A0A+1S- ;$ >=L7#L(' 3>>> '>
;(; A7AMS +#D ;;(( 5'LNA0L(3 55>> '>
;=39 MI++# +#D ;;(' '3LNA0L(' 53>> 5>
-
8/10/2019 DBMS Introduction to SQL
9/45
WEEK 8 :SQLO&"us -unctions
Sin+"e3o! -unctions-hese functions operate on single rows only and return one result per row. -here are different types of single
row functions.
5. Ch#r#cter /unctions: accept character input and return both character and number
alues.
'. Au.0er /unctions: Accept numeric input and return numeric alues.
3. D#te /unctions: /perate on alues of the date datatype. All date functions return a
alue of date datatype except the M*ATSBETWEEAfunction, which return anumber.
9. Con%ersion /unctions: onert a alue from one datatype to another.
$. ener#" /unctions:
L 0?+ functionL 7#/7# function
-unctions
Sin+"ero!
/unctions
Mu"ti"ero!
/unctions
Sin+"ero!
/unctions
Ch#r#cter
ener#" Au.0er
D#teCon%ersion
-
8/10/2019 DBMS Introduction to SQL
10/45
C#se con%ersion /unctions
-unction 3esu"t
L*WE3( SQL Course )
&&E3 ( SQL Course )
IAITC$& ( SQL Course )
sF" course
SQL C*3SE
SF" Course
Ch#r#cter .#niu"#tion /unctions
-unction 3esu"t
C*AC$T( oodU Strin+ )
SBST3 ( Strin+ 1 8 )
LEAT ( Strin+ )
IAST3 ( Strin+ rU )
L&$D ( s#" 1= OU)
oodStrin+
Str
8
OOOOOO5=== ( e4#."e on" )
3*AD: ounds alue to specified decimal
3*AD" 9$.=',' % 9$.=3
T3AC: -runcates alue to specified decimal
T3AC" 9$.=',' % 9$.='
M*D: eturns remainder of diision
M*D" 5>>, 3>> % 5>>
Ch#r#cter /unctions
C#se con%ersion
/unctions
Ch#r#cter .#niu"#tion
/unctions
L*WE3&&E3
IAITC$&
C*AC$T
SBST3
LEAT
IAST3
L&$D
Au.0er -unctions
-
8/10/2019 DBMS Introduction to SQL
11/45
Wor6in+ !ith D#tes
/racle stores dates in an internal numeric format: entury,
year, month, day, hours, minutes, seconds.
-he default date format is 77LM/0L11.
S1S7A-# is a function returning date and time.
7
-
8/10/2019 DBMS Introduction to SQL
12/45
3ound
This /unction returns the d#te !hich is rounded to the unit seci/ied 0 the /or.#t .ode"
The /or.#t is round(d/.tX) !here d is the d#te #nd /.t is the /or.#t .ode"
SQL Se"ect round(tod#te(28oct9dd.on)e#r) /ro. du#"
>5LHanL=; will be the result.
SQL Se"ect round(tod#te(28oct9dd.on).onth) /ro. du#"
>5LnoL= will be the result.
Trunc#te
This /unction returns the d#te !ith the ti.e ortion o/ the d# trunc#ted to the unit seci/ied 0 the
-or.#t .ode"The /or.#t is trunc(d/.tX) !here d is the d#te #nd /.t is the /or.#t .ode"
SQL Se"ect trunc(tod#te(28oct9dd.on)e#r) /ro. du#"
>5LHanL= will be the result.
SQL Se"ect trunc(tod#te(28oct9dd.on).onth) /ro. du#"
>5LoctL= will be the result.
C!ARACT#R FUNCT$N%
-ACTI*A IA&T *T&T
Initc#(ch#r) Se"ect initc#(he""o) /ro. du#" e""o
Lo!er(ch#r) Se"ect "o!er(-A) /ro. du#" /un
er(ch#r) Se"ect uer(su.) /ro. du#" SM
Ltri.(ch#rset) Se"ect "tri.(4@#d#.s4@)
/ro. du#"
$d#.s
3tri.(ch#rset) Se"ect rtri.(4@#d#.s#.s)
/ro. du#"
Y@#d
Tr#ns"#te(ch#r/ro.to)
Se"ect tr#ns"#te(#c60) /ro.du#"
B#c6
3e"#ce(ch#rse#rchs
trin+re strin+X)
Se"ect re"#ce(#c6 #nd ue0")
/ro. du#"
B"#c6 #nd
0"ue
Su0str(ch#r.n) Se"ect su0str(#0cde/+82) /ro. du#" Cd
Soundex, which is also a character function compares words that are spelled differently,but sound ali2e.onsider the following example.
SQL Se"ect n#.e /ro. custo.er !here sounde4(n#.e) ? sounde4(s.the)
-
8/10/2019 DBMS Introduction to SQL
13/45
/ther two functions are "#dB r#d.
SQL Se"ect "#d(#0c15?) /ro. du#"
-his function returns the sign 4 before the character string abc. -he output gies the
sign 4 before the word function. -he entire string is 5$ in length after the padding is
done.
SQL Se"ect r#d(#0c15?) /ro. du#"
-he rpad function pads the alue gien to the right of the string.
NU"#RC FUNCT$N%
-ACTI*A IA&T *T&T
$0s Se"ect #0s(15) /ro. du#" 15
Cei"(n) Se"ect cei"(;;
-
8/10/2019 DBMS Introduction to SQL
14/45
SQL Se"ect tod#te(#nu#r 15 1999 .onthdd ) /ro. du#"
5$LHanL== will be the result.
'R$UP FUNCT$N
3*& -unctions
-
8/10/2019 DBMS Introduction to SQL
15/45
sin+ the 3*& BZ C"#use on Mu"ti"e Co"u.ns
SQL se"ect detno o0 SM(s#") /ro. e. 3*& BZ detno o0
1ou can return summary results for groups and subgroups by listing more than one E/
-
8/10/2019 DBMS Introduction to SQL
16/45
-
8/10/2019 DBMS Introduction to SQL
17/45
1ou cannot use the KO## clause to restrict groups.1ou use the OA?I0E clause to restrict groups.
S*+ S#+#- deptno, A?E"sal%
F/M emp
KO## A?E"sal% '>>>
E/
-
8/10/2019 DBMS Introduction to SQL
18/45
Dis"#s the n#.e #nd hire d#tes /or #"" the e."oees The hire d#te "oo6s "i6e 1; Ao%e.0er
19
-
8/10/2019 DBMS Introduction to SQL
19/45
WEEK :
*0t#inin+ D#t# /ro. Mu"ti"e T#0"es (oin)
EM& DE&T
7ata from Multiple -ables
Sometimes you need to use data from more than one table. In the example aboe, the report displays data from
two separate tables.
5. EM&A*exits in the EM&table.
'. DE&TA*exits in both the EM&and DE&Ttables.
3. L*Cexits in DE&Ttable.
-o produce the report, you need to lin2 #M6 and 7#6- tables and access data from both of them.
Wh#t is # oin\
-
8/10/2019 DBMS Introduction to SQL
20/45
Tes o/ oin
#UuiHoin 0onLeUuiHoin /uter Hoin Self Hoin
-here are two main types of Hoin conditions:
EFuioins
AoneFuioins
Additional Hoin methods include the following:
*uter oins
Se"/ oins
Set oer#tors
EFuioin
A Hoin which is based on eUualities is called an eUuiHoin.
SQL Se"ect e.e.no e.en#.e e.detno detdetno det"oc
-ro. e. det
Where e.detno ? detdetno
In the aboe statement e.detno ? detdetnoperforms the Hoin operation.
It retriees rows from both the tables proided they both hae the same detnocolumn as specified in the
where clause. Since the where clause uses comparison operator eUual to "4%, to perform a Hoin, it is said an
eFuioin.
EFuioins #re #"so c#""ed si."e oins or inner oins
$ddition#" Se#rch Conditions sin+ the $AD *er#tor
For example, to display employee number, name, department number and department location, you need an
additional condition in the KO## clause.
SQL SELECT e.no en#.e e.detno "oc
-3*M e. det WE3E e.detno ? detdetno
$AD IAITC$& ( en#.e ) ? Kin+U
-
8/10/2019 DBMS Introduction to SQL
21/45
AonEFuioins$ non eFuioin seci/ies the re"#tionshi 0et!een co"u.ns 0e"on+in+ to di//erent t#0"es 0 .#6in+ use
o/ the re"#tion#" oer#tors ( ?? ) other th#n ?
EM& S$L3$DE
The re"#tionshi 0et!een the EM& t#0"e #nd the S$L3$DE t#0"e is # noneFuiion .e#nin+ th#t no
co"u.n in the EM& t#0"e corresonds direct" to # co"u.n in the S$L3$DE t#0"e The re"#tionshi
0et!een the t!o t#0"es is th#t the S$L co"u.n in the EM& t#0"e is 0et!een the L*S$L #nd IS$Lco"u.n o/ the S$L3$DE t#0"e The re"#tionshi is o0t#ined usin+ #n oer#tor other th#n eFu#" ( ? )
*uter oins
Zou use #n outer oin to #"so see ro!s th#t do not usu#"" .eet the oin condition
*uter oin oer#tor is the "us si+n ( P )
Missin+ ro!(s) c#n 0e returned i/ #n outer oin oer#tor is used in the oin condition It is "#ced on the
side o/ the oin th#t is de/icient in in/or.#tion This oer#tor h#s the e//ect o/ cre#tin+ one or .ore nu""
ro!s to !hich one or .ore ro!s /ro. the nonde/icient t#0"e c#n 0e oined
$ condition in%o"%in+ #n outer oin c#nnot use the IA oer#tor or 0e "in6ed to #nother condition 0 the
*3 oer#tor
Se"/ oinsSo.eti.es ou need to oin # t#0"e to itse"/ To /ind the n#.e o/ e#ch e."oeeUs .#n#+er ou need to
oin the EM& t#0"e to itse"/ -or e4#."e to /ind the n#.e o/ BL$KEUs .#n#+er ou need to :
-ind BL$KE in the EM& t#0"e 0 "oo6in+ #t the EA$ME co"u.n
-ind the .#n#+er nu.0er /or BL$KE 0 "oo6in+ #t the M3 co"u.n BL$KEUs .#n#+er nu.0er is
;
-
8/10/2019 DBMS Introduction to SQL
22/45
Set *er#tors
Set operators combine the results of two Uueries into a single one.
nion
nion #""
Intersect
Minus
The queries )hich are relate* +y a set operator shoul* hae the same num+er
o- columns an* the correspon*ing columns must +e o- the same *atatype.
nion
-he union operator returns all distinct rows selected by either Uuery. -he following
example combines the result of two Uueries with the union operator which eliminates
duplicate rows.
SQL Se"ect custid /ro. custo.er union se"ect ordid /ro. orderin/o
nion #""
-he union all operator returns all rows selected by either Uuery including duplicates.
SQL Se"ect custid /ro. custo.er union #"" se"ect ordid /ro. orderin/o
Intersect
Intersect operator returns only rows that are common to both the Uueries.
SQL Se"ect ordid /ro. orderin/o intersect se"ect ite.id /ro. ite.
Minus
Minus operator returns all distinct rows selected only by the first Uuery and
not by the second.
SQL Se"ect ordid /ro. ite. .inus se"ect ordid /ro. orderin/o
Khile using the order by clause, it must follow the last select statement and wemust order by interger and not by column name. onsider the following example.
SQL Se"ect ordidcustid /ro. orderin/o union se"ect ite.idrodid
/ro. ite.order 0 2
-he aboe example displays distinct rows selected by either Uuery, ordered by the
second column stated in both the Uueries. Since the column names are different inthe aboe Uueries, we use an integer in the order by clause instead of a column name.
-
8/10/2019 DBMS Introduction to SQL
23/45
$SSIAMEAT
$ Cre#te t#0"e detour ro"" nu.0er !ith /o""o!in+ structure
DE&TA* A*T ALL AMBE3 (2)
DA$ME ,$3C$32 (1)
L*C ,$3C$32 (18)
6ut the alues.
DE&TA* DA$ME L*C
1= $CC*ATIA AEW Z*3K
2= 3ESE$3C D$LL$S
8= S$LES CIC$*
= *&E3$TI*AS B*ST*A
B Cre#te t#0"e S#"+r#deour ro"" nu.0er !ith /o""o!in+ structure
3$DE AMBE3 (2)
L*S$L AMBE3()IS$L AMBE3()
6ut the alues.
3$DE L*S$L IS$L
1 ;== 12==
2 12=1 1==
8 1=1 2===
2==1 8===
5 8==1 9999
E%#"u#te #n e."oeeUs s#"#r +r#de
5 Dis"#s EA$ME DE&TA* DA$ME /or #"" the de#rt.ents The *&E3$TI*AS
de#rt.ent !hich does not h#%e #n e."oees is #"so dis"#ed sorted 0 DE&TA*
Dis"# the /o""o!in+
3E&*3T
BL$KE !or6s /or KIA
CL$3K !or6s /or KIA
*AES !or6s /or KIA
M$3TIA !or6s /or BL$KE
[[[[[
[[[[[
-
8/10/2019 DBMS Introduction to SQL
24/45
WEEK 5 :
Say this is a problem.
7 Who h#s # s#"#r +re#ter th#n onesUs \ 7
-o sole this problem, you need two Uueries : one Uuery to find what Nones earns and a second Uuery to find
who earns more than that amount.
1ou can sole this problem by combining the two Uueries, placing one Uuery inside the other Uuery.
Su0Fueries
$ su0Fuer is # SELECT st#te.ent th#t is e.0edded in # c"#use o/ #nother SELECT st#te.ent
In the snt#4:
*er#tor inc"udes # co.#rison oer#tor such #s ? or IA
Co.#rison oer#tors /#"" into t!o c"#sses: sin+"ero! oer#tors ( ? ? ?) #nd .u"ti"ero!
oer#tors ( IA $AZ $LL )
The su0Fuer is o/ten re/erred to #s # nested SELECT su0SELECT or inner SELECT st#te.ent The
su0Fuer +ener#"" e4ecutes /irst #nd its outut is used to co."ete the Fuer condition /or the .#in or
outer Fuer
M#in Quer
7Which e."oees h#%e # s#"#r +re#ter th#n onesUs s#"#r\]
Su0Fuer
7Wh#t is onesUs s#"#r\]
SELECT se"ect"ist
-3*M t#0"e
WE3E e4r oer#tor
( SELECT se"ect"ist
-3*M t#0"e
WE3E e4r )
-
8/10/2019 DBMS Introduction to SQL
25/45
E4#."e
SQL SELECT en#.e
-3*M e.
WE3E s#"
( SELECT [[[
-3*M [[[
WE3E [[[[ )
uide"ines /or sin+ Su0Fueries
1 Enc"ose su0Fueries in #rentheses
2 &"#ce su0Fueries in the ri+ht side o/ the co.#rison oer#tor
8 Do not #dd #n *3DE3 BZ c"#use to # su0Fuer
se sin+"ero! oer#tors !ith sin+"ero! suFueries
5 se .u"ti"ero! oer#tors !ith .u"ti"ero! suFueries
Tes o/ Su0Fueries
Sin+"ero! su0Fueries: Queries th#t return on" one ro! /ro. the inner SELECT st#te.ent
Mu"ti"ero! su0Fueries: Queries th#t return .ore th#n one ro! /ro. the inner SELECT
st#te.ent
Mu"ti"eco"u.n su0Fueries: Queries th#t return .ore th#n one co"u.n /ro. the inner
SELECT st#te.ent
3eturn on" one ro!
se sin+"ero! co.#rison oer#tors
/perator Meaning
4 #Uual to
Ereater than
4 Ereater than or eUual to
V +ess than
V4 +ess than or eUual to
V 0ot eUual to
If the inner Uueries return single alues, the S*+ statement is called a singleLrow subUuery. -he outer and the
inner Uueries can get data from different tables.
Zou c#n use rou /unctions in # Su0Fuer
S*+ S#+#- TTTTTT.
F/M TTT.
KO## TT.
" S#+#- MAP"TT.%
F/M TTT % )
-
8/10/2019 DBMS Introduction to SQL
26/45
$,IA C"#use !ith Su0Fueries
1 The *r#c"e Ser%er e4ecutes su0Fueries /irst
2 The *r#c"e Ser%er returns resu"ts into the .#in FuerUs $,IA c"#use
S*+ S#+#- TTTTTTTTTTT..
F/M TTTT
E/
-
8/10/2019 DBMS Introduction to SQL
27/45
In singleLrow subUueries and multipleLrow subUueries only one column was compared in th e KO## clause
or OA?I0E clause of the S#+#- statement. If you want to compare two or more columns, you must write a
compound KO## clause using logical operators.
Snt#4
D#t#0#se *0ects
Snon.
A synonym is a database obHect, which is used as an alias" alternatie name % for a table,
iew or seUuence.
SQL Cre#te snon. cust /or custo.er
SeFuences
A seUuence is a database obHect which can generate uniUue, seUuential integer alues. It can
be used to automatically generate primary 2ey or uniUue 2ey alues.
-he syntax for the creating a seUuence is as follows.
Cre#te seFuence seFn#.e incre.ent 0 n st#rt !ith n .#4%#"ue n X
.in%#"ue n X cc"e ' nocc"e X c#che ' noc#che X
Incre.ent 0 n : n is an integer which specifies the interal between seUuence
numbers.
St#rt !ith n : Specifies the first seUuence number to be generated.
Min%#"ue n : Specifies the minimum alue of the seUuence.
M#4%#"ue n : It specifies the maximum alue that the seUuence can generate.
Cc"e : Specifies that the seUuence continues to generate alues after reaching
either its max or min alue.
Aocc"e : Specifies that the seUuence cannotgenerate more alues after reaching
either its max or min alue.
C#che : Allows faster generation of seUuence number. /racle preallocates seUuence numbers and 2eeps them in memory for faster access.
-he cache alue must be less than maxalue minus minalue.
SELECT co"u.n co"u.n [
-3*M t#0"e
WE3E ( co"u.n co"u.n [) IA
( SELECT co"u.n co"u.n [
-3*M t#0"e
WE3E condition )
-
8/10/2019 DBMS Introduction to SQL
28/45
Aoc#che : 7oes not preallocate seUuence numbers for faster access.
SQL Cre#te seFuence custseF incre.ent 0 1 st#rt !ith 1 .#4%#"ue 1=
Min%#"ue 1 cc"e c#che
After creating a seUuence we can access its alues with the help of pseudocolumns li2e
curr%#"and ne4t%#". A pseudocolumn behaes li2e a table column, but it not actually stored
in the table.
Ae4t%#" :0extal will return inital alue of the seUuence, when referred to, forthe first time. +ater reference to nextal will increment the seUuence alue
by I0#M#0- 1 clause and return the new alue.
Curr%#" : urral returns the cuttent alue of the seUuence which is the alue returned
y the last reference to nextal.
SQL Cre#te t#0"e te. ( id nu.0er(8) n#.e %#rch#r2(2=))
SQL Insert into te. %#"ues ( custseFne4t%#" %i#)
-o find out the current seUuence number
SQL Se"ect custseFcurr%#" /ro. te.
$"ter seFuence
Ke can alter the seUuence when we want to do the following :
Set or eliminate min or max alue. hange the increment alue.
hange the number of the cached seUuence numbers.
-he following example will change the maxalue of the seUuence from 5> to 5$.
SQL #"ter seFuence custseF .#4%#"ue 15
-
8/10/2019 DBMS Introduction to SQL
29/45
$SSIAMEAT 5
5. Kho has a salary greater than NonessX
'. Kho has a salary greater than the salary of employee ;$.
3. 7isplay the employees whose Hob title is the same as that of employee ;3=.9. 7isplay the employees whose Hob title is the same as that of employee ;3= and whose salary is
greater than of employee ;(;.
$. 7isplays the employee name, Hob title and salary of all employees whose salary is eUual to the
minimum salary.
. 7isplays all the departments that hae a minimum salary greater than that of department '>.;. Find the Hob with the lowest aerage salary.
(. Find the employees who earn the same salary as the minimum salary for department.
=. 7isplays the employees whose salary is less than any cler2 and who are not cler2s." hint: -he maxsalary that a cler2 earns is 53>> so the S*+ statement displays all the employees who are not cler2s
but earn less than 53>>%
5>. 7isplays employees whose salary is greater than the aerage salaries of all the departments. " hint: the
highest aerage salary of a department is '=5., so the Uuery returns those employees whose salary
is greater than '=5.%
55. 7isplay the name, department number, salary and commission of any employee whose salary and
commission matches both the commission and salary of any employee in department 3>.
-
8/10/2019 DBMS Introduction to SQL
30/45
WEEK 6
PL/SQL Tutorial
PL/SQL BLOCK : The pl/sql block contains the following section:--
The DECLAREsection.
The Master BEGINand ENDsection that contains the
EXCEPTIONsection.
The declare section contains declaration of memory variables, constants,cursors etc. The begin section contains sql eecutable statements and
pl/sql eecutable statements. The eception section contains code tohandle errors that may arise during the eecution of the code block. The
end declares the end of pl/sql block.
! bit about it"s working. #hen you typed out the pl/sql block foreecution. $t is sent to the pl/sql engine, where procedural statements
are eecuted% and sql statements are sent to the sql eecutor in the
oracle engine. &ince pl/sql engine resides in the oracle engine, the codeseecutes smoothly and efficiently.
PL/SQL DATA-TYPE :
This is easy since it includes almost all the data types which u have usedin sql such as date, varchar, number, char etc etc.. &ome of the
attributes such as 'T()* is also used. This attribute automatically takesin the default data type of the sql table from which u have passed the
query. #e will discuss this later.
+emember in pl/sql a variable name must begin with a character and can
be followed by maimum of other characters. +eserved words can"tbe used unless enclosed within double quotes. ariables must be
separated from each other by at least one space or by a punctuationmark. (ou can assign values of operator using : operator. $ won"t
discuss about logical comparisons operators such as 0, 1 , 1, 23T,T+4*, !25, 3+, 2466 etc since they r quite easy to understand.
OW TO DISPLAY !ESSAGES ON SCREEN :
DB!S"O#TP#T :is a $a%&a'(that includes a number of procedure and functions
that accumulate information in a buffer so that it can be retrieved later. These functionscan also be used to display messages to the user.
P#T"LINE :)ut a piece of information in the package buffer followed by an end-of-linemarker. $t can also be used to display message to the user. )ut7line epects a single
parameter of character data type. $f used to display a message, it is the message
-
8/10/2019 DBMS Introduction to SQL
31/45
"string".
*8: dbms7output.put7line9%
RE!E!BER: To display messages to the user the &*+*+34T)4T should be set to 32.&*+*+34T)4T is a sql ;plus environment parameter that displays the information on
screen passed as a parameter to the )4T76$2* function.
EG: SET SER)ERO#TP#T ON
PL/SQL %o**(+t, :
! comment can have forms i.e.-- The comment line begins with a double hyphen 9--. The entire line will be treated as
a comment.-- The < style comment such as /; i am a comment ;/
EXA!PLE :
--ADDITION O TWO N#!BER5eclare
a number%
b number%c number%
=egin
a:>a%b:>b%
c:a?b%dbms7output.put7line9"&um of " @@ a @@ " and " @@ b @@ " is " @@ c%
*nd%
Aere B>C symbol is used to take user input at runtime.....
CONDITIONAL CONTROL :
S.+ta :$D --b%
dbms7output.put7line9"*nter c:"%
c:>b%
-
8/10/2019 DBMS Introduction to SQL
32/45
if 9a1b and 9a1c thendbms7output.putline9"! is Maimum"%
elsif 9b1a and 9b1c thendbms7output.putline9"= is Maimum"%
elsedbms7output.putline9"< is Maimum"%
end if%*nd%
Ea*$l( 4: 1CALC#LATION O NET SALARY3
declare
ename varchar9EF%basic number%
da number%hra number%
pf number%netsalary number%
beginename:>ename%
basic:>basic%
da:basic ; 9GE/EHH%hra:basic ; 9EF/EHH%
if 9basic 0 IHHH
thenpf:basic ; 9F/EHH%
elsif 9basic 1 IHHH and basic 0 FHHHthen
pf:basic ; 9J/EHH%elsif 9basic 1 FHHH and basic 0 KHHH
thenpf:basic ; 9K/EHH%
else
pf:basic ; 9EH/EHH%end if%netsalary:basic ? da ? hra -pf%
dbms7output.put7line9"*mployee name : " @@ ename%dbms7output.put7line9")rovidend Dund : " @@ pf%
dbms7output.put7line9"2et salary : " @@ netsalary%end%
ITERATI)E CONTROL AND SEQ#ENTIAL CONTROL
5. SI!PLE LOOP
S.+ta :loop
-- &equence of statements%-- the loop ends when u use *L$T #A*2 statement --condition
end loop%(a*$l( :
5eclare n number:E%6oop
5bms7output.put7line 9n%n:n?E%
*L$T #A*2 n1F%
*nd loop%
-
8/10/2019 DBMS Introduction to SQL
33/45
45 WILE LOOP
S.+ta :#hile --condition
loop--sequence of statements
end loop%
Ea*$l( :
--S#! O ODD N#!BER WITIN 7
declare
n number%sumE number default H%
beginn:E%
while 9n 0 FHloop
sumE:sumE?n%n:n?%
end loop%dbms7output.put7line9"&um of odd numbers :" @@ sumE%end%
$SSIAMEAT
5. Krite a program using 6+YS*+ to input an integer and chec2 whether a year is +eap year or not.
'. Krite a program to chec2 the salary of W+AD# from #M6 table. If it is V5>>> then increment comm
with >> else show message ! 0/ I0#M#0- 8 .
3. Krite a program to display 5st'> odd numbers " suing simple loop%
9. Krite a program using to input an integer and display it in reerse order"using Khile loop%
$. Krite a program using to input an integer and chec2 whether it is prime or not.
WEEK 825 OR LOOPS.+ta :
Dor i in E..EH
loop--sequence of statementsend loop%
Ea*$l( 0 :
5eclarebegin
for i in E..EHloop
dbms7output.put7line9i%end loop%
end%
-
8/10/2019 DBMS Introduction to SQL
34/45
Ea*$l( 4 : 1S#! O ODD N#!BERS WITIN 73
declaren number%
sumE number default H%
begin
n:E%for n in E.. FH
loop
if mod9n,E thensumE:sumE?n%
end ifend loop%
dbms7output.put7line9"sum " @@ sumE%end%
95 GOTO : 1SEQ#ENTIAL CONTROL3
S.+ta :
83T3 L%00 L 11
declare
--takes the default datatype of the column of the table pricemsal emp.sal'type%
beginselect sal into msal from emp where empnoJHH%
if msal 1 JHHH thengoto 4pd%
elseupdate emp set salsal?FHH where empnoJHH%
end if%
00 4pd 11dbms7output.put7line 9 $2
-
8/10/2019 DBMS Introduction to SQL
35/45
$r((;i+( (%($tio+,: are already defined within datadictionary. Dollowing are some eamples of )redefined eceptions
EXCEPTION
2o-data-found when no rows are returned
-
8/10/2019 DBMS Introduction to SQL
36/45
=*8$2
&*6*
*25%
WEEK =
C3S*3:
-
8/10/2019 DBMS Introduction to SQL
37/45
EXA!PLES
--EXA!PLE O SQLO#ND 1I!PLICIT C#RSORS3
begin
update emp set salsal ;H.EF where empno >emp7code%if sql'found then
dbms7output.put7line9"employee record modified successfully"%
elsedbms7output.put7line9"employee does not eist"%
end if%end%
--EXA!PLE OR SQLNOTO#ND 1I!PLICIT C#RSORS3
beginupdate emp set sal sal;H.EF where empno >emp7code%
if sql'notfound then
dbms7output.put7line9"employee does not eist"%else
dbms7output.put7line9"employee record modified successfully"%end if%
end%
--EXA!PLE OR SQLROWCO#NT 1I!PLICIT C#RSORS3
declare
rows7affected char9G%begin
update employee set salary salary;H.EF where Oob"programmers"%rows7affected : to7char9sql'rowcount%if sql'rowcount 1 H then
dbms7output.put7line9rows7affected @@ "employee records modifiedsuccessfully"%
else
dbms7output.put7line9"There are no employees working asprogrammers"%
end if%end%
S.+ta of eplicit cursor:
-
8/10/2019 DBMS Introduction to SQL
38/45
3)*2 cE%
633)D*T
-
8/10/2019 DBMS Introduction to SQL
39/45
TRIGGER:
Trigger is a stored procedure which is called implicitly by oracle
engine whenever a insert, update or delete statement is fired.
Aa+ta'(, o; ata>a,( tri''(r,:
---1 5ata is generated on it"s own
---1 +eplicate table can be maintained
---1 To enforce comple integrity constraints
---1 To edit data modifications
---1 To auto increment a field
etc..
S.+ta:
-
8/10/2019 DBMS Introduction to SQL
40/45
-
8/10/2019 DBMS Introduction to SQL
41/45
WEEK
PROCED#RES AND #NCTIONS
procedure is a subprogram...which consists of a set of sql statement.
)rocedures are not very different from functions. ! procedure or functionis a logically grouped set of &6 and )6/&6 statements that perform a
specific task. ! stored procedure or function is a named pl/sql code blockthat have been compiled and stored in one of the oracle engineCs systemtables.
To make a procedure or function dynamic either of them can be passed
parameters before eecution. ! procedure or function can then change
the way it works depending upon the parameters passed prior to itseecution.
Pro%(ur(, a+ ;u+%tio+ ar( *a( u$ o;
5eclaration part
*ecutable part
*ception-handling part93ptional
! declaration part consists of declarations of variables. !eecutable part consists of the logic i.e. sql statements....and
eception handling part handles any error during run-time
T@( ora%l( (+'i+( $(r;or*, t@( ;olloi+' ,t($, to ((%ut( a
$ro%(ur( or ;u+%tio+5555
erifies user access
erifies procedure or function validity
eecutes the procedure or function
So*( o; t@( aa+ta'(, o; u,i+' $ro%(ur(, a+ ;u+%tio+, ar(:
&ecurity
)erformance
memory allocation
productivity integrity.
!o,t i*$orta+t: 1the i;;(r(+%(between $ro%(ur(,and;u+%tio+,
! function must return a value back to the caller. ! function canreturn only one value to the calling pl/sql block. =y defining multiple
out parameters in a procedure, multiple values can be passed to the
caller. The out variable being global by nature, its value is accessibleby any pl/sql code block including the calling pl/sql block.
-
8/10/2019 DBMS Introduction to SQL
42/45
S.+ta ;or ,tor( $ro%(ur(:
-
8/10/2019 DBMS Introduction to SQL
43/45
EXA!PLE 0:
--)+3
-
8/10/2019 DBMS Introduction to SQL
44/45
WEEK 07
PACKAGE:
! package is an oracle obOect, which holds other obOects within it.
3bOects commonly held within a package are procedures, functions,
variables, constants, cursors and eceptions. )ackages in plsql arevery much similar to those packages which we use in S!!.
Part, o; $a%&a'( :
Pa%&a'( ,$(%i;i%atio+
Pa%&a'( >o.
! $a%&a'( ,$(%i;i%atio+part consists of all sort of declarationof functions and procedures
#hile package body consists of group of code and logic of declaredfunctions and procedures.
EXA!PLE
--package specification 9save into file packEcreate or replace package pack is
Dunction rmt9 in number return number%procedure rmtE9 in number%
end%
--body 9save into file p
create or replace package body pack is
Dunction rmt9 in number return number is
begin
return 9;%end%
procedure rmtE9 in number is
begindbms7output.put7line9;%end%
end%
-- To eecute the package at first run the pE file and then p file
and then from &6 prompt type eec pack.rmtE9I%
!s shown above u can put in complicated procedures and functionsinside the package. $ have Oust shown a simple eample. (ou can
easily modify the above code to fit your requirement. Sust try out
-
8/10/2019 DBMS Introduction to SQL
45/45
packages which include cursors, procedures and functions etc.
+emember pl/sql supports overloading. i.e. you can use the samefunction or procedure name in your application but with different
no or type of arguments.