You are on page 1of 52

ANSI SQL

SQL Functions
LEVEL LEARNER
1
Question
s
Coding
Standards
Referenc
e
Test Your
Understanding
Icons Used
Lend A
Hand
Hands on Exercise Points To
Ponder
Summar
y

Overview
SQL Functions session !ro"ides
#no$%edge and understanding of
t&e use of functions a"ai%a'%e in
A(S) and *na%%y a!!%y t&e syntax
%earned as !art of t&is session in a
case study !ro"ided+
,
To understand t&e SQL functions conce!ts t&at a
de"e%o!er needs to #no$ to $or# $it& it+

Ty!es of SQL Function

(umeric- c&aracter . /ate


Time functions

Aggregate Function

0at&ematica% Function

(esting of Functions
Objective
1
For com!%ete understanding of A(S) SQL $e are
going to ma#e use of Product Management
System 2PMS3 for A4C Traders+
A4C Traders is a com!any $&ic& 'uys co%%ecta'%e
mode% cars- trains- truc#s- 'uses- trains and s&i!s
direct%y from manufacturers and se%%s t&em to
distri'utors across t&e g%o'e+ )n order to manage t&e
stoc#ing- su!!%y and !ayment transactions t&e
a'o"e soft$are is de"e%o!ed+
As !er t&e re5uirement of t&e trading com!any a
in"entory system is de"e%o!ed to co%%ect t&e
information of !roducts and customers and t&eir
!ayment !rocessing+
Scenario
6
Database tables
T&ere are many entities in"o%"ed in Product
Management System. PMS as gi"en 'e%o$ $&ic& $e
$i%% 'e dea%ing $it& t&roug&out t&is course
P
a
y
m
e
n
t
s
T
o

m
a
i
n
t
a
i
n

i
n
f
o
r
m
a
t
i
o
n

o
f

!
a
y
m
e
n
t
s

d
o
n
e

e
+
g
+

!
a
y
m
e
n
t

d
a
t
e
-


a
m
o
u
n
t

e
t
c
+

C
u
s
t
o
m
e
r
T
o

m
a
i
n
t
a
i
n

c
u
s
t
o
m
e
r

d
e
t
a
i
%
s


e
+
g
+

C
u
s
t
o
m
e
r

(
a
m
e
-

a
d
d
r
e
s
s

O
r
d
e
r
s
T
o

m
a
i
n
t
a
i
n

8
r
d
e
r
s

d
o
n
e

'
y

c
u
s
t
o
m
e
r
s

e
+
g
+

o
r
d
e
r

n
o

-
d
a
t
e

e
t
c
+

O
f
c
e
s

T
o

m
a
i
n
t
a
i
n

i
n
f
o
r
m
a
t
i
o
n

o
f

8
9
c
e
s

e
+
g
+

8
9
c
e

c
o
d
e
-

a
d
d
r
e
s
s
-

c
i
t
y

e
t
c
+

E
m
p
l
o
y
e
e
s
T
o

m
a
i
n
t
a
i
n

e
m
!
%
o
y
e
e


d
e
t
a
i
%
s


e
+
g
+


i
d
-
(
a
m
e

e
t
c
+

P
r
o
d
u
c
t
s
T
o

m
a
i
n
t
a
i
n

i
n
f
o
r
m
a
t
i
o
n

o
f

!
r
o
d
u
c
t
s

e
+
g
+

!
r
o
d
u
c
t

i
d
-

n
a
m
e

e
t
c
+

O
r
d
e
r
D
e
t
a
i
l
s
T
o

m
a
i
n
t
a
i
n

8
r
d
e
r
s

d
o
n
e

'
y

c
u
s
t
o
m
e
r
s

e
+
g
+

o
r
d
e
r

n
o

-
d
a
t
e

e
t
c
+

:
Schema diagram
;

Lets %earn a'out aggregate functions $&ic& $i%% &e%! us meet T)0<s
re5uirements++
Scenario
Hi=
>ood t&at t&e re5uirements %i#e
adding t$o co%umns are
im!%emented using o!erators-
remaining re5uirements %i#e
*nding t&e maximum amount
!aid 'y t&e customers s&ou%d
'e im!%emented+
?
Do you Know
@&at is FunctionA
?
B
What are Functions?
What are SQL Functons !
SQL functions are 'ui%t in AP)<s $&ic& SQL !ro"ides for
de"e%o!ers $&ic& can 'e used in SQL statements to
!erform s!eci*c %ogicCfunctiona%ity+
E"am#$e!

Round t&e num'ers+

C&ange t&e string to u!!er case+


1D
Classiying S!" Functions
ANSI SQL Functons %$ass&caton
T&e *rst %e"e% of c%assi*cation &ierarc&y is
'etermnstc (unctons
Non)'etermnstc (unctons
T&ere are no ironc%ad ru%es for recogniEing a SQL routine as
eit&er deterministic or nonFdeterministic+
A /eterministic function
a%$ays returns t&e same resu%ts if gi"en t&e same in!ut "a%ues+
A (ondeterministic function
returns diGerent resu%ts e"ery time it is ca%%ed- e"en $&en t&e
same in!ut "a%ues are !ro"ided+
An exam!%e of a deterministic function is t&e function
LE(>TH+ @&en !assed an argument of a string data ty!e- it
returns t&e %engt& of t&e argument !assed+ Ca%%ing it $it&
t&e same argument o"er and o"er again $i%% yie%d exact%y
t&e same resu%t+
A function t&at
ta#es no arguments
is ca%%ed N$adc.
11
#ggregate Functions and Scalar Functions
ANSI SQL Functons %$ass&caton %ont..
T&e SQL &as t$o 'asic ty!es of functionsH
Aggregate Functions
Sca%ar Functions+
Aggregate (unctons o!erate on sets of ro$s and
returns one "a%ue !er grou!+
aggregate*(uncton*name +,ALL - 'IS.IN%./ e"#resson0
Functon 1sage
AI>2ex!ression3
Com!utes t&e a"erage "a%ue of a co%umn 'y t&e
ex!ression
C8U(T2ex!ressio
n3
Counts t&e ro$s de*ned 'y t&e ex!ression
C8U(T2J3 Counts a%% ro$s in t&e s!eci*ed ta'%e or "ie$
0)(2ex!ression3
Finds t&e minimum "a%ue in a co%umn 'y t&e
ex!ression
0AK2ex!ression3
Finds t&e maximum "a%ue in a co%umn 'y t&e
ex!ression
SU02ex!ression3
Com!utes t&e sum of co%umn "a%ues 'y t&e
ex!ression
1
#ggregate Function $%am&les
T&ey are common%y used $it& t&e >R8UP 4Y c%ause in a
SELECT statement- and acce!ts sing%e co%umn as in!ut +
T&e fo%%o$ing are some of t&e Aggregate Functions-
Functo
n
E"am#$e 'escr#ton
C8U(T SELE%.
%21N.+%ustomerNum
3er0 FR2M %ustomers
4
/is!%ays t&e tota% num'er of ro$s in t&e
Customers ta'%e+
SU0 SELE%. S1M+amount0
FR2M Payments4
/is!%ays t&e sum of a%% t&e !ayments in t&e
!ayments ta'%e+
0)( SELE%. MIN+amount0
FR2M PA5MEN.S4
/is!%ays t&e minimum amount !aid in t&e
Payments ta'%e+
0AK SELE%. MA6+amount0
FR2M PA5MEN.S 4
/is!%ays t&e maximum amount !aid in t&e
Payments ta'%e+
AI> SELE%. AV7+amount0
FR2M PA5MEN.S4
/is!%ays t&e a"erage of a%% t&e amounts
!aid in !ayments ta'%e+
1,
Classiying #ggregate Function
Su3 c$assng o( the aggregate (unctons
g8en 3e$o9!
%ategory 1sage
>rou! T&ese functions dea% $it& t&e grou!ing o!eration or t&e
grou! aggregate function+
@indo$ T&ese functions com!ute t&eir aggregate "a%ues t&e same
as a grou! function- exce!t t&at t&ey aggregate o"er t&e
$indo$ frame of a ro$ and not o"er a grou! of grou!ed
ta'%e+
Unary >rou! T&ese functions ta#e an ar'itrary L"a%ue ex!resssionM as
an argument+
4inary >rou! T&ese functions ta#e a !air of arguments- a de!endent one
and an inde!endent one- 'ot& of $&ic& are numeric
ex!ressions+ T&ey remo"e (ULL "a%ues from t&e grou! and
if t&ere are no remaining ro$s- t&ey e"a%uate to D+
)n"erse
/istri'ution
T&ere are on%y t$o in"erse functionsH PERCE(T)LENC8(T
and PERCE(T)LEN/)SC+ 4ot& functions ta#e an argument
'et$een D and 1+
Hy!ot&etica% Set T&ese functions are re%ated to t&e $indo$ functions RA(O-
/E(SENRA(O- PERCE(TNRA(O and CU0EN/)ST+
11

Lets %earn a'out string functions $&ic& $i%% &e%! us meet T)0<s
re5uirements++
Scenario
Hi=
@rite a 5uery to dis!%ay
t&e customer and
em!%oyee names in t&e
ca!ita% %etters+
16
Scalar Functions
Sca$ar Functons

Re5uire no arguments- or at most one argument- to 'e


!assed to t&emP t&ey return a sing%e "a%ue t&at is
'ased on t&e in!ut "a%ue+

Sca%ar functions can 'e 'ro#en do$n into t&e


su'categories s&o$n in t&e fo%%o$ing ta'%e- 'ased
u!on t&eir intended useH
%ategory 1sage
4ui%tFin T&ese functions !erform o!erations on "a%ues and
settings t&at are 'ui%t into t&e data'ase 2suc& as s!eci*cs
dea%ing $it& t&e user session3
String T&ese functions !erform o!erations on c&aracter "a%ues
suc& as CHAR and IARCHAR and t&ey can return eit&er
numeric or string "a%ues+
(umericC0at&em
atic
T&ese functions !erform o!erations on numeric "a%ues+
/ate and Time T&ese functions !erform o!erations on dateCtime *e%ds+
CASE and CAST
CASE su!!%ies )FFTHE( %ogic to SQL statements and CAST
can con"ert "a%ues from one data ty!e to anot&er+
1:

:u$t)n sca$ar (unctons identify 'ot& t&e current


user session and t&e c&aracteristics of t&e current user
session- suc& as t&e current session !ri"i%eges+

4ui%tFin sca%ar functions are a%$ays nondeterministic+


'uilt(in Scalar Functions
Functon 1sage
CURRE(TN/ATE )denti*es t&e current date+
CURRE(TNT)0E )denti*es t&e current time+
CURRE(TNT)0EST
A0P
)denti*es t&e current date and time+
CURRE(TNUSER
)denti*es t&e current%y acti"e user $it&in t&e data'ase
ser"er+
SESS)8(NUSER
)denti*es t&e current%y acti"e Aut&oriEation )/- if it
diGers from t&e user+
SYSTE0NUSER
)denti*es t&e current%y acti"e user $it&in t&e &ost
o!erating system+
1;
String Functions
Strng Functons
String function acce!t c&aracter "a%ue as in!ut and
can return 'ot& c&aracter and numeric "a%ue+
Functon 1sage
C8(CATE(ATE A!!ends t$o or more %itera% ex!ressions- co%umn "a%ues- or
"aria'%es toget&er into one string+
C8(IERT
Con"erts a string to a diGerent re!resentation $it&in t&e
same
c&aracter set+
L8@ER Con"erts a string to a%% %o$ercase c&aracters+
SU4STR)(> Extracts a !ortion of a string+
TRA(SLATE Con"erts a string from one c&aracter set to anot&er+
TR)0
Remo"es %eading c&aracters- trai%ing c&aracters- or 'ot&
from a c&aracter string+
UPPER Con"erts a string to a%% u!!ercase c&aracters+
1?
String Function $%am&les
Functon 'escr#ton E"am#$e Resu$t
UPPER Con"erts A%!&a C&aracter "a%ues to
U!!er Case
SELECT UPPER 2%1S.2MENAME3
FR80 %1S.2MERS4
ATEL)ER
>RAPH)QUE
L8@ER Con"erts A%!&a C&aracter "a%ues to
Lo$er Case
SELECT L8@ER2%1S.2MENAME3
FR80 %1S.2MERS4
ate%ier
gra!&i5ue
C8(CAT Concatenates t&e *rst c&aracter
"a%ue to t&e second c&aracter
"a%ue+
SELECT C8(CAT
2%1S.2MERN1M:ER-
%1S.2MENAME3
FR80 %1S.2MERS4
1D,Ate%ier
gra!&i5ue
SU4STR)
(>
Returns t&e s!eci*ed c&aracters
from t&e c&aracter starting !osition
and retrie"e t&e next n c&aracters+
SELECT
SU4STR)(>2%1S.2MENAME-1-,3
FR80 %1S.2MERS4
Ate
TR)0 Ena'%e you to trim %eading or
trai%ing 2or 'ot&3 from a c&aracter
string
SELECT TR)02LEA/)(> QAQ
FR80 %1S.2MENAME3 FR80
%1S.2MERS
SELECT TR)02TRA)L)(> ReQ
FR80 %1S.2MENAME3
FR80 %1S.2MERS4
te%ier
gra!&i5ue
te%ier
gra!&i5u
T&e fo%%o$ing are some of t&e String functions-
1B

Lets %earn a'out numeric functions $&ic& $i%% &e%! us meet T)0<s
re5uirements++
Scenario
Hi=
(o$ t&at you &a"e
con"erted t&e names to
u!!er case- no$ round
t&e num'er to decima%
!oints+
D
)umeric*+athematical Functions
Numerc;Mathematca$ Functons
0at&ematic functions acce!t num'ers- !rocess it . return
numeric "a%ues+
Functon 1sage
A4S Returns t&e and a'so%ute "a%ue of n+
CE)L Returns t&e sma%%est integer greater t&an or e5ua% to n+
FL88R Returns t&e %argest integer e5ua% to or %ess t&an n+
08/
Returns t&e o!erator o!erator remainder of m di"ided 'y nP
returns m if n is D+
P) Returns !i 2a!!rox+ ,+1116B:+++3+
P8@ER Returns m raised to t&e nt& !o$er+
R8U(/
Returns a numeric ex!ression rounded to t&e s!eci*ed %engt&
or !recision+
SQRT Returns t&e s5uare root of n+
SQUARE
Returns t&e ex!ression raised to t&e !o$er of P e5ui"a%ent to
P8@ER
2num'er-3+
TRU(C
or
TRU(CATE
Returns t&e numF 'er x- truncated to / decima%s+ )f / is D- t&e
resu%t $i%% &a"e no decima% !oint or fractiona% !art+ )f / is
negati"e- t&e integer !art of t&e num'er is Eeroed out+
1
)umeric*+athematical Functions
Fe$ mat&ematic functions exam!%es are s&o$n 'e%o$H
Functon
Name
'escr#ton E"am#$e 2ut#ut
Round Rounds "a%ue to
s!eci*ed decima%+
SELE%. %1S.2MERNAME<
R21N' +%RE'I.LIMI.< =0
FR2M %1S.2MERS
CC@&en Credit%imitS16DD+B:
16DD+B,
Truncate Truncates "a%ue to
s!eci*ed decima%
SELE%. %1S.2MERNAME<
.R1N%A.E+%RE'I.LIMI.<
=0
FR2M %1S.2MERS
CC@&en Credit%imitS16DD+B:
16DD+B
0od Returns remainder of
di"ision
SELE%. %1S.2MERNAME<
M2'+%RE'I.LIMI.< >??0
FR2M %1S.2MERS
CC@&en CreditLimitS1:DD
1DD


Lets %earn a'out date time functions $&ic& $i%% &e%! us meet T)0<s
re5uirements++
Scenario
Hi=
P%ease te%% me t&e
command to *nd t&e
current date+
,
Date ,ime Function
Funct
on
Name
'escr#ton E"am#$e Resu$t
/ATE Con"erts T)0ESTA0P or c&aracter string to
/ATE+
se$ect date2=??@?=3
(rom customersP
DDFD?F
D
A///AT
E
Adds inter"a% to date time "a%ue+ SELE%. A'''A.E2A=??@)?B)
?=Q- IN.ERVAL ,1 'A53
FR2M customersP
DD?FDF
D
/ATE/)F
F
Su'tract t$o dates 2Com!utes diGerence
'et$een t$o date time "a%ues+ 3
SELE%. 'A.E'IFF2A=??C)
B=)>B =>!DE!DEQ-A=??C)B=)
>?Q3
(rom customers4
1
T)0E Con"erts T)0ESTA0P or c&aracter string to
T)0E+
SELE%. tme2A=??@)?=)?>Q3
FR2M customersP
DDHDHD?
EKTRAC
T
A%%o$s t&e date !art to 'e extracted
2YEAR- 08(TH- /AY- H8UR- 0)(UTE-
SEC8(/- T)0ET8(ENH8UR- or
T)0ET8(EN0)(UTE3 from a tem!ora%
ex!ression+
SELE%. E6.RA%.+'A5
FR2M 'A.E2A=??E)?B)?BQ3 3
FR2M customers4
1
'e&ntonH /ateCTime functions o!erates on date-
timestam! data ty!e+
1
Date ,ime Function
Functon
Name
'escr#ton E"am#$e Resu$t
CURRE(TN/A
TE
Returns current date SELE%. %1RREN.*'A.E4 D1,FDF16
CURRE(TNT)
0E
Returns current time SELE%. %1RREN.*.IME4 DBH1DH61
CURRE(TNT)
0ESTA0P Returns current date and time
SELE%.
%1RREN.*.IMES.AMP4
D1,FDF16
DBH1H1D
/ate AdditionAdding days to a date SELE%. %1RREN.*'A.EFB?4 D1,D6
/ate
Su'traction
Su'tracting days from a date SELE%. %1RREN.*'A.E)B?4 D1,DD6
/ate
/iGerence
Pro"ides no of days 'et$een t$o dates
SELE%. %1RREN.*'A.E)
orderdate FR2M orders4
+%urrent date s =?B>)?=)BD
and orderdate s =?B>)?=)
?D04
1D
Fe9 more e"am#$es
6
+iscellaneous Functions
Msce$$aneous Functons
C8ALESCE23H
Synta" H

T&e C8ALESCE23 function returns t&e *rst nonFnu%%


ex!ression in t&e ex!ression %ist+ At %east one
ex!ression must not 'e t&e %itera% (ULL+ )f a%%
ex!ressions e"a%uate to (ULL- t&en t&e function returns
(ULL+

Consider t&e fo%%o$ing exam!%eH


SELE%. coa$esce+State< ANot assgnedA0
FR2M %ustomers 4
SELECT C8ALESCE2 co$umnB<co$umn=3
FR80 LTA4LEF(A0EMP
Functon 1sage
C8ALESCE Returns *rst nonF (ULL ex!ression in t&e %ist+
(ULL)F
Com!ares t$o ex!ressionsP if t&ey are e5ua%-
returns (ULLP ot&er$ise returns t&e *rst ex!ression+
:
)U""IF Function
T&e (ULL)F function com!ares t$o co%umns+
)f 'ot& t&e co%umns are e5ua%- t&e (ULL)F function
returns (ULL+ 8t&er$ise- it returns t&e "a%ue of t&e
*rst co%umn+
SyntaxH
Co%umn1 and Co%umn must 'e of t&e same data
ty!e+
E"am#$es!
SELE%. N1LLIF+B=< B=0
FR2M %ustomers4 9ou$d return
N1LL
SELE%. N1LLIF+B=< B>0
FR2M %ustomers4 9ou$d return B=
SELE%. N1LLIF+Aa##$esA< Aa##$esA0
FR2M %ustomers4 9ou$d return
N1LL
SELE%. N1LLIF+Aa##$esA< AorangesA0
FR2M %ustomers4 9ou$d return
Aa##$esG
E"am#$es!
SELE%. N1LLIF+B=< B=0
FR2M %ustomers4 9ou$d return
N1LL
SELE%. N1LLIF+B=< B>0
FR2M %ustomers4 9ou$d return B=
SELE%. N1LLIF+Aa##$esA< Aa##$esA0
FR2M %ustomers4 9ou$d return
N1LL
SELE%. N1LLIF+Aa##$esA< AorangesA0
FR2M %ustomers4 9ou$d return
Aa##$esG
SELECT (ULL)F2 co%umn1-co%umn3
FR80 LTA4LEF(A0EMP
;
%ontro$ F$o9 Functons
It is similar to the IF-THEN-ELSE logic where a value is
substituted based on the return value of the column
Synta"!
E"am#$e!
Se$ect %ustomerName< %ountry<
%ASE %ountry
WHEN G1SAA .HEN G1nted State o( AmercaI
WHEN G1JA .HEN G1nted JngdomI
ELSE GN;AI EN'
FR2M %ustomers
Control Flow Functions
CASE "a%ue @HE( Ucom#are*8a$ueV THE( resu%t U@HE(
Ucom#are*8a$ueV THE( resu%t +++V UELSE resu$tV E(/
?
C#S$ O&erator e%am&les
E"am#$e B!
SELE%. %ASE B WHEN B .HEN Aths s case oneA
WHEN = .HEN Aths s case t9oA
ELSE Aths s not n the caseA
EN' as Aho9 to e"ecute case statementA
E"#$anaton
Since CASE is 1- so Wt&is is case oneW is returned+
E"am#$e =!
SELE%. %ASE AAA WHEN AaA .HEN B
WHEN A3A .HEN = EN'4
E"#$anaton
Since CASE is not satis*ed 'y neit&er of t&e @HE(- it
returns (ULL+
B

)f ex!r1 is TRUE 2ex!r1 LM D and ex!r1 LM (ULL3 t&en


)F23 returns ex!rP ot&er$ise it returns ex!r,+

)F23 returns a numeric or string "a%ue- de!ending on


t&e context in $&ic& it is used++

)f ex!r1 is not (ULL- )F(ULL23 returns ex!r1P ot&er$ise


it returns ex!r+

)F(ULL23 returns a numeric or string "a%ue- de!ending


on t&e context in $&ic& it is used+
Control Flow Functions
)F2ex!r1- ex!r- ex!r,3
)F(ULL2ex!r1- ex!r- ex!r,3
E"am#$es!
Se$ect IF+BK=<=<>04 ;; >
Se$ect IF+BL=<I5esI<InoI04 ;;
5es
Se$ect
IF+S.R%MP+GhI<IhBI0<InoI<Iy
esI04
)K no
Se$ect IFN1LL+B<?04 ;; B
Se$ect IFN1LL+N1LL<B?04 ;;
B?
E"am#$es!
Se$ect IF+BK=<=<>04 ;; >
Se$ect IF+BL=<I5esI<InoI04 ;;
5es
Se$ect
IF+S.R%MP+GhI<IhBI0<InoI<Iy
esI04
)K no
Se$ect IFN1LL+B<?04 ;; B
Se$ect IFN1LL+N1LL<B?04 ;;
B?
,D
Nestng o( Functons

)n case of nesting of functions t&e inner most


functions is e"a%uated *rst . t&e out !ut of t&at
function ser"es as in!ut to outer function+

T&e !rocess goes ti%% outer most function return t&e


"a%ue+

Sca%ar functions can 'e nested to any %e"e%+ T&oug&


Some data'ase "endors &a"e t&eir o$n restrictions+
E"am#$eH
)esting O Functions
SELECT !"#IFN$LL#%RE'I.LIMI.< ?%%
F&'( %1S.2MERS)
Step 1:
IFN$LL function is a**lied+
If the SL column in N$LL, it is re*laced as -
Step 2:
!" function is a**lied+
verage is ta.en after the IFN$LL function is a**lied
SELECT !"#IFN$LL#%RE'I.LIMI.< ?%%
F&'( %1S.2MERS)
Step 1:
IFN$LL function is a**lied+
If the SL column in N$LL, it is re*laced as -
Step 2:
!" function is a**lied+
verage is ta.en after the IFN$LL function is a**lied
,1
What s E"#resson?

An ex!ression is a com'ination of one or more of


conditions- "a%ues- o!erators- and SQL functions t&at
e"a%uates to a "a%ue+
Where they can 3e used?

Ex!ressions can 'e used in-


T&e SELECT statement+
A condition of t&e @HERE-HAI)(> and 8R/ER 4Y c%ause+
T&e IALUES c%ause of t&e )(SERT statement+
T&e SET c%ause of t&e UP/ATE statement+
S!" $%&ression
,
E"am#$e o( E"#resson
S!" $%&ression
E"#resson
Name
'escr#ton E"am#$es
Sim!%e
Ex!ression
A sim!%e ex!ression s!eci*es a
co%umn- !seudo co%umn- constant-
se5uence num'er- or nu%%+
4uy!rice X 0SRP
Com!ound
Ex!ression
A com!ound ex!ression s!eci*es a
com'ination of a function and one or
mu%ti!%e ex!ressions
credit%imit J AI>2amount3
/ate Time
Ex!ression
A /ate Time Ex!ression can 'e a date
time co%umn or a com!ound
ex!ression t&at yie%ds a date time
"a%ue+
2re5uired/ate Y
s&i!!eddate3C;
Function
Ex!ression
A Function Ex!ression can 'e
com'ination of one or more Functions
SU02amount3 J
AI>2credit%imt3
C8U(T2customername3
CASE
Ex!ression
)t is simi%ar to t&e )FFTHE(FELSE %ogic
$&ere a "a%ue is su'stituted 'ased on
t&e return "a%ue of t&e co%umn
Se%ect customer(um'er-
country-
CASE country
@HE( RUSAQ THE(
RAmerica<
@HE( RUOQ THE( R4riten<
ELSE R(A< E(/
FR80 customers
,,
(o$ $e &a"e im!%emented fe$ of t&e T)0<s
re5uirement successfu%%y using functions+
Scenario
Yea
&=
,1
-eca& o the Case Study
%ase Study Scenaro!
T&is case study is to de"e%o! a Course Management
System 2C0S3 for A4C Uni"ersity+ T&e fo%%o$ing are t&e
t$o uses case for $&ic& t&e data'ase needs to 'e
designed+

Add Course
To add t&e course detai%s into t&e course management
system+

Retrieve Course
Retrie"e t&e courses stored in t&e system and dis!%ay it+
T&e courses to 'e added $i%% &a"e t&e fo%%o$ing
attri'utes Course Code- Course (ame- (um'er of
!artici!ants- Course /escri!tion- Course /uration-
Course start date and Course Ty!e+
@e $i%% use t&e same C0S case study for %earning &o$ to use
o!erators in /QL and /0L statements
@e $i%% use t&e same C0S case study for %earning &o$ to use
o!erators in /QL and /0L statements
,6
Pre)reMuste ! Use t&e CourseN)nfo and
CourseNFees ta'%e+

)nsert records in courseNfees ta'%e $it& 'ase fees as


nu%%+

)nsert records in courseNfees ta'%e $it& 'ase fees as


,DD and 1;6+
Pro3$em B! @rite a 5uery $&ic& $i%% dis!%ay t&e tota%
num'er of records in CourseN)nfo ta'%e+
Pro3$em =H /e"e%o! a 5uery $&ic& $i%% gi"es t&e sum
of a%% 'ase fees of a%% courses in t&e
CourseNFees ta'%e+
Pro3$em >! /is!%ay t&e minimum and maximum 'ase
fees of t&e courses+
Pro3$em N! /is!%ay t&e a"erage infra fees of t&e
courses+
"end a .and
,:
So$uton B!
SELE%. %21N.+O0
FR2M %21RSE*INF2
So$uton =!
SELE%. S1M+:ASE*FEES0
FR2M course*(ees
So$uton >!
SELE%. MIN+:ASE*FEES0<MA6+:ASE*FEES0
FR2M %21RSE*FEES
So$uton N!
SELE%. AV7+INFRA*FEES0
FR2M course*(ees
Solutions
,;
Pre)reMuste! @e $i%% use t&e CourseN)nfo and
CourseNFees ta'%es for doing t&is %end a &and+ Add a
ne$ co%umn )nfraNFees in courseNfees $it& ty!e
num'er26-,3+ For a%% t&e records in u!date t&e
)nfraNFees $it& some "a%ues say 16+;61- 1,+16, etc+
Hnts!

Use Zoins $&ere"er needed


Pro3$em D ! /e"e%o! a 5uery $&ic& $i%% dis!%ay t&e
course name and course )nfra fees of a%% t&e course+
T&e infra fee s&ou%d 'e rounded to one decima% !oint+
"end a .and
,?
Pro3$em P ! /e"e%o! a 5uery $&ic& $i%% %ist a%% t&e
course code and course names in CourseN)nfo ta'%e
$&ere in t&e *rst %etter s&ou%d 'e ca!ita% %etter+
Pro3$em C !/e"e%o! a 5uery $&ic& $i%% dis!%ay t&e
course name and t&e num'er of days 'et$een t&e
current date and course start date in CourseN)nfo
ta'%e
Problem 8 :/evelo* a 0uer1 which will concatenate the
Course Name and Course Code in the following format and
dis*la1 all the courses in the course2info table3
45 Course Name65Course Code67
"end a .and
,B
Problem 9 :/evelo* a 0uer1 which will dis*la1 all the
Course Name in u**er case3
Problem 10 :/evelo* a 0uer1 which will dis*la1 all the
characters between 8 and 9 of the Course /escri*tion
column for all the courses in the Course2Info table3
Problem 11+/evelo* a 0uer1 calculate average of all the
base fees, an1 records whose base fee is null needs to be
considered as :ero3
"end a .and
1D
So$uton D !
SELE%. %21RSE*INF2.%21RSE*NAME-
R21N'+%21RSE*FEES.INFRA*FEES<=3
FR2M %21RSE*INF2<%21RSE*FEES
WHERE
%21RSE*INF2.%21RSE*%2'EQ%21RSE*FEES.%21RSE*
%2'E
So$uton P !
SELE%. %2N%A.+1PPER+LEF.+%21RSE*NAME< B00<
L2WER+S1:S.RIN7+%21RSE*NAME< =000
FR2M %21RSE*INF2
So$uton C !
SELE%. %21RSE*NAME<
.2*'A5S+current*date3 Y
.2*'A5S+course*start*date3
FR2M %21RSE*INF2
Solutions
11
So$uton @ !
SELE%. %2N%A.+%21RSE*NAME<%21RSE*%2'E0
FR2M %21RSE*INF2
So$uton E !
SELE%. 1PPER+%21RSE*NAME0
FR2M %21RSE*INF2
So$uton B?!
SELE%. S1:S.R+%21RSE*'ES%RIP.I2N<B<>0
FR2M %21RSE*INF2
So$uton BB!
SELE%. AV7+IFN1LL+:ASE*FEES-D33
FR2M %21RSE*FEES
Solutions
1
Pre)reMuste ! Use t&e CourseN)nfo and
CourseNFees ta'%e+

)nsert records in courseNfees ta'%e $it& 'ase fees as


nu%%+

)nsert records in courseNfees ta'%e $it& 'ase fees as


,DD and 1;6+

)nsert , records in courseNinfo ta'%e eac& course $it&


course ty!e CLR-EL- 8F
Pro3$em B=! @rite a 5uery $&ic& $i%% dis!%ay t&e
course ty!e and t&e a!!ro!riate message as
mentioned 'e%o$+
Course2
T1*e
(essage
CL& ;Class &oom<
EL ;ELearning<
'F ;'ffline &eading<
"end a .and
1,
So$uton B=!
SELE%. %21RSE*.5PE< %ASE %21RSE*.5PE
WHEN A%LRA .HEN A$%LASS R22MG
WHEN AELA .HEN AELEARNIN7G
WHEN A2FA .HEN A2FFLINE REA'IN7A
EN' RES1L.
FR2M %21RSE*INF2
Solutions
11
Pre)reMuste! Let us use t&e Student_Info and
Course_Fees ta'%e+
Pro3$em B>!
@rite a 5uery $&ic& $i%% con"ert StudentN)nfo Qs
StudentN)d to (um'er and add 1DDDDD
and dis!%ay it for a%% t&e students in t&e StudentN)nfo
ta'%e+
Pro3$em BN !
@rite a 5uery $&ic& $i%% con"ert 4aseNFees into
Iarc&ar from t&e CourseNFees ta'%e+
And dis!%ay in t&e fo%%o$ing format
AT&e 4ase Fees Amount for t&e course name< LCourse
(ameM< is <L4ase FeesM
16
"end a .and
So$uton B>!
SELE%. B????? F %AS.+S.1'EN.*I' as decma$0
FR2M S.1'EN.*INF2
So$uton BN!
SELE%. %2N%A.+A.HE :ASE FEES AM21N. F2R .HE
%21RSE*NAME ISA<
%INF2.%21RSE*NAME< %AS.+FEESINF2.:ASE*FEES as
decma$00
FR2M %21RSE*INF2 %INF2<%21RSE*FEES FEESINF2
WHERE %INF2.%21RSE*%2'EQFEESINF2.%21RSE*%2'E
Solutions
1:
!uestions?
1;

@&at function is used to *nd


t&e num'er of c&aracters in
Iarc&arA

@&at function is used to get t&e


current system dateA

@&at $i%% R8U(/ 2,,+,1,-3


returns A

@&at Function is used to get


num'er of years 'et$een t$o
dates+A

Ho$ can ) con"ert a c&aracter


to a num'erA

Ho$ can ) con"ert a "arc&ar to a


dateA
Chec/ 0our Understanding
1?

A(S) SQL Functions C%assi*cation

/eterministic and
(ondeterministic functions

Aggregate Functions and Sca%ar


Functions

String Functions- 0at&ematica%


Functions

0isce%%aneous Functions
2C8ALESCE . (ULL)F3

(esting of Functions . SQL


Ex!ression
Summary
1B
:ooR ! 8Rei%%y SQL )n (utS&e%% Page No ! 1:1
:ooR ! @rox SQL Functions ProgrammerQs
Reference DD6 Page N2! ,1
/isc%aimerH Parts of t&e content of t&is course is 'ased on t&e materia%s a"ai%a'%e from t&e
@e' sites and 'oo#s %isted a'o"e+ T&e materia%s t&at can 'e accessed from %in#ed sites are
not maintained 'y CogniEant Academy and $e are not res!onsi'%e for t&e contents t&ereof+
A%% trademar#s- ser"ice mar#s- and trade names in t&is course are t&e mar#s of t&e
res!ecti"e o$ner2s3+
Source
6D
You &a"e successfu%%y com!%eted F
SQL Functions
ANSI SQL
6
1
Change "og
Verson
Num3er
%hanges made
VB.? Inta$ Verson
VB.B
S$de No.
%hanged :y
ESect8e
'ate
%hanges
ESected


6

You might also like