Professional Documents
Culture Documents
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
-''--,
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 :
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
Furtction
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-
Solution.
mysql> SELECT CHAR (70, 65, 67
' e'9 );
t---"----* -----+
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
Bsr One
i,ri.:.i..ipiI io.lg writeaqueryfaretfiope lcadirtga,cltrailirtgspacesftomstritrg'
'lRiM(' Bar One ') I
Solution. mysql> SELECT
i *___ _--------+
I TRIM(' Bar one ') I
Solution.mysql>SELEcTi'-l-1.]i..iji(,1..1,{.]iiDE,)''Lengthinchanacters,';
---,-.
i ratlca ---- ;
+----- ---------+
j row in set (0.02 sec)
Page3ofll
'16,2) Tnurcnte unltrc
IyAh4pt_[ 15.7g to -1 decittwl
Ttlttce ,
+--*--------+
i 15.7 I
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
01:02:03'.
[x.\MpLE i6.25 Writeaqlteryto'extracttlntefromagiuendatetineanlue'2020-12-31
Solution.
nysql> SELECT DATE(' 2020-12-31 A1:02:03' ) .;
+
I
+ ------+
L row in seL (0.03 sec)
[:'.r.i.tpLE't6.?-6 ltrite0ryrcrytoextrsctrtonthpartfromdate3'dFeb2020'
5o lurto i.t.
+____ -*-------+
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
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
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.
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,
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
10
1 8595 IBINA
IMANAGER
15000'00 INULI'
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
'"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
/J
L . ,)Ui'.-i -^.. ^^r..
ThisftrrrctioncountsthenumberofrowsinagivenColllmnorexpresslon.
SvNrnx
ALL] expr])
c0ui'Jr({ * [DrsrrNCT I
Page6of11
.f _-....- ------+
!.;tr,i"it'L[ 1ij.30, Corttti rtrtttiret of tuortls itt tnltlc tttrytl' I ToLal. I
.l___--,---""1.
Solution. 14
I |
[).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)
+---- ------ I
Solution. ,I lL oon-11-1Q
-t )v I
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 ;
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"
:
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 ;
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( ),
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
?
. .r: . "
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
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
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
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
{: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),
filnteins
Lust*Name first*Narne
Wangroo Pturrsuk
Qureshi Fathan
,
R
"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
// ,/
*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
^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
Last_Name varehar(30),
Fi rst-Narne varchar(30) );
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
5ID Order*lD
Last Name 0rder*Dats
Page 4 of ;l