You are on page 1of 15

SQL FT]I\CTTONS

16.6 iIYSC.i. FUi'ICTiOh]S


s:le operation and
A function is a special type of preclefi*ecl command set that performs that are provided to
rtlhrrns a single Furrctions operate orl zero, one, two o,
*o.a values
'alue. parameters or arguments'
thcm. The values that are proviclei to ftlnctions are called
'|he Ivl,vSQL functlons have been categorised into variotts categories' such as String fitnctitnts'
MySQL offers a big bouquet
ltrlatlturrttticnl.furtctiotts, Dnte nnd Tirne funtctiottsand so on. Altl-rough
functions'
oi tuurctions, yet iir this discussion rve shall remain limited to some corlmon
r ir 5. I Slr"inq Funciiorrs
Some commonly
The string functions of MySQL can manipulate the text string in many ways'
used string functions are being discussed below

Function
1 cr{AR( ) Relums the character for 1 SELECT CHAR (70, 65, 67, 69 ) ;
each integer passed 2 SELECT CHAR 65 67 .3, '69.3
2. coNCAr( ) Rehtrns concatenated SELECT CONCAT(name, aggregate) AS "Name Manks"
string FROM StUdCNt WHERE =140R =J.b

J LO\^/ER( ) / Rehrms the argument in SELECT LOtJER('f'1R. 0BAMA' ) AS "LowerNamel-",


LCASE( ) lorvercase LOI^JER 'Ms. 6andhi' AS "LowerName2" ;
.,5UbS,,
4. suBSTRrNG( ), Rehrrns the substring as 1 SELECT SUBSTR('ABCDEFG" 3, 4) ;
uBS"rrl0 (ABCDE
specified 2 sELECT sUBSTR FG -5 4 "Subs"
ir. uI)Prjl(()iuCASE( ) Converts to uppercase SELECT UPPER('Large' ) "Uppercase" ;
or SELECT UCASI ncase" ;
)
6. TRIM( ) Rernoves Ieading atrd SELECT TRIM(' Ban One ) t
S

7 I-ENGTI-I( ) Returns the length of a SELECT LENS|H('CANDTDE') "Length in characters" I


in bytes

-''--,
1, .). i'.]u ; rtei"ir: i:unciions
'Ihe nr-rmber furrclions are those functions that accept nurneric values and after perfomring the
recpircct operalion, rehrm numeric values. Some useftil numeric functions are being discussed below :

Function Description Example


1 lvloD0 Retums the rernainder of one expression SELECT [10D(11, 4) "Modu1us" I
by diving by another expression.
) POTvER(yPOW0 Ileturns the value of one expression raised SELECT pgt^lER(3, 2) "Raised";
ttr thc porver of another exprcssiorr
J. ROUNLT0 Returns numeric expression rounded to an SELECT R0UND(15.193, 1) "Round" I
integer. Can be used to round an
expression to a number of decirnal points
4 srcN0 This function rehrms sign of a given number SELECT SI6N(-15) "Sign" ;
5. sQ11r0 Returns the non-negative square root of SELECT SQRT(26) "square root" ;
numerlc resslon.

6. I'RUNCATti() Reburns numeric expl truncated to exp2 SELEC| TRLnf,ATE(15 .79, L) 'Truncate" ;
decimal places. If exp2 is 0, then the result
wili have no decim al point.

Page l ol'i 1
7 l;,, i'; .i licie crrrci J irrrt: Furrciiorrs

I-,.;'rtu fLurctiotrs operate orr values of the DATE clatatype.

Furtction

I culilliYfij( ) / l{ettrrns the cnrre'nt clatc SE LECT CURDAI E 0 .;

C.UItt(l,1NIl-Dt\'1'L( ) /
ATE
31 a1- :A2:A1') i
DAl'li( ) Ex tracts the date part of a date LECT DATE('2A2O-12-
2.
date-time
Q2-03' ) t
3. tlON'IIJ( ) Rcturns the rtrontl'r fronl tlre date sELEcT MoNTll('2020-

SE LECT YEAR 20-02


,{. YEAno Returns the
NO\\( ) llcturns tl-re timc at whiclr the SELECT No,'^.l( ) ;
5
function execrttes c t ctrO N0l', t
Z
SE LECT N0'!'J
6, Retums thc current clatc and timc
65' 57' 59'
i::t;r'lpLr 16.13 Wrifc (t (ltrcrv to crentc a strirtg fi'orrr tlrc ASCI| rtnlrrcs 70'

Solution.
mysql> SELECT CHAR (70, 65, 67
' e'9 );
t---"----* -----+

stttdetrts hnaing age as L4


or 7'6'
i:)(i,,i,i t,L-i i6.1/.i Co/lc ntarmte rrntne artd aggrcgate for

tille Sltrtlaiit of exrunltle L6'3)


{Cttttsi.ler student
mysql> c0NCAT(name' aggregate) AS "Name Manl<s'LFROM
Solution. SELECT
-> WHERE a$e = !4 0R age = 15 ;

I i'larne Mat:ks I

t---'-- -------+
I AanYa340 I

I Gurvinder4B0 I

I Alj260 I

I I'etinrah400 I

I t'i.ria150 I

+_--- -----+
5 rcws in set (0'00 sec)
tttltttes 'MR' OBAMA' nntl'MS' Gatdhi' into lowercase'
i,).:,r,r'trLr- 16.I5 Displtty

Solution,
AS "LowerNamel"
mysql> SELECT LOl^lER( MR:9.819,,) ',
"LowerName2" ;
-> LOI'JER('lts' Candfri') AS
AS "LowerNamel"
Or nrysql> SELECT TCASE('Mn' osAJ'lA'; ',

AS "LowerName2" ;
-> LCASE ('l4s ' Gandhi')

Page2ol11
i):..i.ii,ii iii.i6 i)islri nydclnrnctusrxtrncttrlJrorrr3rtllcftchnrtcturtnttt'arrlsfrrttrtstritrg'ABCDEFG'
S' t\) "Subs" ;
Soltrtion. mysql> SELECT SUBSTR('ABCDEFG "
t_-__-------+
I Subs I

.i__*_----*--'f
i (ii]nF I

nnd 8904'
of enq)loYees B88B
l rrt,',0,-, tr; ;, ,rrr,*r, n" t tlvcc clnr{lcters cxtrncted from iobs
+-"' l' 3)
+

Solution. , ,u*tt*(job' +

l) +----
mysql> SELECT SUBSTR(job, 1, I

I ANA I

-> FROM emPl I CLE


)----- -------+
-> [^IHERE empno = 8888 or empno = B9O0 ;

Bsr One
i,ri.:.i..ipiI io.lg writeaqueryfaretfiope lcadirtga,cltrailirtgspacesftomstritrg'
'lRiM(' Bar One ') I
Solution. mysql> SELECT
i *___ _--------+
I TRIM(' Bar one ') I

i ri:w in seL (0'00 sec)

thue in string 'CANDIDE''


?
:-,., , l,i,i , i:. i:l Horr ttmtty clnracters are

Solution.mysql>SELEcTi'-l-1.]i..iji(,1..1,{.]iiDE,)''Lengthinchanacters,';

I ::i::: -': "n"i'-"'"-'j- ]

lll write n qLtery to cxtract n sub strirtg front string 'Qttailratically'


whiclt shauld be 6 cl'rstacters long
i.,i,., i,., i,i- r,, t i..) t)
giaen string'
iitrti stitrt Jrorrt 5!i' cltctractcr of thc
,5, |, );
Soltrtion. mysql> SELEcT SUBSI.RlNG( 'Quadr.atica}1y,
'i---- ----+
I SUBSTRII'1G ('Quadratical1y" 5' 6) I

---,-.
i ratlca ---- ;
+----- ---------+
j row in set (0.02 sec)

11 ctiairted by 4 nnd display S2'


i,,ii\,,ir,i i, l 6.2l Fi,d aut tlrc remsinder of
p01/ER(3, 2) "Raised" I
Soiution. mysql> SELECT l'10D(11., 4) "Modulus",

Page3ofll
'16,2) Tnurcnte unltrc
IyAh4pt_[ 15.7g to -1 decittwl
Ttlttce ,

Solution. mysql> SELECT TRUNCATE ( 1S .79, 1) ,,Tnuncate,, ;


f-*-------*r+
I T.r:uncaLe I

+--*--------+
i 15.7 I

i*-".*----*--+

[;;.,\i"iPLE ]6.23 Write n query to disploy ctrrre nt dste an ynut. systent.


Soiution'
mysql> SELECT CURDATE( ) ;
i**---------+
I CUilDArll O I

i :2C09"06-03 |

-1.-*---*-----+
i row in set

[:i;ii"rPl-[ 16.24 \Nrite {t quenl to displny dnte nfter 10 dnys of ctrrrent date on your systefi'

Solution.
rnysql> SELECT CURDATE( ) + 10 ;
-------+
ii.:rAlE() + 10
I i-. 1-r I

r ---- ---t thenYou adtl a rutntber to a date, llleil


-
I :l C 9 0 6 l. 3 ta
4r-- tctltnrctl ttulua is not fornratled as dutc.

01:02:03'.
[x.\MpLE i6.25 Writeaqlteryto'extracttlntefromagiuendatetineanlue'2020-12-31
Solution.
nysql> SELECT DATE(' 2020-12-31 A1:02:03' ) .;

+
I

- :l:-1 - :-::: -:: -::- ::- ::-::l f--" i


I ?-02a-72-31- |

+ ------+
L row in seL (0.03 sec)

[:'.r.i.tpLE't6.?-6 ltrite0ryrcrytoextrsctrtonthpartfromdate3'dFeb2020'
5o lurto i.t.

mysql> SELECT MoNTH( '2AZA-82-03') i

+____ -*-------+
I l"loN',rH ('2A20-02-03') I

+_*__ *---+
\? I

i____.- _-------+
l. row in set (0'03 sec)

Page4of11
disptny cttrrcrfi dntc and
tifirc'
i:i.\;.'i:'!i irr..l/ \lrite n qru:ry to
Soltrtion. mYsql> SELECT NOI{( ) ;

1 NCh'o I

+
j,^,'4-..6-0? 1q.l_i:20
I :uw- vr I

1 row j.n set (0.00 sec)

betrttcen nou)( ) and


sYsdnte( )'
[',;,rr,;.ipLt i6.23 Write fi qlte,y to illtrstratc tlrc dit'ferencc

Solution.
mysql> SELECT NOi^lO, SLEEP(2), Nol^Jo;
---+- --*----+
i*--= --+--
I SLEEP(2) I Nol,lo
I

I NOHO -----+
+---- --a'-- ---+-
I 2009-06-03 L5"32"34 I

I 2009-06-03 l-5:32:34 I 0 -------+


+*--* ----+ -+-------\{
] rol in set (2.01 sec) 6\
.\./t,..r. //},'ai,)r[ t.st tl,cry t,
tlt,, ttotvi ] gir,,,s t/rt ){//}l(, ),,t/r/(' L,t LtJt1,1

I s,:r.'rrltis (tltttlt(2) l, l:rrt r-ts'lrtt':(J tilftri's ltuvc a di[tt't'tti'c tti


.l :.'ti,,ttdr hc'('llllJ'' ol sltt'p(2)

mysql> SELECT SYSDATEo, sLEEP(2), SYSDATEo; fr,/


+---- -'---u--$/---
t/(
: --- --+--
I SYSDATE () t SLEEP (2) I SYSDATE 0 I

+---- --+-- ---*+- -*-----+


| ?-009*05-03 15:33:15 I 0 I 2009-06-03 15:33:47 I

+*--- ---+- ---+- --*----+


.l row in sef (2.01 sec)

Cgr-rrpare the above lzuo results. The nozu( ) function will refum the same result even if you use it
rntrltiple tirnes in same statement, even after creating delays (such as through sleepO that creates
clelav of specified seconds) because the rrozu( ) function returns the begin-time of statement,
whereas sysdate{ ) function refurns the execution time of its own i,e., at what time it started to
execute. After reading these lines, compare the above results once again. Now you will clearly
understand the difference between the functionality of the two functions flo?{r( ) and sysdafe0.

16.7 AGGIIEGA.TE FUNCTIONS

Till r-row,vou have learnt to work with functions that operate on individual rows in a table e.g,,\f
you use Round( ) function then it wiil round off values from each row of the table.
NIySQL also supports and Provides group functions or aggregate functions. As you can make
ollt that the group functions or aggregate functions work upon groups of rows, iather than orr
single rolvs. That is why, these functions are sometimes also called multiple row functions.
Ir.4anygroup functions accept the following options :
1)ii{i'iilc'f This option causes a Sroup function to consider only distinct values of the
argument expression,

;11.i. This option causes a group function to consider


all values including all duplicates.

Page)oIll
secfion
of example:,'" tntt
.l.ire usage of tirese options r,viil become clear u,'ith the coverage
i based.rrol
table empl'
Ail tirc examples that we'il be using here, shall
be
'o"o'ving
16.5 Dotabase toble emPl
T able ---+'- __--+
-+--- --+-----+-- --+-'--"-'+
.(-----+---- coMM IDE PTNO I

INAME I JoB I l'lGR I HIREDATE I sAL t _---+


l[r,lPNol +---- -+--'--t---- -. -, -'-+ ---+"-'-"'+'- 20
t-----I'---- -12-LB 1800'00 INULL
I

S|'1ITH ICLERK 18902 11990 30


,ja9 i -02-20 11600'00 1300'00
I

.-i{!r9 TANYA IsALESMAN 18698 i"" 30


|t250'00 l5o0'00
I

I'ALESMAN Is69B it"'''02-22 lt)


iiiS..r i is[r]i 4-02 12985'00 I NULL
I

I'IAIIADEVAN lI'IANAGEn I 8"' i 30


I s5b6 I '991-o IL2s0'00 I1400'00
I

IsALESMAN ls69; irg"-og-2| 30


iur,s4 tr,loMlN i t"'-05-0 t 128s0'00 INULL
I

10
1 8595 IBINA
IMANAGER
15000'00 INULI'
I

lPRESlDIiIlr ' 'ut' it"'-11..18 30


js8-t] lAi"lrR I 1s00'00 I 0'00
I

iiuLDEEP i SALESMAN '""i i 1,0


I BB44 I ' 'nn'-09-08 12450'00 INULL
'u" t'nn'-06-0g )o
I

IEBE2 iSHIAVNSH II'IANAGER 'UU" I1100'00 INULL


I

ICLERK i'n"-oL-r| 20
IJ836 IrrNooP r 3!00 '00 I NULL
I

I A)'jAI'YSr ''uuu
u"u i i"' -12-og 30
i !-rBE i icorr ' ii"'-72-03 1950'00 INULL
i

20
ril!00 l,l,4r1}l lcLERri t3!00'00 INULL
I

IANALYSr ''u" -72-0: r0


ts9,)2 lfAlirR 11300'00 INULL
I

'"uu 'i"'
lLgg2-at-23 --*--+
is934 irlrrA t""'*n -----+- -+--'---"+-
-+--- 'uu"
--+-----+-
+----- +----

I. AVG
given data
'l-his function computes the average of

5vrurax
n)
,,vG( lDlsl'"tlic-i I ALLI
of parameter(s) tl'
;" Rehrrns average value
Numcric +____ ----+
l'Junrcric \gturn yn\tq:
Argylent lype : I Average I

empl +____ ---------+


listed itt table
'i)(,\i,if:ri. ii.?-9. Cnlcttlnte aoerage
snlnry of all entployees | 201 3 .92851 t i
AV6(sal) "Average" +--___--------+
Solution' mysql> SELECT I row in set (0 01 sec)
FROM emPl ;

/J
L . ,)Ui'.-i -^.. ^^r..
ThisftrrrctioncountsthenumberofrowsinagivenColllmnorexpresslon.
SvNrnx
ALL] expr])
c0ui'Jr({ * [DrsrrNCT I

rows in the query'


r lleturns the number of
..lf),,ouspecifyargumentexpr,Lhisfuncti<lnrelumsrowswhereexprisnotntrll.Youcatrcount
distinct values of expr'
eitirer all rows, or only
llfyouspecifytheasterisk(*),thisfunctionreturnsallrows,includingduplicatesandnulls.
Retun uttlttc: Numcric
Argttmcnt lYPc : Nrrnreric

Page6of11
.f _-....- ------+
!.;tr,i"it'L[ 1ij.30, Corttti rtrtttiret of tuortls itt tnltlc tttrytl' I ToLal. I

.l___--,---""1.
Solution. 14
I |

mysql> SELECT C0UNT(*) "Tota1" 1.___*------+


FROM emPl ; 1 row in set (0.00 sec)

[;r.,r,iu'i Pr-[ 16.31. Cotttti trrttriter oi iobs itr taltle ertryil


Solution.
mysql> SELECT COUNT(job) "lob Count"
FR0M empl ;

[).3\jv]irLr 16.32. Llottt ltnrnl tlistittct jobs nra listcd itt tnble un1il ?

Solution"
mysql> SELECT COUNI(DISTINCT job) "Distinct Jobs"
FROM empl ;

sec)
3. iiAx
This function retllrns the maximum value from a given column oI exPfesslon'
SvNrnx
l"1AX( [DlsTIt'JCT IALL] exPr)

^ Ilelums maximttm value of argument erpr'

i\rgurnent ttlpe : Nurneric Rehn'n anlue : Numeric

[:)'i,il,.tpLE i6.33. Disptlal rrtsxinnrm snlnry ftom tnble en4tl'


Solution.
mysql> SELECT MAX(sal) "Maximum 5aIanY"
FR0f4 emPl ;
sec)
':. ,/, r'j
'this functiort returns the minimr.rm value from a given column or exPression'
SYNTAX

MrN([DrsTrNCr I ALL] expr)


x llctrrrns minimum value of erpr'
At'gutrttrtt tyPa Nr:meric Return unlue : Numeric
+-*-- -*----+
[:r,rt tprr 16.34" DisTtlny the loirtirtg dnte oJ seniornost enrytloyee' lMinimum Hj-re Date i

+---- ------ I

Solution. ,I lL oon-11-1Q
-t )v I

mysql> SELECT MIN(hinedate) "Minimum Hine Date" +_-__ ----*-+


FR0M empl ; 1 row in set (o ' 06 sec)

Page7of11
7 :j SLlivi
Ihrs ir.rnction Leturns the sum of values in givcn column or exprcssion'
Svxrnx
sui"1( [DrsTrNCT I ALL] n)
^ lletums sum of values of n
..'1r'.qri rir.'lr f fyPr : Nttnrt'ric Retttnt utthrc ', Nurnertc

i,riAi,ii)f.i 16.-i5, Disylnrl totnl snlnry of nll enrytloyees listed in tnltle enrytl'

Solutir:n'
sec)
ntysql> SELECT SUM(sa1) "Total SalarY"
FR0M empl ;

Some more exalnples of grouP functions are being


givenbelow :

Ixomples:
1. To caiculate the total gross for empioyees of grade'FiZ"
thc cotnmand is :
function is a single value'
SELECT SUM(gnoss) FR0M emPloYee
I^JHERE grade
*'E2' ;
the command used is
with grades'E1', or '82"
:

2. To display the average gloss of employees


SELECT AVG(gross) FR0M emPloYee
t,n]HERE (gnade ='E:1' 0R
grade ='82') i

3'Tocounttirenumberofemployeesinemployeetabie,theSQLcommandis:
sELECT C0UNT(*)
FROM emPloYee ;
use the follorving
the number of cities, the t:lifferent members belong to' you
4. To count
command :
SELECT COUNT(DISTINCT
city) FROM members ;

The * is
keyrvord ensures that multiple entries of the same cify are ignored'
r-{crc t}re DISTINCT
onry with couNT, fu.ctions other than
trre onry argument that
incrudes NuLLs when it is used
COUNT disregard NULLs
in anY case'
The follorving
inciuding repeats' the keyword ALL is used'
if yor.r rvant to count the entries
conrnranciwillCoUNTthenunrberof,-'onNuLLcifyfieldsinthefiunlberstable:
SELECT COUNT(ALL CitY)
FROM members ;

In general, GITOUP functions


a set of rotvs'
+) Retr-rrn a single vaiue for
values, and some Text types and DATE values
e) Can be appliecl to any numeric

Page8of11
. r... -!L fiPES oF us talk
Nirn, th.tt \'otl hil functions can
catetories' SQI- stt
J]r'r1 lYf'cli
c"rt*Sorized itrttt fo Iltlu'irtg
-- llittr' (or :''i,,;i'li) ftrrruliotrs'
Sirrlil,-'
t !rtlill! ol' r'\!li;l'(' '6.rtt') fr'rnclions
'*. llhrltilr Itr llrrrv (oI'
work with a
ir) Sirrglr Rot* fircfiorts of a clueri ed table.
rr.turns a result ft'rr t'r'ery rolv that you learnt in Class
rrctitttts are thc functiclns
lixamprles of Sirrg/c rlu .ft(
as ycar( ), clay( ), etc
Ii rf,;Clrit rart $ j:tt n c ti L'tts srrclr
rvurk with data
1il) .MrlfiPl c Ronr ar Grouy ftmctitttts
return asgrega ted value that you have learnt
are the grouP functions in
Examples of multiPle row functions
min ( ), Avg( ) etc'
prcvittttssectir:n i.c., sum( ), count( ), max( ),

o-f functions is,in tlre


of rows they act upr:n'
The rlifference between these two types lumber
row function works with the rlata of a single row at a time and retums a singie
A singte with a Sloup of rows and
uPon; a multiple row function works
result for each row queried
retums a single result for that ErouP'

I,6.4 GROUPING RESULT


. GROUP BY

The GROUp By clause combines all those records


that have identical values in a partlcular
field or a group of fields. This grouping results intl-o11 311111ty
tu.*t! q:t group
iI
is usecl in SEIECT
group-funcrions are;;;i,h it."t, oih*r*words, dre CROUP BV clause
$tatements to divide'the table into groups. Grouping can be done
by a column name' or with
each group' For
aggregate functions n *f-.f. casl tfre aggreg;te-Produces u uulr" for
**i*it", to calculate the nunther af etryloyees in each grade, you use the command
irre(T j$b, ($uHr(*)
t.,,ilM flmp I

i;i'i'!1jP i*Y j0tr ;

CROUP

*"-

Page9of11
l1 \\'lr,rt rr'rll lrt' tltt: (rtll[111t oI Iirllorr'irrE nrdt' ?
nrysql> 5[.t[.cT' coNCAT ((oN('A-r ('rnform','at{c3')r'pra(t1cG3r}i
i .* l'!hat rr"ill lrt' thtt orttput of fullorvirrg cr:dc ?
mysql) s[Lr.CT L.(AsE (.lNFoRMArIc$ PRACTICE$ CLAS$ 11TH,} ;
\\'h.rt rvill [t tlrt: ortll:ltt of folluwing cor'lc ?
il-vsql> 5Ei.r(r ucAse ('computer studies') ;
ti\ \\')r;t rr'ill trr' ilrc otltfut of following codt' ?
ft!sqj> SELECT C0NCAT (Lo{ER (.c]ass'), UPPER (.xii') ) ;
lt Str .. ,.lNFORN{ATICS IIRACI.ICES ..'.,, and Strl -,..' FoI{ CLASS xI,,
1\'ritt' -sQi. stntunlcllt to t'lisplay
roday, the date is <current date>
tthat is a constraint ? Name some constraints that you can aPPly to enhance database int€Pity'
What is the role of UNIeUE constraint ? How is PRIMARY KEY constraint
different from IINIQUE
constratnt ?
What is primary key ? What is PRIMARY KEY constraint ?
lVhat is NOT NULL constraint ? l{hat is DEFAULT constraint ?
When a column's value is skipped in an INSERT command, which value is insert€d in dre daabase
?

\{trat is the error in following statement ?

. .r: . "

Idenri$, the error :

.I .rr;Id I;",ijr. f hl"1Pl- ,

Yrpx $* : Srrort Answer Questions q

What is the role of database server in database management system ? Give the key features o$

MySQt-.
How are SQL comrnands classified ?
Differentiate between DDL and DML commands.
; Write SQL commands for the following on the basis of given table CLUB

Table: {-.l.,ti}t
' q0AC!!::I!
_-
AgE 5r0fr5 DATAFAp.F sfx
I KARATE ?710311e96 1000

2 prqyprlfi :r;.,,i' ',.M, ' KARATE 20/01119e8 1200 F

3, KARAN 19102/19e8 2000

BASKETBALL 0u01/19e8 1500

ulau1998

Page 10 of I 1
fAY $EX
tfiActtJ0 c0A CHNAITE
F
?4fi2119e8 &{ru
KETAKI 36 SWIMMINC
6 F
2{tlil2l1W8 22W
n ANKITA 39
100 F
37 KARA'TU 221$2lle98 1

8. q0a ;v{
4l SWIMMINC tllfi1l1w8
9. KUS}J M
I}ASK['TBALT, 191{}21w9* t7{N
sl lAlt-YA J/
I rl.

des*nding order'
fot all the ccar:hss'

'199&01-31',;


Grode Class

B 128
78,5
I r\-
Commerce- 89.2
C T?C
Com.merce 68.6
B 12C
73.1
OA 114
N onmedical 90.6
B 128
75.4
C 114
Humanities 64.4
88.5
A l1{
92.0 A ll.A
500.00 onmedical
C I?C
Conrmerce 67,5

(a)
by StiPenrl.
(b)
in descendirtg order
{c) receivsd in a year
(d)

te) v5; :

l
1

A'; l
l

i
lI

I
tr, What I
I
.,'{
I
t

Page11ofl1
SOL CONSTRAINTS

(. | )llllll{l!1 inclurle th* foll*wing

r .$.rY*. fs.;strsirrt$
\rilJ \rlll .": [:;"irru|r.s llr*tt ;t t:(rl*rnrt have

ili:i',^1tlt-';-
), i i,\iLliJi- Irtsrl rc5 thltl ;rl valrirl* 1n r*lumn sre diff rerr*.

--.i
i. I ii r.l', t ful;rk*s sur* th*l all valucs rn a column
l
: iri Jrr'ili: tl ]\{'{
i
I (i',1,
i i',ri'jtll

:,i'.. N$T NULL; i;,i :r,-.,,,i.l


iii .lcl;ult, .r colunul can hold NULL. If you not want to allow NULL
rr,ill rt ant to piace e con$traint on this column specifying thAt NULL
li,iur,. For ex.rrnple, in the following statement,
(REATE TABLE CUstOMEr
( sio integer i.,ri,:.'i r;r;r ,- ,

Page 1 of4
,\(tt,r this 5Q[. rirtr:rV , ih* tahl* rvill k:*k lik* ll'le fcrlltl wuls
:

Sfudent J0
.tr.'r:, .Scr.'*: Jir:liJ tms
8U thr Jt:ftiuk t'alue
Irr Qrrmshi

irr thc INSI,RT INTO sfatern*nt'


l:\,*n thl|ugh rvi: cliiln't sp:rilV iT \N.llg11 f6r tlrr'$rtrrr Lttltlnllt for
alrr:a dv sct 8{) as th* tlt:-fttu/l e,rJttr
il drxs gl,t ;lssigtrcd th* r&:,firull {,olttr *f S0 xince rYe had
this colittrtt,

{:rt}ter vat:lrd'6,
11'li'tl\lQfi[:ronstr.tintensure$t]ratallr';rlu*sinacnlumn'rr+:rlistinci'lr
lli)lr"{ the s;ttttt'valu* fr;r a ci;lutnn wilh
UNIQU[' e*nstraint'
ii\'.-, i'(1r\ s,.:.lll
*tatem*nt'
iiirr r,\.l1ilpls. itr th* lollor'r'ing CItIATI'I'AB1'[
LRLATE TABLE CU5IOMET
SID i nteger ;''' i 'r: '
'
(
varchar (30),

duplicate ue*, $rtch


$r:, if thtl t*hle

filnteins
Lust*Name first*Narne
Wangroo Pturrsuk

Qureshi Fathan
,
R

fix*ruting statement, Please note thar a coiumn


that is rp*cili*tJ as a pr:rna;"v key
' Inust ;lis* be *niq**' '{r ri:s sar*'e
dtrne, a c$ltimn thar'* uniq**
rlxey

of m&y not k a pr"imarT key' trn


rvill result in
addition, multiplt uN*QUr
in the 5/D c$n$traints can b* defined on a
with that table.

"I'hc CI"{ECK
r*rtain ri:rnditi,.x'ts' filrce
fin* rurv ii lht nerv v&luc
definecl, the ensur* d*ta quatitY
satisfies the
l:rlr examPla

Page 2 of zl
// ,/

i. *11ss111 $IL) has i{ r$rr*tralnt


ifs rmlue ffiN$t. ofilrl''iadudr
,rltrurpting t{} cXdCutB the
INSERI" Xl,tTfl (u$ f$n*r vAlux.s (**),,'Gonralves",Lindan) ;

*lt,rrrlr-l rt..trrlt ilr ;rrr err(rr bucarr,sr. thc value$ q';**{*i} Pls*** np,m ttrat
for SIL)
*rirrf tr* $rrittt'r. thnrr 0. Sut ynu wiII find that your
qurry i* *xccutcd withuut cherking thc rnndition
specified through (HECK constrainl. T&c rrasor brirrg

PRIfrilARY fif,| r. .i;i Lr,rt;',,i::i,i

^t\ |r!1116O" hey is used. tr: uniquely identif each row in a table. It can *ither be part of
the
*t'ht'rl rt{orcl itself, or it can be an-artificii fieta (one that has nothing to do wittrthe
uomJ
rcct'rd)' A prrimary-key can consist of one or more fields on a table. tlytur, multiple ri-far
use,J as a primary key, they are called a comporite
key. "*
Ilrirnarv k*ys can be specified either when the table is created (using CAEATE TA$tr
ci',anging thr-. existing table struchrre (using ALTER TABLE).
e cx byr

Defining Primory Key through creore Toble commond


Yr:u can define a prfurrary key inCIREATE TABLE commandtlxough keywon{s PRETAKYKXY.
5t:iow are exarnples for specifying a primary key when creating a table :
CREATT TABLr (ugtfrner.
( Slp i nteger not nul l t,{i;:*}.a }' i'.i, i" u

Last_Name varehar(30),
Fi rst-Narne varchar(30) );

$r (EHATE TAgLf; CUSTOM€r


( sro integer not nu'|l,
Last-Name varchar(30),
Fi rst*Name varchar(30),
: ir !.'*..rr. r tlo { ,, i fl I );
lhe latter w*y is useful if you want to opeeify a comptrsitn primary kry e.g.,
CRSATE TAELE

You can

Page 3 of4
v ,!q&$q.ft$ii&
jrr.l.fr .irr'(,\ilnlplt's itrr spetifying,t
primary key by t:f,:f :: Before using th€ ALTER

prirnfiry k*y, you,il need t0 make


4l"t F,R -TABLE Custsmer gurs rhat th* field is deflned *r
Air0 PRr.rdARY KIY (Sru);
rc; , 'NOT NULL" * in cthsr wordi,
NULL cannot be an a(cepted
yalue {or that field.
FOHEIGN KEY
i'. r'r I{D}il\,1S. la[ilr'r fralercn(€ $r]c an$thcr t]rrr.rugh r.*mn1{}rr fi11lds irnd
fcr €{r$ilrf validitv of
ful{r'(:'rlr'r:h, rr'fi:rclrlt,t/ irtft'trih/ is rnf*re*d. Iir./trrnlial inltgrittl i5 rr syslr:n *f rttll/].; tk*t
stiiiMs
i,:'i.' l,' r ritrli'(' llluf lelrrtittrlslrry;s br'lurefit recorils in rclatul ln&i*s ar* z:*lid, rtird tl,af us*rs don,t
.;,'.,,ii',1,;iJi.. ifr'lr,'fr'r:r.Jtilltft'rr/nfr:rJ rfirfa. Referential integrrity is ensured through pq3HEIGN
r.L \ , ()r'!str'"utlt"
'lhis is implcmented as explainrd in thr: fallowinq
prrugr*pt,-
i\'iir.,iir'r'rl trt'o tahl*$ are related hy il conlmon column (or sei r:f columnsj, thert th* related
.'i::iir:riris) in the p*rent table (or prinraqy table) should be ertirer declared n PIdiklARY KHY
,,: L:i\iQLih, key and the related colurnn(s) in the child table {or rel*ted tabl*} Eh*ulcj have
Fdl( EltlN KE)' constraint.
For instance , if we'hf,ve'two tables having strucfure$ as given b*low :

Table: . L.jlai(?ffir.ei Table ' * rs1, -i '

5ID Order*lD
Last Name 0rder*Dats

the Curtomer*SlD eolumn in the ORn{ftS teb}e is * roreipr kev


m the CUSfSMIR table.
can also be created in ftrro ways : thruugih CRIATE TAEL&

foreign key's delinition through fcllowing $$"rtilx


:

ed*a$-forei gn*key>) rtf*rxnees

wh*n rrtmtins, the ORDXRS table

Page 4 of ;l

You might also like