Relational Database and SQL Pt.2
Relational Database and SQL Pt.2
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~
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
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:
~
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.
..
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.
~ 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
-
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.
♦--------♦
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(!).
..
..,__ _ _,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.
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
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'
)(II ,,...,..r
puter Science with python-
tant table : Stud ent
~esu l
For example,
Stud e'lt 1i:1.EFC: '::i....,.'?
mysql > SELECT Rolln o, Name , Gend er, Mark s, DOB FROM
NOT LIKE " %r __ ";
•
''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
~,, . student
r,blt'• ,f h I r
mysql> SELECT Name AS " s t ur:lt>n t n "'"' ", fi{)!:I r,. ,, " I,.., , ,.. r ~"
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.
•
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)
-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:
• 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 .
• 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.)
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
: ' 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""
:::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
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
~ - ~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
A 8
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
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)