0% found this document useful (0 votes)
10 views25 pages

Relational Database and SQL Pt.2

The document provides an overview of SQL commands for inserting, updating, and deleting records in a database table. It explains different forms of the INSERT INTO command, including inserting all columns, specific columns, and handling NULL values. Additionally, it covers the UPDATE command for modifying existing records and the DELETE command for removing records from a table.

Uploaded by

anushka.120077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views25 pages

Relational Database and SQL Pt.2

The document provides an overview of SQL commands for inserting, updating, and deleting records in a database table. It explains different forms of the INSERT INTO command, including inserting all columns, specific columns, and handling NULL values. Additionally, it covers the UPDATE command for modifying existing records and the DELETE command for removing records from a table.

Uploaded by

anushka.120077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

1. lnsnt ing 0.&t.l into a T.

1b lf'
The ISSERT INTO command is used to insert a new record / row/t
uple in a table.
It tS poss~b ie to write the INSERT ISTO statem ent in the follo\\ing
differ ent forms :
(a) Inser ting data (for all the columns) into a table: In the first
metho d, it does not specify th,
colum n names where the dat.a "ill be insert ed. only their value
s.
S}'Dtll for SQL INSERT:
ISSERT l~'TO <table_name> VALUES (value1, valueZ, value
3m);
For example, mysql> :~s::.::.. : I~::o St:.;cient
v ;..::..;E5 (l , " ?.a j Ku=:a.r ", •M • , 93 , · 2~v c-., - ·•
.... - - '~
7 '
) ;
While insert ing a row, if we are addin g value for all the colum
ns of the table, we need not.specify
the colum n(s) name in the SQL query. But we need to make
sure that the order of the values is
m the same order as the colum ns repres ented in the struct ure of
the table. The follo""'ing points
s hould be kept in mind while insert ing data in a relatio n:
• When values are inputt ed using INSERT INTO comm and.
it is terme d as single row
insert since it adds one tuple at a time into the table.
• The INTO clause specifies the target table and the VALUES
clause specif ies the data to
be added to the new record of the table.
• The argum ent/ values of chara cter or text and date dataty
pe are alway s enclosed in
doubl e or single quota tion marks.
• Colum n values for the date data type of a colum n are provi
ded within single quotes in
'yyyy- mm-d d' or "yyyy/ mm/ dd• forma t
• t\UU ,.-al ues are stored and displa yed as NULL only witho
ut any quote s.
• If the data is not available for all the colum ns, then the
colum n-list must be included
folloY.ing the table name.
CTM: In SOL. we can repeat or re-execute the last command
typed at SQl promp t by pressing up and down ,.
L ~ keys followed by Entef key.
.
1
(b) Inserting data by specifying all the colum n name s and assoc
iated value s into a table: The
.second fonn specifies both the colum n name s and the value
s to be insert ed.
Syntax for SQL INSERT:
INSERT INTO <table_name> (column1,column2,columnN,_.)
\ 'AWES (value1,value2,valueN_ );
Here. colum n 1, colum n2. ,_colum nN-t he name s of the colum
ns in the table for ,.,.,ihich you want
to msen data.
for txamp le, mysql> I~i~E~ :' nao S-:ud ent (Rcll No , Narr.e , Ge nder, M.3!'.ks , C(3
)
':P..:..!_'ESt2 , 'Ceep Sir.g h', ' M' , 98 , ' 1 996- 0B- 22 '
);
[CDt ~~ •ro w. onl~ IN chMactffl 01 date values should be enctosed . . . . sangle
o, double Quot~

( c) lnser Un1 data Into specif ic colum ns of a table:


Syntax for SQL INSERT:
INSERT INTO <tabl e_nam e>l(c olum nl, colum n2, -colu mnN ))
VAWES ((val u•l. nlue 2- nlueN )J;
·k
t"rt a l"f'Cord Into the stu d r nt •~hJ f r th(• col um n, ffol l nn N,j m(• .11111 M .J 1 "
le to tns - e o ·
etJl11P '
f,,r SQL insc11 qut •ry Is:
' thC
i,11 '\ . ., ._
o Ntm
..,c:[ RT 1NT 0 Stu ctlm t (Ro lln ,
· ~ ,. 1,,~ • .~ , 1·,,1 ra;.•1 )
1 78 );
lf1\~ VALllEE: ( 4 , " Rd dhl ktt Gu pta ",
t• .rnd M.i rk -.
vt stat t.•m ent sha ll ins ert the val ues for spc rifi c col um n,- Roll110, N.Jm
fht Jt,,,
ll hold th e V.1 Ill ('S clS NULi ,.
_ ·tivt •ly. Also, the col um ns Gen der and DOB sha
ll'"p t'l sl ng vJlue, th en th<>
a col um n In a row has no v.ilu e or rnl-.
insrrttng NU LL val ues Into a lable: If co lum n oth l'r th.i n
L value. Null valu e ca n be given to a ny
.Jl c,,iurnn is said to be ~ul l or hol din g NUL Is adv isab le to use Null whe n th e actu
c1I
pnm ary key or Not Nul l con stra int It
t,t!OS assigned as es a,; the y
def ined or una vail able . NUL L valu es are trea ted differe ntly from o th er valu
value is not L valu es.
esen t mis sing unk now n dat a. By def ault . a colu mn In a tabl e can hol d NUL
rt'Pr
a n exi stin g tup le
can Ins ert a new rec ord or can mo dify
If a column in a tab le is opt ion al, we for thrs
val ues to this col um n. In oth er wor ds, the valu es in eve ry rec ord
",thout add ing a tab le. Jt
as NUL L. We can inse rt NULL valu e into any co lu mn in
:n lurnn/fi eld sha ll be

len t
sto

to
red
be don e by typ ing NULL wit hou t quo
0, i.e., NU LL~ 0.
tes.
It acts as a pla ceh old er for unk now n or ina ppl
ica bl e
Null is not equ iva
values. Ma rks , DOB)
e, mys ql> INS ERT INT O Stu den t (Ro lln o , Nam e, Gen der ,
for exa mpl
'F' , NULL, NULL );
VA LU ES( l2, 'Sw ati Me hra ',
ed for the fiel ds
the exe cut ion of the abo ve com ma nd, NULL values sha ll be ins ert
After
Maries and DO B res pec tive ly.
a NUL L alwa ys eva luat es
ns unavailable oru nde flne d value.Any arithmetic expression containing
Clll:Null mea
.....
:. 'fodifring Dat a in a Tab le s in a
le or to ma ke cha nge s for som e or all of the val ues in the exis ti ng rec ord
Te modify data in a tab difi ed usi ng
UPD ATE stat em ent . The UPD ATE com man d spe cifi es the row s to be mo
lhlt, we use the usin g the SET key wor d.
lit WHERE clause and the new dat
a is wri tten into the resp ecti ve rec ord

fptu for UPDATE:


UPDATE <table_name>
=
SET <co lum nl> <va lue t>, <co lum
n2> =<Value2>,.....
WHERE <co ndi tion >;
ample, mysql> UPDATE Stu den t
Fortx
SET Ma rks = 90
WHERE Ro lln o = 8;
roll num ber is 8.
e of Marks field to9 0 for the stud ent whose
!btih(,w, statement shall cha nge the valu
(i) Upd atin g mu ltip le col um ns
col um ns a lon g
ifying the valu es jn mo re tha n one colu mn can be don e by sep ara ting the
Mod
with the new valu es usin g SET clau
se, sep ara ted by com mas .
t
For example, mysql> UPDATE Stu den
8-l l '
~ET Md rks • 7 0, O'JB& ' l9g 8-0
WHf..f!.E NdfflP. • " l' dyd l .. ,
DOB to 70
es for both the fie lds Marks and
The abov e state men t shal l chan ge the valu and
1998 11' l"e'spectiv ely for the stud ent whos e name is Payal.
' -08-

(b) Updating to NULL values


entere d as NULL u5 ing UPDATE cornnianct.
The values for the attributes in a relation can also be
For exam ple, mysql> UPDATE Stud ent
SET Mari es = NULL
WHERE Rol lno = 9;
of the field Marks to Null for the stud ent whos e ro11
The abov e state men t shall chan ge the value
num ber is 9.
(c) Upd ating usin g an expr essio n or form ula
For example, mysql> UPDATE Stud ent
SET Mar ks = Mar ks + 10
WHERE (Ro llno = 5 or Rol lno =1 0) ;
tr
of Marks by 10 for all the reco rds with Roll nurnh
The abov e state men t shall incre men t the valu e
5 or 10.
form ula
(d) Upd ating all rows usin g an expr essio n or
For example, mysql> UPDATE Stud ent
SET Mar ks = Mar ks + 10;
of Marks of all the stud ents by 10.
The abov e state men t shall incre ase the value

3. Rem ovin g Data from a Tabl e


from a table .
The DELETE state men t is used to dele te rows
Synt ax for DELETE Stat eme nt:
n>;
DELETE FROM <tab le_n ame > WHERE <con ditio
are to be dele ted.
here <tab le_n ame > is the tabl e who se reco rds

N:•ll:ilt4M~1B1:li;1
l
nal and it identifies the rows in the column thitget j
The WHERE clause in the SQL delete command is optio
rows in the table are deleted.
deleted. If we do not include the WHERE clause, all the
mysql> DELETE FROM Stud ent WHERE Rol lno
= 10;
For example,
for roll num ber 10.
The abov e state men t shall dele te the reco rd only
, Deleting all rows from the table:
To dele te all the rows from the stud ent table , the
DELETE statement will be:

mysql> DELETE FROM Stud ent;

, SQL T RU NCAT E Sta tem ent


te all the row ffiiri the table and free the sract
The SQL TRUNCATE com man d is used to dele
cont ainin g the table for reus e.
Synt ax to TRUNCATE a table :
TRUNCATE TABLE <tab le_n ame >;

- Computer Scienct wd'1 ~--" "


·
,,,pie,the ro ws from stud ent table, the state ment wlll he .
,,>
~.J I it.all .. ,~AT £ TAB LE Stu d ent ;
Jt r ·ri~u,~ l.,
fl' 111~-s~I> ,n pFLE TE a nd TRUNCATE St ,1lt•n tpn t,.,
til't\\ t'l
ent: This com man d dele tes only the rows
from the Wblc base d on the c.nncJ1t1 ,,n
.. , ,..,,i·
e ta ble If no cond ition Is spec i fied . But 1t
, .£16 State: re clau se or dele tes alJ the rows from th
ii\ 111 tht whe spac
e
e cont aini ng the table.
ff free t te all th e rows from the table and free th e
,;,t'sn°l E Statement: This com man d Is used to dele
...i1ttcAf . . g the table for reus e.
111v nta1n1n
ct CO
~ sOL QUERY PROCESSING it Now it Is time to
1.15,reatt.ng the data base , the table is created and the data i s s tore d i n . .
. h I table s to retri eve a nd view the data on the
.lfltr query proc essin g ?n t e a ready-create
d
main ly usin g the SELE CT com man d. The
ptrfo~Retrieving info rmat ion from the table s is done
mor e da taba se table s. ft is used to sele ct
sate · ECT state men t is used to fetch data from one or
sQLSELd olumns from a data base /rela tion .
ro"'S an c
.15 _1 SOL SELECT Statement
7 as proj ectio n.It is the mos t exte nsiv ely used
Stied command can perf orm sele ction as well
to retri eve a subs et of rows or colu mns from
SQLcommand. The SELECT state men t can be used
one or more table s pres ent in a data base.
L Projection
lbis capability of SQL retu rns all row s from a relat
ion with selec tive attri bute s .

~
SW:CT <col umn -nam e!> [, <col umn -nam e2>
...]
FROM <table-name>;
For example,
t;
mysql> SELECT Nam e, Gen der FROM Stu den
lesultant table: Stud ent

lliiKumar M
Oeepsingh M
AltitSharma M
llidhika Gupta F
PiyalGoel F
DlkshaSharma F
Gurs,ree,: Kaur F
~Du reja M
~~nd F
~ Mittal M
10~• •
n a set (0.0 1 sec)
l'tit ilbove c0 trs fro m th t" s tud e n t tJhl t".
:~ mma nd disp lays o nly Nam e and
~ t\k (•J means •Au-. SELECT•-■• colum ns from I rN t lOn.
\,,IQ.,. u4
t.lJ·~ illld SOL ... '"" -
To d1,pla) .tll c-olumns ,ilong wtth lhc n.•srH·rtlve row,, w<' u,tt the comm;in tl:
fll\ ,qt... '3. E.:T • FR M StU,iP!lt;
Rt-sult:ant table: Student
i!! ii kd ltt·d■cmlll;::mli?:.)itd i1@,;,3
2000-11-17 NULL
'2 RajKumM
Dffp Stngh
M
M
93
98 1996-08-22 NULL
3 AnkitSNnN M 76 2000-02-02 NULL
4 Radhika Gupta F 78 1999-12-03 NULL
5 PayalGoel F 82 1998-04-21 NULL
6 OiksN Sharma F 80 1999-12-17 NULL
7 Gurpn!e!Kaur F 65 2000-01-04 NULL
8 Akshay Dureja M 90 1997-05-05 NULL
9 Shreya Anand F 70 1999-10-08 NULL
10 Prateek Mittal M 75 2000-12-25 NULL
10 rows in a set (0.02 sec)
The above command displays all the rows of all the columns according to the column-list defined
in the table structure. The salient features of SQL SELECT statement are as follows:
► SELECT command displays the columns of the table in the same order in which they are selected
from the table.
► To retrieve all the columns in the column-list from a table using SELECT command, asterisk(') is
used and the columns are displayed in the same order in which they are stored in the table.
► All the statements (inclusive of SELECT statement) in SQL are terminated with a
semicolon (;). Use of semicolon is dependent on the version in use.

2 . Selection: Selecting Specific Rows-WHERE Cla use


This capability of SQL returns some of the rows and all the columns in the relation. Use of WHERE
clause is required when specific tuples are to be fetched or manipulated. To select all the columns
from a table, the asterisk (*) can be used.
Syntax;
SELECT <wbat_to_select>
FROM <which_table>
WHERE <conditions_to_satisfy>;
For example,
mysql> SELECT • FROM Student WHERE Gender =- 'M';
Resultant table: Student
it
1 ,..,Kumar id=.\ 1■
M 93 2000-11-17
2 OeepSingh M 98 199fr-08-22 NUU.

..
J AnkitShMmi M 76 2000--02..02 NULL
• Abtwy~ M 90 1997..()5-05 NULi.
10 Prateek Mitt.al M 75 2000-12-25
S rows la • set (0.01 sec)
The above command wall di!,,play all attributes but 1 which satisfy tht co
nd1Ul)II
in the 1tudrnt uble.
o#.
-• ~ .+ ·•. . Compul•r St:,11iu •in ~
iu ..
II JH f),u1,<"
~i \\ I •
, · . . .... T • F~OM Stud en t WHERE F<ol lno<• l3 ;
1~ :: ,,- A.
no l(•s, th.,n or cq1J .1I tr>
~·-4 t-i~''t' comm and shall displa y only those record ~ whose Roll
l!i

..,, J
· t.1ble: Stude nt
.,_~~ c·a--:.·H·,·■·mm11 MobU e no
~
1
A,f lCumar M 93 2000-11-17 NUU
DfeP Singh M 98 1996-08-22 NULL
l ~ Sharma M 76 2000-02~2 NULL
J F 78 1~12 ~3 NULL
• ~hika Gupta
F 82 1998--04.21 NULL
s p,yalGoel
Diksha Sharma F 80 1999--12-17 NULL
6 F 65 NULL
<,urpreet Kaur 2000-01--04
7
AAshay Dureja M 90 1997-05-05 NULL
1
"""5 in a set (0.02 sec)
1
query proce ssor goes throu gh
r.'hen a WHERE clause is used with a SELECT statem ent, the SQL
mt entire table one row /reco rd at a time and check s each row
to determ ine wheth er the condi tion
the co rresp o n ding row is
specified is true with respe ct to that row or not. If it evalu ates to True,
).
selected, retrieved and displa yed, else it return s an empty set (i.e., no data found
have same meani ng in SQL j
mt SOL is case-insensitive, which means keywo rds like SELECT and select
'I miements.

3 Reordering Col um ns while Displ aying Query Resul ts


to be displa yed can be chang ed
~'bile displaying the result for a query , the order of the colum ns
y purpo se a nd no actua l
according to the user's requi remen t. But this is done only for displa
(physical) rearra ngem ent of the colum ns is done.
For example,
mysql> SELEC T Name , Rol lno , DOB, Mark s FROM Stud ent;
in the chang e d order as Name
After executing the above statem ent, the colum n shall be displa yed
as the third colum n and
sh.ti be displayed as the firs t colum n, Rollno as the secon d colum n, DOB
N.r1cs as the fourth colum n respec tively.

~ dent
~ C?l:mlll : Marks

..,~ 1 2000-11-17 93
~ Stngh 2 199<H>&-22 98

~ Sh.rm. 3 2000-02-02 76

~(q j
~Gu ~ .. 1999-12-03 78
IJ
s 1998-04-21
C.-.v.. St1er"'- 6 1999-12-17 80
~..ett ~ 2000.( )1-04 65
7
~st~°"'
.. r..:
'-,.A • 1997-0S-OS 90
9 19"-lo -GI 10
..._ "4.fhl 7S
~ ~ 10
~ • •1111 lt-t (0.0Z M'C)
Dai.r..
"•11Cls.ot. - ·• - · · ·
CTM: The order in which th• columns ire displayed using the SELECT command Is In accordance with th
in which they are ,ctually stored In the table.
l' Ord
tr

4. Eliminating Duplicate/Redundant Data-DISTINCT clause


DISTINCT clause 1s used to remove duplicate rows from the res ul ts of a SELECT 'ita leme t
n It 1
used to retrieve only umque values for a column in the table. The DIST INCT keyword can b ,
e llSed
only once wi th a give n SELECT state me nt.
Syntax:
SELECT DISTINCT <column-name> from <table -nam e>;
For example,
Suppose we have adde d a new column Stream to the table student.
Resultant table: Student
limlli!-1 G§,t.iJi mml Hfflffili,i•l•Mii l■
1 Raj Kumar M 93 2000-11-17 9586774748 Science
2 Deep Singh M 98 1996-08-22 8988886577 Commerce
3 Ankit Sharma M 76 2000-02-02 NULL Science
4 Radhika Gupta F 78 1999-12-03 9818675444 Humanities
s PayalGoel F 82 1998-04-21 9845639990 Vocational
6 Diksha Sharma F 80 1999-12-17 9897666650 Humanities
7 Gurpreet Kaur F 65 2000-01-04 7560567890 Science
8 Akshay Dureja M 90 1997-05-05 9560567890 Commerce
9 Shreya Anand F 70 1999-10-08 NULL Vocational
10 Prateek Mittal M 75 2000- 12-25 9999967543 Science

-
10 rows in a set (0.02 sec)
Resultant table: Student
With refe rence to the above table, if we write
the SELECT statement as: Science
(Displays all rows wrth
mysql> SELECT Stream FROM Student ; Commerce duplicate values as well)
Science
this statement shall return all the tuples
Humanities
for field Stream from table student. It will
Vocational
return duplicate values also. Thus, in order
Humanities
to remove these duplicate values, DISTINCT
Sdenca
clause is used.
Now, we write a query for displaying the VoQtlonlf
distinct contents on t he basis of the field Science
Stream from student ta ble: 10 rows in a set (0.02 sec)
For example,
Science
my~qI> '3.i:. ! FC I DI TINCT Stream FROM onoe only
(Duplrcnte volues are
removed)
QL operators
1S 2 S with SELECT statement using WH ERE cl,rnsc, co ndill on -b,1\cd 'lllC'ry cAn hr c.Jrrwd
1 ".0 r~111 g of SQL operators:
~"lilt . fou r rypes
11 ~111g operators
·"'' ~r'I·rtirneuc
. operators
i'1 1auona1
:?tl Re I operators
1 t,og1ca
t.:l . 1operators
specia
lJl Table 7 .5: SQL Operators and their Functions
DESCRIPTION
Used In arithmetic calculations and expressions.
+, -, •, /, ~. -

_ <>
. .. .. Used in conditional expressions.

~ Used in conditional expression•

~ Checks whether an attribute value Is within a range or not.


B[TWELL/lS NOT NULL Checks whether an attribute value is NULL or not.
~ T LIKE Checks whether an attribute matches a given string pattern or not_
OTIN Checks whether an attribute value matches any value with a given list or not_
:NCT Permits only unique values. Eliminates duplicate ones. _
AGGREGATE FUNCTIONS Used with SELECT to return mathematical results/values on the basis of the
operation performed on the columns.
Returns the total number of records with non-null values for a given column.
COUNTO
MWO Returns the minimum/lowest value found in a given column.
MAXO Returns the maximum/highest value found in a given column.
9.JMO Returns the sum of all the values for a given column.
AVG() Returns the average of all the values for a given column.

(a) Arithmetic Operators


Arithmetic operators are used to perform simple arithmetic operations like addition ( + ) .
subtraction (-), multiplication (*), division (/) and modulus (%). These operators are used
with conditional expressions and for performing simple mathematical calculations. The
arithmetic operators with SELECT command are used to retrieve rows computed with or
Without reference to any table.
mysql> SELECT 5 + 10 FROM DUAL;
The above statement returns the value 15 as the result.
+-------·-·------ +
Is+ 10
+------·--·------ +
I ts
mysql>SELECT SIN(Pl() / 4), (4+1)"'5;
+-------♦---------- ♦
I SIN(PI0/4) I (4+ t)•s I
♦------------- ♦--------♦
10.101101 2s
♦----------•------------- ♦

mysql> SELECT 5 • 4 FROM DUAL;


♦-------------♦

♦--------♦

120
+------------+
mysql> SELECT 4 7 % 5 FROM DUAL;
+---------·--+
147%5
+--------------+
12
+--------------+
The modulus (%) operator returns the remainder as the result after performing the division
operation. Hence, the above statement shall return the value 2 as the output.

POINTTO REMEMBER
DUAL is the default table automatically created in MySQL It has one row with a value X and one column
'dummy' defined as varchar2(!).

Evaluating Scalar expression with SELECT statement


MySQL permits calculations on the contents of the columns and then displays the calculated
result using SELECT statement. We can write scalar expression and constant values for the
selected columns. If we are taking NULL value in the expression, It shall result in NULL only.
Along with NULL, arithmetic operators can be used while 1ffl)jl1Wng scalar expressions.
For example, mysql> SELECT Roll no, Name, Marks + ~ ~ Student;
The above command, on execution, shall increment the value lbrd the rows of the field Marks
by 10 and shall display the Rollno, Name and Marks for all the mdents, increased by 10.
Resultant table: Student
1: '·I E~CDilll•I
1 Raj Kumar 103
2 Deep Singh 108
3 Ankit Sharma 86
4 Radhika Gupta 88
5 PayalGoel 92
6 Oiksha Sharma 90
7 Gurprftt ~ur 75
I Akshay Oureja 100
9 Shreya~nd 80
10 Pr.ieek M1tt•I 85
10 row1 In a set (0.02 sec)
.- - . . ~~ -.>· ~ ~ '
. JI oper ator s
ttrlau on .
ol wh1t.h a\ u-.,·d to cor11JlcH" ~ .,
~, (ionc1I (com pans on) oper ator ls a Rl.lthemt1t1c.al symb
~
\J
::s.
1
It 15 used to com pa~ _two value s of the s.ime
to~ Jrt' used for cond ition s where two
or comp.1tihlt.> d.il.J type , C.om p,1r1•,,1n
expr essio ns c1rc requi red to be com pJrl' d with
used with WHEH E d;iu,e
Llp('r: ther, whic h resu lts In eithe r true or false. They a~
rJCh d 'b d I'ftieren t types of comp ariso n oper, Hors in SQL
'('ht following table escn es
OESClltlPTION
~ Equa lto
Grea ter than
>
Less than
Grea ter than or equa l to
<:: less than or equa l to
<>,I= Not equa l to
er in the alpha betic al sequ ence and >
For comp ari~g char acter d~ta type value s,< mean s earli
means later m the alpha betic al sequ ence .
s FROM Stud en t wher e Mark s>=9 Ci ;
Forexample, mysq l> SELE CT Roll no, Nam e, Mark
and Mark s of all the s tu dent s with mark s
The above comm and shall displ ay the Rollno, Nam e
either equal to or grea ter than 90.
Resu ltant table : Stud ent
t:%!·1 Emmll
1 Raj Kuma r 93
2 DeepSingh 98
3 Akshay Durej a 90
3 rows in a set (0.02 sec)
For example, mysq l> SELE CT * FROM Stud ent
WHERE Stre am< > 'Com merc e';
The abov e comm and shall displ ay the reco rds of
all the students who are not fro m
Commerce strea m.
Resu ltant table : Stud ent
: Mobi le_no . ' .
. _ me 164,t·MMmll lll DOB 9516774748 Scien ce
1 Raj Kumar M 93 2000-11•17
76 2000-02-02 8567490078 Scien ce
3 Ankit Sharma M
4 F 78 1999-12-03 '818675444 Huma nities
Radhika Gupta
s F 82 1998-04-21 9845639990 Vocationa l
Payal Goel
Huma nities
6 Diksha Sharma F 80 Ulllllrftlr,ll-■.. IP' 6666 50
7 F
567890 Scien ce
Gurpreet Kaur
9 F Voca tiona l
Shreya Anan d
10 M iJlll!~ 967543 Science
Pratee k Mltta l
8 rows in a set (0.02 sec)
LF.Cf s t..ttt> ment. the d JUb.c .t>
Thus, While using relati onal opera tors in a WH
one jfld com pJl"\.'S with the
Program goes throu gh the entire table cheddna
-- , _
Clll:
I... · ~ i . ,
·~,u. .. ,
· !.peclfied Ifit is true. the corre spon dJng
cond 1tion
Wh,;:,- -- -- -- --- - -- -- -- ~
---~ 'dr.1\ 1 comp aring chara ct•r, date and time
-Quo t «U1on
- ~:::. mark'
.:.:~

~.t,t,,.,. •1110 ~Ol


:. -.
. _ __ _ _ _
data Ult"8
__ _ _

..
..,__ _ _,www-,sN•.,.•••l!M11111111..a_
~~.;;;;,w-i-
,._
--=~~
das plJy, o lhl.'rw 1-.~ it b i~no tnl.

1
in

J.m,
(c-) Logical Operators
The SQL logical operators are the operators used to combine multiple conditions to nar
ow th e
data selected and displayed on the basis of the condition specified in an SQL statemen/ L
.
operators are also known as Boolean operators. The three logtcal operators in SQL are-ANOogical
OR and NOT operator. Out of these, AND and OR operators are termed as Conjunctive op ·
. ..
since these two operators combme two or more cond1t1ons. The AND and OR operators arerators
e used
to filter records based on more than one condition.
These operators provide a means to make multiple comparisons with different operators in the
same SQL statement.
CTM: ~ order of precedence for logical operators (AND, OR. NOT operator) is NOT(!), AND(&&) and OR(II).

1. AND operator
The AND operator displays~ record and returns a true value if all the conditions (usually
two conditions) specified in the WHERE clause are true.

Condition 1 Condition 2 Result (AND operation)


True True True
True False False
False True False
false False False

As shown in the table, when both condition 1 and condition 2 are true, only then the
result is true. If either of them is false, the result becomes false.
For example, to list the details of all the students who have secured more than 80 marks
and are male.
mysql> SELECT * FROM Student
WHERE Marks> 80 AND Gender= ' M';
Resultant table: student

1 Raj Kumar M 93 · Science


2 Deep Singh M 98 Commerce
8 Akshay Dureja M 90 Commerce
3 rows in a set (0.02 sec)
2. OR operator
The OR operator displays a record and returns a true
(usually two conditions) specified in the WHBRB CUllll4tl
Condition 1 Condition 2
True True
Tr~ Falw
Falw True
Fal~ fal\e

As shown In the table, when ei ther , the rtsult 1s trut -


If both of t11~m ilre fal,e, then only the
all th e stud ent~ w ho a re in
for exam ple, to displ ay the roll numb er, name and strea m of
either Scien ce or Comm erce strea m.
nt Wf-lEP E
mysql> SELE CT Roll no, Name, Strea m FROM Stud 8
Strea m= 'Scie nce' OR Strea m= ' Comm erce ';

Resultant table: Stud ent


Strea m
trbiffl·• Name
Raj Kumar Science
1
2 Deep Singh Commerce
3 Ankit Sharma Science
Gurpreet Kaur Science
7
8 Aksha y Dureja Commerce
1o Prateek Mittal Science
6 rows in a set (0.02 sec)
3. NOT oper ator
NOT opera tor is also terme d as a negat ion opera tor. Unlik
e the other two opera tors, this
it as the resul t. It retur ns a
opera tor takes only one cond ition and gives the rever se of
false value if the cond ition holds true and vice versa .
Condition 1 Result (NOT opera tion)
True False
False True
t is false. If the cond ition is
As show n in the table , when the condi tion is true, the resul
false, then the resul t becom es true.
nts who are not in the
For exam ple, to displ ay the name and marks of all the stude
vocational strea m.
mysql> SELE CT Name , Mark s FROM Stud ent
WHERE NOT (Stre am= 'Voc atio nal' );
Resultant table: Stud ent
Name Mark s
Raj Kumar 93
Deep Singh 98
Ankit Sharma 76
Radhika Gupta 78
Diksha Sharma 80
Gurpreet Kaur 65
Akshay Oureja 90
Prateek Mlttal 75
8 rows In a set (0.02 sec)
(d) S
PeciaJ Oper ators
Apart fr r. there are some specl JI operJ tors
in SQ om several stand ard Ii brary funct ions discu ssed aillle
L th at perfo rm some specific funct ions.
Syntax for LIKE:
SELECT <column_name(s)>
FROM <table_name>
WHERE <column_name> LIKE <pattern>;
For example,
mysql> SELECT • FROM Stude nt WHERE Name L IKE " D1, " ;

Resultant table: Student


■;ftijj,j.4 Name i&J,i-1 iii.Vfoii •Mi Mtiiutm&Pa
2 Deep Singh M 98 1996-08-22 8988886577 Commerce
6 Diksha Sharma F 80 1999-12-17 9897666650 Humanities

2 rows in a set (0.02 sec)


The above command shall display those records where the name begins with
character 'D'.
mysql> SELECT * FROM Student WHERE Name LIKE " %a";

■;ffljj ,f. $ffiffil) ,i·• ~


3 Ankit Sharma M 76 NULL Science
4 Radhika Gupta F 78 9818675444 Humanities
6 Diksha Sharma F 80 9897666650 Humanities
8 Akshay Dureja M 90 9560567890 Commeia!
4 rows in a set (0.02 sec)

The above command shall display the records for those students whose name ends
with letter 'a'.
mysql> SELECT * FROM Student WHERE Name LIKE •tsel";
Resultant table: Student
■;fbjj,\,j Name Gender Marks ·,. no Stream
2 Deep Singh Commerce
s Payat Goel F •••I Vocational
7 Gurpreet Kaur F Science
8 Akshay Dureja M : •I Commerce
9 Shreya Anand F Vocational
10 Prateek Mittal M Science
6 rows in a set (0.02 sec)

As the resul tant table shows, the abo ords of all the students
whose name contains character 'e'

mysql> SELECT " From Studen

)(II ,,...,..r
puter Science with python-
tant table : Stud ent
~esu l

~ Dffp Singh 1996-08-22


•., in a set (0.02 sec)
1 ron
n tc, whos t' N.ime
This comm and .shall displa y the Rollno , Name and DOB of a ll the studl•
ins the letter 'e' at the secon d place.
con ta
NOT LIKE
s the rows th.it
The NOT LIKE opera tor work s oppos ite to LIKE opera tor. It return
do not match the specif ied patter n.

For example,
Stud e'lt 1i:1.EFC: '::i....,.'?
mysql > SELECT Rolln o, Name , Gend er, Mark s, DOB FROM
NOT LIKE " %r __ ";

Resul tant table : Stude nt


tMUh-1 G4,f.t4Mif.M
· 93 200CH 1-17
1 Raj Kumar M
Deep Singh M 98 1996-0 8-22
2
4 Radhika Gupta F 78 1999-1 2-03

5 Payal Goel F 82 1998-04-21


Gurpre et Kaur F 65 2000-01-()4
7
8 Akshay Dureja M 90 1997-05-05

9 Shreya Anand F 70 1999-1 0-08

10 Prateek Mittal M 75 2000-1 2-25

8 rows in a set (0.02 sec)


DOB of all the stude nts
This comm and shall displa y the Rollno, Name , Gende r, Marks and
on.
whose Name does not conta in the letter 'r' from the third-last positi

7.15.3 Comments in SQL


Acomment is a text which is ignor ed by the SQL comp iler and is
not execu ted at alJ. It is give n
for documentation purpo se only. A comm ent usuall y descr ibes
the purpose of the statem ent given
W!thin an application.

~LComments are used to under stand the functi onalit y of


the progr am witho ut looki ng into it .
statem ent and how it wo r ks.
~ comments give us an idea about what is writte n in the given SQL
c..n :mrnents can make an applic ation or code easier to read as well
as to maint ain. A comm e nt
e nt. Comm t.>nts
~ b P~aced betwe en any keyw ords, param eters or punct uation marlraJn a statem
e either . I
S<i sing e-line comm ents or multip le-lin e com .....,
Jl or M S
• Y QL suppo rts three comm ent styles :
Coinrnents b
line eginn ing with -- (folfo wed a a., lines im.tll'att.> a sang lt.~
cornrn ent In SQL statem ents. These sin ically used to show the
corn
txpl-
rnents a t t h e start and end of a progr am. this comm t•nt ty pe to
c11n th n l"n<l s with o1 Ian~ b rt<..i k.
e ow of progr am. Thls text canno t e


''ti, «:.it,,,
11
:.e " d SOL
-------
r Comments be&tnnln& with I: The comments begin with'#' symbol followed by the text to be
displayed for the user's Information. This text unnot extend to a new lln e and end s With a
hne break.
-, Comments beginning with r: Multi-line comments begin_wit~ a slash and an asterisk r;-}
followN by the text of the comment This text can span multiple lines. The comment end~ With
an asterisk and a slash C-/). The opening and term inating characters need not be separatt d
fro m the text by a space or a line break.
For example,
mysql> SELECT l<ollno, Name, Stream
-> /• This statement shall display the recor ds of all those stud~nts
who are in science stream and have secured mar k s mo r e than 75 . .. /
-> FROM Student t student table in use
- > WHERE Stream= , Science' and Marks> 7 5 ; --condi tio n f o r selec t ion

7.16 SOL ALIASES


SQL aliases are used to give an alternate name, i.e., a temporary name, to a database table or a
column in a table. We can rename a table or a column temporarily by giving another name called
alias name which leads to a temporary change (renaming) and does not change the actual name
in the database.
Aliases can be used when
• more than one table is involved in a query.
• functions are used in the query.
• column names are big or not very readable.
• two or more columns are combined together.
Using column alias name, we can give different name(s) to column(s) for display (output) purpose
only. They are created to make column names more readable. SQL aliases can be used both for
tables as well as for columns.
• COLUMN ALIASES are used to make column headings in the query result set easier to read.
• TABLE ALIASES are used to shorten a table name by giving an~ alternate name, making it
easier to read or when performing a self-join (i.e., listing the table more than once in
the FROM clause).
Syntax for table alias:
SELECT <columnnamel>, <columnname2>-
FROM <table_name> AS <alias_name>
WHERE (<condition>];
Syntax for column alias:
SELECT <column-name> AS <"alias_name•>
FROM <table..J13me>
WHERE (<condition>);
~• keyword is used to assjgn alias name to a

mpuler Sc11nc:t •1111 ..........


ryu-•·
111
v111plt,

7
~,, . student
r,blt'• ,f h I r
mysql> SELECT Name AS " s t ur:lt>n t n "'"' ", fi{)!:I r,. ,, " I,.., , ,.. r ~"

~ ;0()()-,-1·1~ FROM StudAnt1 ~ •

a,.,,,
-fff Sin9h
1996-08-22
2()()()--02-02 AIIH name for fields, Name and DOB

~Shi""'
Gupta
1999-12-03
,' 1998-04-21
_.,1ue,el
,.... 1999-12-17
~Sharma
2000-01-04
~Ka~r
1997-05-05
,dll'JoureJ<l
1999-10-08
~~
,_ek Mittal 200()-12-25
--. in a set (0.02 sec)
10 ,v.. -
► AliaS name can be given to a mathematical expression also:
For example,
mysql> SELECT 2 2 / 7 AS PI; Output: +------------+
Pl
+------------+
I 3.1429 I
+------------+

N>lfTS TO REMEMBER
~
I
fthe alias- name contains spaces, we must enclose it in quotes.
,. kisacceptable to use spaces when we are aliasing a column name. However, it Is not generally a good practice
t> use spaces when we are aliasing a table name.
.. The aliu_name is only valid within the scope of the SQL statement.

7.17 PUTTING TEXT IN THE QUERY OUTPUT


1 0rd
er to get an organized output from a SELECT query, we can include some user-defin ed
columns at runtime. These columns are displayed with a valid text, symbols and comments in the
Dlltplut only. These included columns will appear as column heads along with the contents for that
COwnn.
nus rnake h
st e query output more presentab le by giving a formatted output.
l'-or~m l • B
Pe, rnysql> SELECT Rollno, Name, 'was born

FROM Student; lo be displayed
l'ht ibo\'e co n• with every rt-cord (tupl~)
• 0itt..bJ rnmand, on execution , shall display the tat
e.


Resultant table: Student
■;bii.\-1 Name was born on
1 Raj Kumar was born on 2000-11 -17
2 Deep Singh wasbomon 1996-08-22
3 Anklt Sharma wasbomon 2000-02-02
4 Radhika Gupta was bomon 1999-12-03
s PayalGoel wasbom on 1998-04-21
6 Diksha Sharma was born on 1999-12-17
7 Gurpreet Kaur was born on 2000-01-04
8 Akshay Oureja was bomon 1997-05-05
9 Shreya Anand was born on 1999-10-08
1o Prateek Mittal was born on 2000-12-25
10 rows in a set (0.02 sec)

7.18 SORTING IN SOL-ORDER BY


The SQL ORDER BY clause is used to sort the data in ascending or descending order based on
one or more columns. The ORDER BY keyword is used to sort the result-set by one or more
fields in a table. This clause sorts the records in ascending order (ASC) by default. Therefore,
in order to sort the records in descending order, DESC keyword is to be used. Sorting using
ORDER BY clause can be done on multiple columns, separated by comma.
Syntax for ORDER BY clause:
SELECT <column-list> FROM <table_name> [WHERE <condition> ] ORDER BY <column_
name> [ASC I DESC);
Here, WHERE clause is optiol)al.
For example, 1itbil,11 i Na m e
•MflM
8 9shay Dureja 90
► To display the roll number, name and marks of students on 3 Ankit Sharma 76
the basis of their marks in the ascending order. 2 DeepSingh 98
mysql> SELECT Ro llno , Name, Marks FROM 6 Dlksha Sharma 80
Studen t ORDER BY Name ; 7 Gurpreet Kaur 6S
► To display the roll number, name and marks of all the students S Payal Goel 82
in the descending order of their marks and ascending order teek Mittal 7S
of their names. hika Gupta 78
mysql> SELECT Rol l no , Name , Marks FROM Student 93
ORDER BY Ma rk s DESC, Name; reya Anand 70

Sorting on Column Alias


If a column alias Is defined for a column, it can be used for . . . .ng rows in ascending or
desce nding order using ORDER BY clause. -;-
For example,
ScLECT Ro l l no , Name , Mar ks AS Mar ks obtained
f P0 M Stude n t "- -
0Pt;E:R ~ Y Ma rk ~_o bt <S ine d ;---~--rAl laellMle
-GAE GATE FUNCTIONS
• ,g· Au " r h,1\·e stu d ll"d a h out singe-row
· I I
1 "
runrtlon~ which work on ., , 111 1:lr v,11 111• \ C} • -• •
1111 11
• "' rnulttplC'• row func-Uons which work on multiplr vc1 luPs. So, w r c,ttl ., p pl y t,f-.1 r-. CT <1 < r y
A..," ,Je",ur of records rathl"r than the entire tt1hle. Th<>r<'fore tht>se fun , tton c; ,H <' r ,Jll t•d Aggn·g .,r ,•
I f

-1 • ►n r Group functions .
. ,.,~ ,nS 0
....,1

• _ l)v, the following aggregate functions are applied on group~ as dcscrihc d twlow :
. -.,,J .
',I,
Table 7 .6: Aggregate Functions In SQL

.-..c
~
:! ■ MAXO
Oncription/Purp os. t~.,_ .
Returns the maximum/highest value among the values in the given column/expressH>O .
_

MINO Returns the minimum/lowest value among the values In the given column.' expression.
2
suMO Returns the sum of the values under the specified column/expression.
3
, AVGO Returns the average of the values under the specified column/expression .
Returns the total number of values/records under the specified column/expressio n.
s couNTO
.. •der a table Employee (employee code, employee
'
name, salary, job and city) with the fo!Jow ing
..,.,nsi
~Jcture:

~ Ritu Jain mmll City

El 5000 Manager Delhi


E2 Vik.as Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
e. Leena Arora 7200 Manager Bengaluru
ES Shikha Sharma 8000 Accountant Kanpur

• M.\X()
MAX() function is used to find the highest value among the given set of values of any column or
expression based on the column. MAX() function takes one argument which can be either a column
name or any valid expression involving a particular column from the table.
For example,
mysql> SELECT MAX (Salary) FROM EMPLOYEE;
Output:
♦----------- +

! MAX(Salary)I
------------- ♦
181.JtJO
♦--·-···-----•
T~ui c.1,mmand, on execution, shall return the maximum value from dle~c1fied rnlumn (SJl..u-y)
,,. th h

. ~;\()
it U It Employee, which is 8000 .

"11~1, srt of vJlul'-; of .rny <.ulumn or


l une11un •~ u ~~d to find th~ lowest vJlu~ .imon1 tht! giv~n
t->r.ir t'~
, '>ti,n t.,•~t-d on th~ ,olumn. MIN() I unction takes. onr aracumttnt wha,·h cJtl ht• t' lthc:-1 .t rnlumn
411 1lit c, -
r ,my v• lid t-JC pr~\lon 111volv1n~ ;,t pJrtil:ulJr column trum thtt whit'

For example,
mysql> SELECT MIN (Salary) FROM EMPLOYEE;
Output:
+--------------+
I MIN(Salary) I
+-------------+
I 4500
+--------------+
This command, on execution, shall return the minimum value from the specified column (Salary)
of the table Employee, which is 4500.

• SUM()
SUM() function is used to find the total value of any column or expression based on a column.
It accepts the entire range of values as an argument, which is to be summed up on the basis of
a particular column, or an expression containing that column name. The SUM() function always
takes argument of integer type only. Sums of String and Date type data are not defined.
For example,
mysql> SELECT SUM (Salary) FROM EMPLOYEE;
Output:
+----------------+
I SUM(Salary) I
+-------------+
130700
+---------------+
This command, on execution, shall return the total of the salaries of all the employees from the
specified column (Salary) of the table Employee, which is 30700.

• AVGQ
AVG() function is used to find the average value of any column or expresston based on a column.
Like sumQ, it also accepts the entire range of values of a particular column to be taken average of,
or even a valid expression based on this column name. Like SUMO function, the AVGQ function
always takes argument of integer type only. Average of String and Date type data is not defined.
For example,

-
mysql> SELECT AVG (Salary) FROM EMPLOYEE;
Output: OM·fi
♦ ----·---------+ El Delhi
I AVG(Salary) I E2 Jaipur
£3 Clerk 1<.1npur
j 6166.66 E4 Manager Beng.tluru
ES Accountant K,npur
ThiJ command. on execution, <,h,111 rl'tu rn the aw,...
spt>cif1cd column (Si!IJry) of tlw t.1ble Em ployee, whJch lsM"llalll
all the l'mployees from (ht
,-~
' , f
, -
n -Jo ;.i 1s .!Sea :o co _n
.. r ~ _'"' - - ·· n ~
t: e n u...- b""r 0 ,
. .., " ' \ a1U ~ 5
a col umn COU"T ) i u- c· on t~b( C
lii
1

. . . ca ..... e o. ·• c_ .. ;,r.-:
• ..
- 1,: o ~-n
,_ .,
b
• a r , p-e , , 1011 a, ed o n a column or an a•-ten'-~
'· (· J
-~- :~c J ~ --r.- ~: t ,s a ~O,.i r'ln r.arr.e or an exore s~ r: '
bc1 ,;;L-d on t..,t. colu mn C0UNTO r et urns th e
~--:- .. : r,0 "'-> L ~L \a..:..:~s ,n ~at C'l;U"ln. If tl-e a ~gu me m 1s a'-~t. n:c.k ( ~). th en COUNT() counw
__ 1
. :. >' n ... -u b"'r
~
o: recon::s, :-ow5 sa ._,S., 1" CI th,e co n d 1,10
~ •~ •• :::,
. n a 1o P. ; \ \l : h NULL
. ,·alues. 11, a-,:.· m,~h e

: -~-=-;.::
- ~~ > ~~ =-~ =-=-

~ut

.- ,-·-J
- - - \, I; ....

--------- +

-----
-.:..5::-:-::-.c..."1.0, on execution. shall r e turn the total number of records in the table Employee, which

- -- _____ ,
7 1.r::- - , · ::-::- ..

0:nput

-- ----+
4
·- -------------------+
- ~ ::a-::.:~ar.a on execution, shaJI return th e total n umber of r-ecords o n the basis of city with no
.:-;•.:2.:e •.-a,...:e5, Le., Kanpur is counted o nly once; the second occurrence 1s ignored by MySQL
--=-:::::.:.sc o; d-:e DISTI.'.\CT clause. Thus, the output will be 4 instead of 5.
· .1 ~reg.ak Functi ons & ~ ULL \'al ues
C --s.::e:- the i:able Employee gn:en in t.he pre\-i ou.s sectio n \\i th NULL values against the Salary
c., d
:: ·c:- some employees.
'. -.t 0f tlie aggregate functions takes NU LL into co nsid eratio n . NU LL \'alu es arc simply ignored
C:- 2 r.1e e1g__g:-egate fu ncnons as clearly show n in the examples given below:
!-\..o, > :_.-__ ~
'Jy•;,w•. 18 50 0
q· q. >
0 ~·p _ .;-.;oo ( ~ULL \ a lues ar e not co nstder~d.)

•• - uJ 0
( ~. ULL , ·3J ue '> a re ign o r ed.)

0 ··1
' .• i
( ~ ULL \ il u,_•<, 1 n • ignort:'d }
. qi ;
• I
~·P. t r, 166 1 ,)
( It \'\'lll bt• l ,,ltul.1h d cJ'i 1 P'" 0 0 / I. , , . ~um / t >t , I no l• I , L'<1 ) d , \ hh h a:'t.•
i a lh: r 1gnorin~ NULL va lut, l
my-sql> $ELECT COUNT ( • l FROM EmployPI'? i
Output S (NULL value counted)
ffl)'Sql> SELECT COUNT (Ecode ) FROM Empl o y ef' ;
Output 5 {No NULL value exists In the colu mn Ecode.)

mysql> SELECT COUNT (Salary ) FROM Empl oyee ;


Output: 3 (NULL values are ignored while counti ng the tota l number of
records on the basis of Salary. )

7.20 GROUP BY
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records
and grQup the results by one or more columns. It groups the rows on the basis of the values present
in one of the columns and then the aggregate functions are applied on any column of these groups
to obtain the result of the query.
This clause can be explained with reference to the table Student; the rows can be divided into
four groups on the basis of the column Stream. First group of rows belongs to "Science" stream,
second to •commerce" stream, the third group belongs to "Humanities" stream and the fourth to
•vocational" stream. Thus, by using GROUP BY clause, the rows can be divided on the basis of the
stream column.
Syntax for the GROUP BY clause is:
SELECT <columnt, column2, ...column_n>, <aggregate_function (expression) >
FROM <tables>
WHERE <conditions>
GROUP BY <columnt>, <column2>, ... <column_n>;
Here, column_names must include the columns on the basis of which grouping is to be done.
aggregateJunction can be a function such as sum(), count(), max(), min(), avg(), etc.
For example, to display the name, stream, marks I number of students who have
secured more than 90 marks according to their
mysql> SELECT Name, r of students"
FROM Student
~;HERE Marks >90

GROUP BY Stre

Res tant ta

,_.., Kum,r Sdencr


Offp $tngh Commf'rct 2
·• 2 row• In a ut (0.02 ~er)

7.21 HAVING CLAU SE


The HAVING cl.-u ..r 1-. u, c·J 111 comb& UP UY dju,~ It l Jn ht u\rd 1n , SELEl""f
statrmrnt to f1h1·r tilt' r 1· 1011.h by 1 wh1d1 .a GROUP BY r l'lurn\.
. ~-- 1'; H_~\ 1, c d.h '- t' ,, 1th GR('l 1' m .. 111 0,· il[!!;l l l,;Hl fun llJll l h
.- ~ ~ :- "'.:' ...
1
LtJ tv'lJ .,(,:1. Th . ..., h\ 1.Ju,1. th1. .1,!.:r1.:gtlh. lun11 1on, trit nc,t dln1,, l d 1
1"

: ' h \ ', h!: "E u 3 l..'C .J S It :, C\ a.lua~Ld (IO J ,,n~le r('I\\ \\ ht'rc h the ;tggr g l lt.: rune Il l 11
"· _ , a-c..:o 0: r1.1 \\<-.
, :. .; _, • =-
• _, J;_;reg.ire_ tunctto n •~ to be us ed after the FROM clause in a SELECT comm,,1nd ,hl.'n
3 1
, - :- t he \\ HE RE cla use. HA\ I NG cl au se should be used
J .._"' -- C""

· - . for HA\'ING clause:


,,-uca~
t .
Cf .::columnl>, <column2> , ... <column_n>, <aggregate_ function (expression )>
,'it .::tables>
' ondition / predicates>
;!£Rf <C
- ollP BY (<colu mn 1 , column2 , ... column_n]
·G (<condition l ... condition_n > J;
~\1\

Stream Tot.I Marks


Science 151
Commerce 0
Humanities 158
Vocational 152

:::c given outpu t, the sum(Marks) for Commerce Stream is O s ince none of the values for field
:::ks ,n the Co mmerce Strea m are less than 85.
1
· SELECT statement can contain only t hose attributes which are already present in the GROUP BY clause

22 AGGREGATE FUNCTIONS AND CONDITIONS ON GROUPS (HAVING CLAUSE)


~ n:a, use any cond ition on group, if req uired. HAV ING <condition> cla us e is used to apply- ,1
, r1 , I
~ on on a group.

mysql> -· .:.C:" Jc.. c , S'J:~ (Salary) FROY! EMPLO YE E GROUP BY Job HA\ IN..;
: - ·,: '': "" : .Jr/) >-= 8 0 0 0 ;
my~ql.,. :. ,...T J~b , ~V-i( S.dary ) FR o •,i FMPI OYE!:: GROUP BY Jol HAVING
-_, :..,~-ar:y ) >-, rv ;
rny•ql~ IIA 1:!
t, , 1 ( Jl ,1rJJ I•W'M E:~rLr1YF:F CEO'JP hY ,J l
rn,sql.>

r11;,,q1~
1
M( d l i r './ ) FF<' :-~ ~ · r '. l , i' f } I

. .
,

f I ✓ ' ., ( ) .

\' Pr'R£. \S •1 \\ ING
WHERE clause works in respect to the whole table but HAVING cl,wse works on Group onl
\\'HER_E and HAVING both are used, then WHERE will be executed first. Wh~re ls used top ~;~
cond1t1on on indi,·idual row of a table whereas HAVING is used to put a condition on an individual
group formed by GROUP BY clause in a SELECT statement.
Aggregate Functions and Group (GROUP BY Clause): Other Combinations
Consider the following table Employee with NULL values against the Salary field for some employees:
Employee

•ii+ti
El Ritu Jain
:::: - -
NULL Manager Delhi
E2 Vikas Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
E4 Leena Arora NULL Manager Bengaluru
ES Shikha Sharma 8000 Accountant Kanpur

None of the aggregate functions takes NULL into consideration. NULL values are simply ignored
by all the aggregate functions as clearly shown in the examples given below.
An aggregate function may be applied on a column with DISTINCT or* (ALL) symbol. If nothing is
given, ALL scope is assumed.
► Using sum (<Column>)
This function returns the sum of values in the given column or
mysql> SELECT SUM(Salary) FROM Employe e;
mysql> SELECT SUM (DISTINCT Sala r y) FROM Emp
mysql> SELECT SUM (Sa lary ) FROM Employee W
mysql> SELECT City, SUM (Salary) FROM
Ci ty= ' Kanpur';
mysql> SELECT Job, SUM (Salary) FROM
► Using min (<Column>)
This function returns the Minimum value i
mysql> SELECT MIN (Salary) FROM
mysql> SELECT City, MIN (Sal ary) VING
Ci ty= 'Kanpur';
mysql> SELECT J ob , MIN (Salary
, Using max (<Column>)
This function returns the Maxi
mysql> SELECT MAX (Sa lar
mysql> SELECT MAX (Sal
mysql> SELECT Cit y, t ,..1 t y HAVING

, Using avg ( <Col um


This function retur
mysql> SELECT

• -· Coriipuler Sc.we~ w,rh Pyrhvrt- l


1
n:, <• Column>)
"' ~-ms t er. mbe.r

- "1 s:L J::NS


..~. J.\ : 0 ...5 e .s used to c~mbme rol\-s fromor more tables, based or. a common field
tl\1>

~ - ~et:. e ::;ue?ing tor a Jorn. more than one table 1s considered m FROM clause. Tne
\\-t;
• § fc::JJ'i o, rnmbm mg data from multiple tables
is called a JOIN.
a physical
~ 2Ju7rt ~ara from t\\"O or even more than two related tables by performing either
x~ -;.zl to=- on the ::ables using WHERE dause.
usmg the
, ~ Car: ~ produc t ~itich make all possible combmations of rupJes. While
\\'!thin FROM clause.
:..J-5= c! 5Q!... \~ e spea.fy conditions on the related attributes of two rabies
~- ~~ ~ a:mlmte 15 the primary key in one table and foreign key in another rable.
~~:::S Q:. j::>ir:s are as foUows:
2. Equi Join

·:.ts:2.n Produc t (Cross Product)


t is a b1:-:ary
nit ~.w product lS also termed as cross product or cross-Jotn. The Cartesian produc
is the sum of the degrees o:-
~~ ~:: ts rieno:ed by ( x). The degree of the new relation formed
rw:l!>n.s on which Cartesian product is performed. The number of tuples in the new relation
1s
is performed.
_:z wilie prod ..ct of the number of tuples of the two rabies on which Cartesian product

4 =: 2 3} ano B=ta b,c}, find Ax B. C=-.xB

A 8

Urtt"~ia<' froo-t fo, A ii< B


(.olwMs after urtesl:an Product ,. I~ 1 • '2
aownftft C11tesun Product 3d ., 9

Table: studen t Table: games

1,t!& A-= - 10 Fas$ • •


1 Rahln
2 J,y1 11 l.-n . . .
l y..,..
Cartesian product for student • games: student )( Rc1rne,
my.. ql> Sr.LE.CT Ndme , gn ,lme rROM Student , q ,HTlf", ; •7-Pit11iri
+.«
ThPrrfore, a C.1rtrslan product ,~ formed whim no join conditio ns exist or Rohan Footbdll

are in\'alid. When we perform Cartesian product between two tables, all th e Jaya Footb.ill
rows in the first table are joined to all the rows In the second table. Using Teena Footb.111
Cartrs1an product operation results in a large number of rows as the output, Rohan Lawn Tenn,s
so it is seldom used. Jaya lawn Tennis
Teena lawn Tennis
Equl Join
An Equi Join is a simple SQL join condition that uses the equal to sign ( =) as a comparison operator for
defining a relationship between two tables on the basis of a common field, i.e., primary key and foreign key.
Syntax for Equi Join:
SELECT <columnt>, <column2>,....
FROM <tablet>, <table2>
WHERE <tablet. Primary key column> = <table2.foreign key column>;
For example,
Table: Student Table: Fees
■;twi,i·- N~me
1 Rohan 4 4500
2 Jaya 2 5500
3 Teena 3 5000
Resultant Table
4 Diksha

mysql> SELECT A.Rollno , A.Name , B. Fee FROM


•@Ihm llmtfi!~idilll
2 Jaya 5500
Student A, Fees B 3 Teena 5000
WHERE A.Rollno = B.Rollno; 4 Diksha 4500

In the given SELECT statement, A and B are the alias names (alternate names) for the tables
student and fees respectively. So, we can always use alternate name in place of primary name for
the two tables to be joined. Equi joins are further classified as:
1. Inner Join 2. Outer Join
1. Inner Join/Intersection: The Inner Join is a classification of equi join where either of the
equivalent queries gives the intersection of two tables, i.e., it returns the rows which are common
m both tables.
mysql> SELECT A . Rollno , A. Name, B. Fee FROM Student 'A, F ees B
WHE~E A. Rollno = B.Rollno ORDER BY A.Rollno;
Thu~, the output for the given command will be:
INNER JOIN
Resultant Table
Rollno , ,...,..
mlll
2 Myi 5500
table 1
3 Tfffli S000
4 Oiklhl 4500
J row• In a 1et (0.00 src)

You might also like