0% found this document useful (0 votes)
75 views20 pages

Chapter 14 More On SQL

This document provides details about ordering records in SQL using the ORDER BY clause. It explains that the ORDER BY clause allows you to sort the results of a SELECT statement by one or more columns. Without the ORDER BY clause, the results are returned in an undefined order. The ORDER BY clause can specify ascending or descending order using the ASC and DESC keywords. By default, it orders results in ascending order if no keyword is specified. An example is provided to demonstrate ordering records in a table by the marks column.

Uploaded by

abc9999999999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
75 views20 pages

Chapter 14 More On SQL

This document provides details about ordering records in SQL using the ORDER BY clause. It explains that the ORDER BY clause allows you to sort the results of a SELECT statement by one or more columns. Without the ORDER BY clause, the results are returned in an undefined order. The ORDER BY clause can specify ascending or descending order using the ASC and DESC keywords. By default, it orders results in ascending order if no keyword is specified. An example is provided to demonstrate ordering records in a table by the marks column.

Uploaded by

abc9999999999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Mo re on

SQL

ii
l4 .1 Introduction
14.2 Ordering R ec or

aa
14 .3 Aggregate Fu nc
14.4 Type s of SQ L
14.5 Grouping Re su
ds in R es ult- Ord er
tio ns
Fu nc tio ns
lt - G R O U P BY
by Cl ause
dh
14.l INTRODUCTION
You have w or ke d w
it h ba si c SQ L co m
This ch ap te r w il l ta m an ds in yo ur pr ev
lk ab ou t so m e SQ L io us class an d us ed
to di sp la y gr ou ps co m m an ds in de ta ils da ta ba se M yS Q l
of re co rd s, su m m . After this ch ap te r, yo
records. ar y of gr ou ps of re u shall be ablt
co rd s an d display se
lected gr ou ps o.
le t us be gi n w ith ou
pa

r di sc us si on on ho w
yo u ca n or de r record
s of a table using ORD
14 2 ER BY clause.
· ORDER ING RECOR
DS IN RESULT - O
RD ER BY CLAUSE
~l th ou gh yo u ha ve
re ad ab ou t O R D E
c ass, he re w e ar e co R BY cl au se of SQL
ve ri ng it ag ai n in SELECT st at em en t in
a de yo ur pr ev io us
14.2 l ta il ed m an ne r.
. Recalling SQL SE
Th LECT ORDER BY C
u e s
la us e
re ul t se
.i. 1owev . t ge ne ra te d by th e SQ L SELECT st t · ot
SE at em en is n or de re d in any form by
er, if yo u w an t to
so rt or or de r th e re lt t yo u can us e th ORDER BY clause deof
fault.
L E ct st at em en t as su se ' e SQL
pe r fo ll ow in g fo rm
SELECT <comma se at :
pa ra te d se le ct
[WHERE li s t> FROM <t ab le
o · . >
<c on d1 .t1 .o n> ]
RDER BY <f ie ld na
m e> [A SC IDESC sc lD ES C] , ... ] ;
] [, <f ie ld na m e>
[A
458 COMPUTER SCIENCE WITH PYT
H01 ~
1.,

Keywords ASC and DESC denote the order - ASC stands for ascending and the DEsc
for descending. If you do not specify any order keyword ASC or DESC, then by defa st'111 clc;
ORDER BY clause sorts the result set in ascending order. u t, th~
For example, consider the table Data having records as shown below :
+-- --- -- - -+- -- - - -- -- -+-- -- - ----- + -- --- - -+ - - --- - -- -- - +
I rollno I name I marks I grade I section
+-- ---- -- - + - --- - ---- - +- -- - -- - -- -+-------+---- ------ -+
101 Ruhani 76.80 I A I A

102 George 71. 2 0 I B I A

103 Simran 81. 2 0 I A I B

104 Ali 61. 2 0 I B I C


105 Kushal 51. 6 0 I C I C

ii
106 Arsiya 91.60 A+ I B

107 Raunaq 32.50 I F I B

108 Meera 97.20 A+ I B


109 Amaa l 57.20 I C I B

aa
111
112
113
115
11 7
118
Simran
Adam
Gurnoor
Rabiya
Rahil
Neha
66.00
74.20
93.50
72.50
32 . 00
59.50
I F
I C
I B
I B
I A+
I B
I
I B
I
I C
I A
I A
C

+ - -- -- - --- +--- - --- -- -+ -- - --- -- -- +- - ---- - +- - - - - ------ +

Now the statement


dh
mysql> SELECT* FROM data
- > ORDER BY marks;
will produce result set with marks arranged in ascending order as we did not specify ASC
keyword explicitly, i.e.,

+--- -- ----+--- - ------+- - --- - - - - - +- - -----+- - - - --- -- - - +


I rollno I name I marks I grade section
pa

+ - -- - - - ---+------- - - - +------ - -- - + - - - ----+------ -- - - -+


I 117 Rahil 32.00 I F I c
I 107 Raunaq 32.50 I F I B
I 105 Kushal 51.60 I c I c
109 Amaal 57.20 I C I B
118 Neha 59.50 I C A
104 Ali 61.20 I B C
111 Simran 66.00 I B I A
102 George 71. 2 0 I B I A
115 Rabiya 72.50 I B I B
112 Adam 74.20 I B I c
101 Ruhani 76.80 I A I A
103 Simran 81.20 I A I B
106 Arsiya 91.60 I A+ I B
113 Gurnoor 93.50 A+ f B
108 Meera 97.20 A+ I B
I
+---------+----------+-- - -------+- - -----+-- -- ---- - --+
15 ROWS IN SET (0.01 S EC)
rhe above SQL statement.1S eq ·
specified. uivalent t 0 Stat
459 ~
mysql> SELECT * FR OM d t einent sh own b
-> ORDER BY marks Aa a elow wh ere ASC
. SC; ..-- - - Th· word is explicitly
is stat
1 .2.2 0 rdenng Data on MuirIp Ie C I above b/ment Wil[ also
cause Ase produce th
4 To orderbthe result set on O urnns Order is taken; same result as
J muJij 1 Y defa,11.
oRDER y cause along With Pe column
the desir s, You c
SELECT ed sort Order,~z.e.,specify
as .. the multiple . col umn names in

ORDER BY <fieldnamel> [A
SC/DESCJ [ .
for example, the following t ., <fleldname1> [ASC/
s atem DESCJ
and then on the basis of de . ent Will sort ., ... 1 ;

ii
scend1ng ord the records f
mysql> SELECT* FROM d er of column mark1rstly on the column
ata - - - - - - - s. name Section
st
->ORDER By section

+---------+----------+---
1 r oll no I name
+- --------+--- -------+---
· ...,
AS(

I mark
aa
s
. - - - - and

----+-
Fir sort field i
for all

------+------
I gra d e I se c . -----+
.
s section in ascend ·
, marks DES( . with descen;.e records of same sec:? orter (as section ASC)
, ing order (marks DES~;, t e sort field is marks

I 101 I Ruhani .,,- ---


·, ---+-- -----+-- t1 o n
76. 80 - - ~ - See _all records of same
dh
102 George I A I A - I ~ section are listed together
71.20 I B
111 I A I
Simran 66.00
118 Neha 59.50
108 Meera 97.20 All records with same section
A+ I B are arranged in descending
113 Gurnoor 93.50 A+ I B order of marks column
106 Arsiya 91.60 A+ I B
103 Simran 81.20 I A I B
pa

115 Rabiya 7 2.50 I B I B


109 Amaal 57.20 I C I B
107 Raunaq 32.50 I F I B
11 2 Adam 74.20 I B I C
10 4 Ali 61. 2 0 I B I C
105 Kush a l 51.6 0 I C I C
117 Rahil 3 2. 0 0 I F I C
+--
15 ---+----------+----------+-------+--------- -- +
r ow s in set (0. 0 0 s ec )

14.2.3
Ordering Data on the basis of an Expression
Soineti
1

result ;es! you need to display the result of a calculation or a mathematical expression in the
calculated. n SUch cases, you may want or need to arrange your result set in the order of the
express· express1on. · The ORDER BY clause allows you to include • the mathematical
lt\athe ion. t0 order the result set by it. However, to arrange a result set on the basis of a
the 11\a~:~al _expression, you should preferably (though not a necessity but preferably) include
atical expression in the select list so that it becomes easy to comprehend the result.
COi\\P UTER SC IENCE WITH PYih Q
4b 0 O
_

r le sta teme nt tl lcl t arran?<'::,es tl1 e r e ~·ult set on the basi s of a


C(m~ itkr tlw folllH·\·ing ...•-' "..,' c'l ll11J
- 1ku lc1ted r esult : t. mark s * . 35 FROM data
L,
111ysq l > SELECT rolln o, name , grade , sec ion, ~ : <
-> ~vHERE marks > 70 ks * 0 35 DESC ; •••••• •••••• ••••••
- > ORDER BY secti on ASC, mar . ---+ ••\

----f - - ----- ---+ ---- -- - --- +-- ---- ---+ ---- -


I mark * 35 I ,..
,---- - I grad e s ·
I s ec ti o n ----+
I ~olln o I n ame +-- - ---- --+- ---
f--- -- ----+ --- - ----- -+-- -- --- I 26 . 8800
l ll 1 Rulla ni A I A 24 .9200
l0 2 Ge o rg e I B I A
I B 3 4 . 0200
108 I Me e r a I A+
Gurn oor A+ I B 32 . 7250
I 11 3 I
32.0 600

ii
1 106 I Arsiy a A+ I B
10 3 I B 28.4 200
1
simra n I A 25 . 3750
I 11 5 Rabiy a I B 1
I B I c I 25 . 9700
~-~~ ~ ----- ~- ~~~~ - ---- ~-~ ---- ---- +---

aa
---- --+- ---- - - ----+
. et ( 0 02 sec)
s rows in s ·
. . h
If You want th math emat ical expr ess10 n mt e select
. a co1
you can provide alias name to e b .
mnn h
' wing state ment w1·11 a Iso produce t e sam
list, e.g., follo e resul t as ·11
abov e ut it w1 name the
colum n rnarks*.35 as Terr nl: . arks * as Term l FROMdat a
mysql> SELEC T r ollno , name , grad e, secti
••••••on , . 35
••••••m•••••• • ••• •• •••• ••
-> WHERE marks > 70 "Y ..
- > ORDER BY secti on ASC , Term l DESC ;
dh
•••• • • • •. •. • •• • • • • • • • • • • • •••
- +- - - - - - - - - - +- - - - - - - - - - +- - - - - - - - - +
+ •••••
+I r o ll no I name I gra d e I sect ion I Terrn l I ••:
-+-- ----- ---+ - - ---- - ---+ ---- ---- -+-
+--- - ---- . A I A
- --- -- - - --+ • •••••
101 Ruhan 1. 26.8 800 I
1 02 Geor ge I B I A 24.9 200
108 Me era A+ I B 34.0 200
11 3 Gurn oor A+ I B 32.7 250
106 Ar siy a I A+ I B 32.0 600
pa

103 Simr an I A I B 28.4 200


115 Rabi ya I B I B
112 25.3 750
Adam I B I C 25.9 700
+--- ---- --+- ---- ---- -+-- ---- -- -- +---
---- --+- ---- ---- --+
8 rows in set (0. 00 sec)

14 .2.4 Specifying Custom Sort Orde r


Sometimes, you have a column where you wan t to arran
ge data as per your own specified order.
For example, if there is column called Project that store s the
statu s of proje ct mad e by the students.
It can have possible values a_s Evaluated, Submitted, Pending,
Assi gned . If you wan t to arrange ;
resu lt set on the basis of this Pro7ect colu mn as per this th
orde r : Eval uate d, Pending, Submitte '
Assigned. For this, you need to use the FIELD func tion in
SELECT
ORD ER BY clau se as per this format :

ORDER BY FIELD( <column name>, <val ues spec ifyin g


or de r >) ,
r E ON 5Q L
. MO R
14
,er • l1-6 1
(10P D function mternally maps the v 1
JEL b f . a ues-specif .
fnef those nurn ers or sortmg. You need not do anythi y1n g-order to a I' t O f .
. is n umeri c v · I
tJ1el1
1,1ses
t nd let us consider the same data t bl . ng, FIELD( ) does all th 15
. ~ ucs and
!lders a ' a e with add d . on its own
fotJ __ _ _ -- + - -- - --- - --+ -- - - ---- - -+ -- - - -- - + -· - . e proiect column w ith th cse - .
val ues :
n am e ma rk s - - --- - -, - -
1
/ -
11no 1 1 grad e I s . -- - ,
ro --------- -+ - - -- - --- - -+ ---- --- + e ct ion I P ~OJ. ~c t
---+
Ruhani I 76.80 A --- -- ---- +---
1 A Pe ndi ng - -·- +
Ge o r g e I 71. 20
I B I A
10 2 s imr an 8 1. 2 0 S ubmitt ed
I A I B
103 61. 2 0 Ev alu a t ed
Ali I B I C
104 Assig ned
Kush a l 5 1. 60 I C I C
105 Eva l uated
Arsi ya 91. 6 0 A+ I B
10 6 Submi t ted
Ra u naq 3 2 .50 I F I B
107 Submi t ted
97.20

i
Meera I A+ I B
108 Ev a lu at ed
Amaal 57.20 I C I B
10 9 Pen d i ng

i
Simran 66.00 B I A
11 1 Pe nding
Adam 74.20 B I C

115
I 117
I 11 8

15 ro ws
112
113

Neha
aa
Gurnoor
Rabiya
Rahil
93.50
72.50
32 ' OO
59.50
I

C
A+
B

F
I A
I B
I B
I C
Pe nd ing
Assi g ne d
Ass i gn ed
S u bm i tted
Ev aluate d I
+-- -- - - - - - + - - - - - - - - - - + - - - - - - - - - - + - - - - - - - + - - - - - - - - - + - - - - - - - - - - - +
in set (0. 00 sec)

Now to order the above table as per the mentioned order above i.e., as per Project field having
dh
values in this order : 'Evaluate d', 'Pending', 'Submitted', 'Assigned', you can write the SELECT
statement's ORDER BY clause with FIELD() as shown below:
~ The sort field
mysql> select * from data ~
-> ORDER BY FIELD(Pro ject, 'Evaluate d', 'Pending' , ' Submitted ', 'Assigne d' ) ;

'
The desired sort order;
+---- - - - - - + - - - - - - - - - - + - - - - - - - - - - + - - - - - - - + - - - - - - - - - + - - - - - - - - - - - + Notice, string values
I grade I secti o n I pr o ject
I are given in quotes
pa

I r ollno I name marks


+---- - - - - - + - - - - - - - - - - + - - - - - - - - - - + - - - - - - - + - - - - - - - - - + - - - - - - - - - - - +
I 11 8 Neha _ 59 50
c I A E v aluated I

108 Meera 97.20 A+ I B E v a luated


Eval uated
105 C C
Kushal 51.60 E v a luat e d
103 A B
S imran 81.20 Pen ding
10 1 A I A
Ruhani 76.80 Pending
112 B C
Adam 74.20 Pendi ng
11 1 B A
66.00

'
Simran Pending
109 C B
Amaal 57.20 su bm itted Result set order as per
102 B A the custom order as
Ge o rge 71.20 sub mit t ed
107 B specified by you.
Raunaq 32 .50 F su bm i t t e d
106 B
Arsiya 91.60 A+ s u b mi tted
117 C
Rahil 3 2 .00 F As s igned
113 B
Gur n o o r 93.50 A+ As s i gned
115 B
Rabi y a 7 2 .50 B Assig n ed
104 C
I
>, Ali B --+----- ------ +
I 61. 2 0
15 r ows -~-+---- ------+- --------- +------- + ----
1n se t
( 0. 0 4 s e c )
462 COMPUTER SCIENCE WITH PYTHON
- Xii

14.3 AGGREGATE FUNCTIONS


Till now you have learnt to work with functions that operate on individu al rows in a table e.g., if
you use Round() function then it will round off values from each row of the table.
MySQL also supports and provides group functions or aggregate functions. As you can Inake
out that the group functions or aggregate functions work upon groups of rows, rather than on
single rows. That is why, these functions are sometimes also called multiple row functions.
Many group functions accept the following options:
DISTINCT This option causes a group function to consider only distinct values of the
argumen t expression.
ALL This option causes a group function to consider all values includin g all duplicates.

ii
The usage of these options will become clear with the coverage of example s in this section.
All the examples that we'll be using here, shall be based upon followin g table empl.

I EMPNO I
+-
aa
T able 14.1 Database table empt
+-----+ -------- --+--- - ------+ ----- +- -------- --+---- ----+-- ----- - +------+
ENAME JOB I MGR I HIRE DATE SAL
--+---- ------+ -------- --+---- -+----- ------+ -------- +------ --+---- --+
I 8 3 6 9 I SMITH
I 8 4 9 9 I ANYA
I 8 521 I SE T H
I CL E RK
I SALESMAN
I 8 9 o2
I 8698
1990-12 -18 I 800.00
1991-02 -20 I 16 00 . 00
I NULL
COMM

I 300.00
I DEPTNO I

20
30
dh
I SALESMAN I 8698 19 91 -02- 22 I 1250.00
I 8 5 6 6 I MA HADEVAN I 500.00 30
I MANAGER I 8839 19 91 -04-0 2 I 2985 .00
I 8 6 5 4 I MOMIN I NULL 20
I SAL ESMAN I 8698 1991-09 -28 11 250 .0 0
I 8 698 I BINA I MANAGER I 1400.00 30
I 8839 199 1- 05 - 01 I 2850.00
I 8 8 3 9 I AMIR I PRESIDEN T I NU LL
I NULL 30
1991 -11-18 I 5000.00
I 8 8 4 4 I KU LDEEP I SALESMAN I NULL 10
I 8 698 1991-09- 08 1150 0.00
I 8 8 8 2 I S HI AVNSH I MANAGER I 0. 0 0 30
I 8839 1991-06 -09 I 2450.00
I 8 8 8 6 I ANOOP I CL ER K I NULL 10
I 8888 1993-01- 12 I 1100 .00
I 8 8 8 8 I SCOTT I ANALYST I NULL 20
I 8566 1992-12 -09 I 3000
I 8 90 0 I JAT I N I CLERK .00 I NULL
I 8 6 98 20
pa

1991-12 -03 I
I 8 9 o2 I FAKIR I ANALYST 950.00 I NULL
I 8566 1991-12 -03 30
I 8 9 3 4 I MITA I CLERK I 3000 .00 I NULL
I 8882 1 992-0 1-2 3 20
+-----+ -------- --+----- ----- +----- 11300.0 0 I NULL
10
-------- ---+--- ---- - +------ --+---- --+
l . AVG
This function computes the average of given data.
S3/nta;<
AVG( [DISTINC T I ALL] n)
J.. Returns average value of parameter (s) n.
Argu~enI !_yp~ : Numeric 13-~~u!n !lE_{~ : Numeric

EXAMPLE 14.1. Calculate average salary of all employees +------ ------ -+


listed in table empl. I Average
+------ -------+
Solution. mysql> SELECT AVG(sal) "Average " I 2 0 7 3 . 928571 I
FROM empl; +--- -- -------- +
1 r o w in s et ( 0. 0 1 s e c l
4c3

+-- -- -- -- -- -r-
1 ~0t al

ii
mysq l > SELECT COUNT( *) ''To tal "
l-l
FROM empl ; +-- --- --- -- +

f\.\t--lPl E

Sol11 til>11.
mysql> SELECT COUNT(job) "Jo b Cou
nt"
aa
l -U . Ctm 11t 111111,bcr c>fjobs in tn[,/ c
cmpl.
l 1' 0\\" i n set

+-- - - --- -- ----+


I J o b Cou n t
+-- -- - --- -- ---+
14
(0 . 00 se;:: \

FROM em pl; +-- - --- --- --- -+


dh
1 row in set (0 . 0 1 sec )

EXi\t-- lPLE 14.4 . How 111n1111 distinct jobs nre


. . listed i11 table e111pl ?
So/11tio11 . +- -- -- --- --- --- -- +
I Di sti nct Job s
mysql> SELECT COUNT ( DISTINCT job
) "D isti nct Job s" +-- --- - --- --- - --- +
FROM em pl; 15
+---- --- --- --- --- +
pa

l row in set (0. 04 sec )

This fu t·
nc ion returns the ma xim um val ue f · en column or expression.
rom a giv
~
MAX( [DISTINCT I ALL] exp r)
" Rett1r
ns n1aximum val ue of arg um ent expr.
Aro..
o•111Ie11t t, '.
YPt · Nu me ric Ret11r11 vnl11e : Nu meric
~
,Xi\~ +---- --- --- -- -- --+
So/ 11 •PLE 14 •S• D1sp
· lay max
fio11 •
imu m salary j.rom tabl e empl. I Max imu m Sal ar y I
+-- --- --- -- -- ---- +
500 0 . 00 I
SELECT MAX(sal) "Maximum Sal ary" +-- - -- --- --- --- - - +
·n s et (0. 0 1 s ec )
FROM em pl; .l r ow 1
4. MIN . . alue from a given column or e xpression .
This function returns the m1mrnurn v

MIN( [DISTIN CT I ALL] expr)


. ·mum value of expr.
J,.. Returns m lIU .
. Return value: Numer ic
Argument typ!_ : Numen c - - --- -
+----- - -- -- -
. l the Joining date of seniormost employee. M i n i mum pl 1· r
14.6. Disp ay D - -
1
EXAMPLE {··
+--- - ---- - - i t, I

1 990 - 1 2-l a
Solution~ysql> SELECT MIN(hi redate ) "Minimum Hire Date" +---- - --- --- -- --
1 row i n s e t ( O ( ·
FROM empl; • I6 ,

ii
5. SUM . ·
. given
This function returns the sum of va1ues m colum n or express10n.

J,..
SUM( [DISTIN CT

Argument type : Numeric

EXAMPLE 14.7.
I ALL]
Returns sum of values of n.
aa n)

Return value: Numer ic

Display total salary of all employees listed in


+----- ------ ----- +
Total S a lar y I
+----- ------ -- - - -+
dh
table empl. 29035. 0 0 I
+----- ------ ----- +
Solution.
1 row in set ( 0 . 01 secI
mysql> SELECT SUM(sa l) "Total Salary "
FROM empl; I

Some more examples of group functions are being given below :


These functions are called
Examples :
pa

.
aggregate func tions bec ausethe1
1. To calculate the total gross for employ ees of grade 'E2', operate on agg regates 0 f tuples
the comma nd is : The result of an aggrega ~
SELECT SUM(gross) FROM employee function is a single va lue.
WHERE grade = 'E2' ;
.
2. To display the average gross of employ ees with grades 'El' or 'E2', the comman d us ed is:
SELECT AVG(gr oss) FROM employ ee
WHERE (grade = 'El' OR grade= 'E2') ;

3. To count the numbe r of employ ees in employee table, the SQL comma nd is :
SELECT COUNT(*)
FROM employ ee ;

4. To count the numbe r of cities, the differe nt me b b the follo 1' ir~
comma nd: m ers e1ong to, you use
SELECT COUNT(DISTINCT city) FROM members .
,
c!Jll/"

. the DISTINCT keyword ensure th 465


f{ere
nly argumen t th at me
. 1
udes NULL
s at rnulti
pie entrie f
theo
couNT disregar
d NULL s When ·t.
s in any case.
u want to count the entries incl ct·
I IS Used only With co~i
so the sam .
are i~1ored. The* is
If yo ' functions other than
u mg rep
rnand will COUNT the number of eats, the keywo d AL .
corn non NULL • r L 1s used Th f 11
SELECT COUNT(ALL city) city fields in th · e o owing
FROM members ; e members table .
·
In general, GROUP functions
¢) Return a single value for a set of rows.
¢'- Can be applied to any numeric val
'I ues, and som T
e ext types and DATE values.
TYPES OF SQL FUNCTIONS
14.4

ii
Now that you have learnt different types of fu t·
SQL supports many and many functions All thnc ions,
f
let us talk abot1t th . b d
. eu roa categories.
following two types : · ese unctions can be generally categorized into

aa ¢)

¢)
Single Row (or Scalar) functions.
Multiple Row (or Group or Aggregate) functions.
(i) Single Row functions work with a single row at a time. A single row function rehirns a
result for every row of a queried table.
(ii) Multiple Row or Group functions work with data of multiple rows at a time and return
aggregated value.
dh
Examples of multiple row functions are the group functions that you have learnt in
previous section i.e., sum( ), count( ), max( ), min( ), Avg( ) etc.
The difference between these two types of functions is in the number of rows they act upon. A
single row function works with the data of a single row at a time and returns a single result for
each row queried upon; a multiple row function works with a group of rows and returns a
single result for that group.
pa

145
· GROUPIN G RESULT - GROUP BY
The GROUP BY c1ause comb'mes a II those records that have identical values in a particular field
.
or a group of fields This rou in results into one summary record per group if group-
functi 0 · g P g d h GROUP BY clause is used in SELECT statements
to d1.v·dns are used with it. In other wor . s, t e b ame or with ao-o-reo-ate
1 e
the table into groups. Groupmg can be done y a co1umn 11 , oo o
functi .
ons m which case the aggregate pro d uces av alue for each group.
For ·
example, to calculate the number of employees in +---------- - -+ --- - - -- --- +
ea.ch
grade, you use the command I job I COUNT ( *) I
+--------- - -- +------ --- - ~
:ELECT job, COUNT( * )
I ANALYST 2
ROM empl
CLE RK 4
GRoup BY J' ob . 3
CR_ , MANAGER
. OlJp BY .
applies the aggregate f t mctions I PRES I DENT I 1
ind . 4
epende tl h •
by h . n Y to a series of groups t at are defined I SALESMAN
+----- --- -- -- +--- ------ - +
aving a f'1e1d value in common.
. h f ll
Now cons ider t e o ow ing quer y ' whic h is also grou ping reco rd s base d on deptn o_
mysq l> SELE CTde ptno , COUNT( * ), SUM (sal )
FROM empl
GROU P BY dept no ;
+-- ---- -- ---- +--- ---- --- +--- -- -- -
+
dept no I CO UN T (.,, l SUM (sal) I
I
+--- ---- ---- - +--- ---- --- +- -- - - - ---- - -
+
10 3 8750 . 00 I
20 5 1 088 5 . 00 I
I 30 I 6
9 4 00 . 00
+--- ---- -- ---+ - -- ---- --- +--- ---- ---- -
+
As you can mak e out that the abov e quer y is d ispla
ying coun t of reco rds and sum of salari es in

ii
each grou p and the grou ps are form ed on the basi
s of deptno. Thu s, from the abov e output, yoJ
can mak e out that in depa rtme nt num ber 10, ther
e are 3 emp loye es (reco rd s) and total of al:
salaries is 8750.00 ; in depa rtme nt num ber 20, ther
e are 5 emp loye es and total of salaries i~

aa
10885.00; and so on.

14.5 .1 Nested Grou ps - Gro upin g on Mult


iple Colu mns
With GROUP BY clause, you can crea te grou ps with
in grou ps. Such type of grou ping is calJed
Nested grouping. This can be done by spec ifyin g in
GRO UP BY expr essi on, whe re the firs t field
dete rmin es the highest group level, the second field
dete rmin es the second group level, and so on.
The last field dete rmin es the lowest level of grouping
.
dh
In orde r to fully unde rstan d this conc ept, cons ider
Tabl e 14.1 emp l.
See there are mult iple-reco rds havi ng sam e valu e for
field Dep tno, we can grou p records on the
basi s of field _Deptno. For instance, if you wan t to coun
t the num ber of emp loye es in each group,
you need to issue a quer y state men t as give n belo
w:
SELECT COUNT(empno) FROM empl +--- ---- ---- -- +
l coun t(em pno)
GROUP BY Dept no j
+--- ---- ---- -- +
pa

3
5
And the resu lt prod uced by this quer y is
6
+--- ---- ---- -- +
But can you mak e out, these are emp loye e-co
unts for
infor mati on, you may mod ify the SELECT list as:
whic h depa rtme nts ? To get this

SELECT Dept no, COUNT(empno) + - - - -- - - -- + - -- - - ---- - -- - --


FROM empl 1 dep tno I c ount: ( e,m!) r. : '
GROUP BY Dept no ; + ---- ---- - + ---- ---- -- - - - - -
10 3
20
Now the resu lt will be : 5
30 I 6
+-- ---- --- +--- - -- ---- -
-
See now it is mor e clear. But one thing that you
' . . h
. s ou 1d
Y
ou shou ld mclu de only thos e valu es m
. the select z· kee P _m · • . · "
min d 1s that w hile grou p111o'
up or (
cont am a grou p aggr egat e) func tion i e zst that e1th h
gro er ave the sam e valu e for a
· ·, a grou
p-ex pres sion . Like in the abo\' c'
fe 14 : MO RE ON SO L
cnoP r
' the first ex p ression Dept 467
qu er) ' no fie!
ession COUN T(emp no) . d has one (,
expr contai ns a g rou f ~a me) valu e fo r a group and the other
.A 5QL as such would not create
1v1y . P unction .
t-list. A non-group field ( any error even 1f. you i
se Iec or expressio ) . d
nc Iu e a non-gro up express i on in the
belongi ·ng to the group n is the field th h .
· at as different va lues in the rows
this case, it will return the value fro .
r...
you issue comma n d 1·k m first record 0 f h
jJ'
1
e: t e group for that non-gro up fi eld e.g., if
SELECT dept no, count ( empno)
, mgr Th is is non-group field as it has
FROM empl
multiple values for a group.
GROUP BY deptno ;
The output return ed will be:

ii
+ - - - - - - - - - + - - - - - - - - - - - - - - +- - - - - - + See, first record of group with dept no IO has value .'V l., 1./, in mgr
I dept no I c O un t ( e rn P no ) I rn g r I field : first record of group with dept no 20 has R902 in mgr field :
+ ___ _ _ - - - - + - - - - - - - - - - - - _ _ + _ _ _ __ -~ a_nd first record of group with cleptno 30 has va lue 8698 in mgr
1 10 I 3 fi eld. Hence this output.

aa 20
30
I 5
6
I

+- -- -- --- -+ - - --- - - -- - - --- +---- - - +


NU L L
I 8902 I
I 8698 1

To create a group w ithin a group i.e., nested group, you need to


specify multip le fields in the GROU P BY expression. If you
have a look at the record s of Empl table, you can make out that
there exists a group of jobs within the department group as there
I

those fields or expression s stat e


be included that eit her ret urn
single value for a group or are
constants . Oth erwi se yo u may not
i:-~~~
:· • ,:,.4 r

In the select li st of a grou p, only


. '
dh
get aut hentic results .
are same values for Job field, in one depart ment group's records.
To group record s job wise within Deptno wise, you need to issue a query statem
ent like:
SELECT Deptno , Job, COUNT(empno)
FROM empl
GROUP BY De pt no, Job ;

And the result produ ced is :


pa

+- - - - - - - - +--- -- - -- ---+ --- - --- - - - - - - --+


I de pt no I jo b I coun t ( e rnp n o ) I
+- - - -- - - - +- --- -- ---- - +- ---- - ------ --- +
10 CLE RK 1 I
10 MAN AGER 1
10 P RESI DENT 1
20 ANA LY S T 2
20 CLERK 2
20 MANA GE R 1
30 CLE RK 1
30 MANAGE R 1
30 I S ALES MA N I 4
+---- - ---+ - -- - -- - - -- -+ -- - - -- -- -- - - - -- +

14.5 2 . G
G Clause HAVIN
· Placing Conditions on roups - . t t to WHERE clause that places
'1'1..
tne HAVING clause places con ditions on groups m con ras f .
c .. d' . cannot include aggre gate unct10ns,
ondihons on indivi du al rows. Wh 1·1e WHERE con it10ns
liAVING condit ions can do so.
If

U lM l) LJ I l R 'i( IL NC ~- WI I I I ,
I Yi I Ir JI
l•'o r l'X'-trnpk, to calcu blL' lhc .:ivera gl' gross and
l
c m p Ioycc s t.oc Iong1. ng to '1,4'
j gra d<.', tlw con- -., JOl,1 1~,i•rl,.,\f,
101 u
ll Woui
·1. Can you arrange the result set of an sr: 1 ECT AVG( gr'n ss ) , SUM( cro ss )
db1,
SOL query on multiple columns ? rnoMemplo yee
2_ What is the significa nce of "ORDER 13Y" GROUP BY gr ade
- 'l'liis rn11diticn 1 w"
in the given query? .
r11111I1c11h/e 011 ,,,. ll 1r/ h•
HAVI NG grad e = 'E4' ,
. . r, UlfJ >UIJ,(
SE LECT emp_ i d , f namc, l nJmr u 11 llltli JJi</1w/ ro 111.1 '''"

FROM pers on To d is pl ay th e jobs whe,,·e the num ber of crnployl'L•s.


,
ORDER BY emp_ id; than 3, you use t l1e com man d : IS 1l

(a) Data of table person on the basis of


SELEC T JOB , COUN T( * )
column emp_id will be sorted in I -- -- - - -- - - - I - -- -

FROM empl

ii
descending order JOn I COU iJ'J', .
1
(b) Data of table person on the basis of GROUP BY job I -- - - - - - - - - -1---
I /\NAJ. Y ST'
column emp_id will be sorted in HAVI NG coun t(*) < 3 ;
I PH l::S [ Dl~N•r
I
ascending order

aa
(c) Only data of column emp_id will be
sorted in descending order
(d) Only data of column emp_id will be
sorted in ascending order
3. What will be the order of sorting in the
given query?
SELECT emp_i d , emp_ name
FROM perso n
Thi s will prod uce the
fo11o wing outp ut : 2
1--- - - - ----- +--- -- - - -

r o ws

The HAV ING claus e can conta in eithe r a simple boolean


i.n

expr essio n (i.e., an expr essio n or cond ition that results into
true or false) or use aggre gate function in the having condition.
You can inclu de more than one condition in HAVIN
G
i
se t ( D. 1I :,c
dh
clause, of cours e, by using logic al operators. Consider this:
ORDER BY emp_ id , emp_name ;
SELECT Dept no, AVG(Comm), AVG( Sal)
(a) Firstly on emp_id and then on
emp_name FROM empl
(b) Firstly on emp_name and then on GROUP BY Dept no
emp_id HAVING AVG(Comm) > 750 AND
(c) Firstly on emp_id but not on AVG( Sal) > 2000 ;
emp_name
Also, you can use an aggr egate fu nct10· nm
· the HA
, YINGhe
(d) None of the mentioned
pa

clause even if it is not in the SELECT list. Consider


4. If column emp_id contains the t
following set {9, 7, 6, 4, 3, 1, 2}, what following quer y to unde rstan d this :
will be the output on execution of the SELECT Dept no, AVG (Sal)
given query? FROM empl
SELECT emp_ i d FROM perso n GROUP BY Dept no
ORDER BY emp_ i d;
HAVING COUNT(*) <= 3 ;
(a) {9, 7, 6, 4, 3, 1, 2} G
(b) {1, 2, , 3, 4, 6, 7, 9}
You can also use IN or BETWEEN oper ators wit. hI-fAYIN I

clause. Follo wing two quer ies illust rate this :


(c) {2, 1, 4, 3, 7, 9, 6}
(d) None of these SELECT Dept no, Job, AVG (Sal)
FROM empl
5 Which function can you use with
· ORDER BY clause to specify custom sort GROUP BY Dept no, Job
order ? HAVING JOB IN ('CLE RK', 'SALE SMAN ') ;
(a) SORT( ) SELECT Dept no , Job, SUM (sal)
(b) CUSTOM( ) FROM empl

(c) FIELD( ) GROUP BY Dept no, Job

(d) All of these HAVING SUM (sal) BETWEEN 3000 AND 7000 ;
: MORE ON SQ L
14
r ~Jpfef
~

Non -Gr o up Exp ress ions with GR


J 5. 3 o
. ' UP BY 469
1 · enti one d befo re, 1£ y ou in duc t
As rn e a non
oVP BY, MyS QL will not pro du
GR . Id fr th fir
-gro u p expr essio .
-group fie om e st row of thce any erro r. Rath
110:n • e I·tn in. the .select-l"ist. f
o a qu ery w ith
. prod uce amb igu ous resu lts Fo . e grou p B r w t!] pick v I "' f
w111 · r Inst anc · ut we do not a ue o the speci fied
e, cons ider the f reco mm .
end ti · ·
1Js przic hce
mysql> SELECT ename ollo w because it
( mg q ue 1. d .
J 5 um s al) Y an it s outp ut.
FROM empl
+ -- - - - -- - 4 -- - - - - -
GROUP BY dep tno . I e n am e
I .,
J
j ;- l .' - I
+--- - -- - - +--- --- - - --
See' isn' t it con veying that AM IR's sal I AM I R il - r • , , ,, 1 :;

SMITH'S 10885.00 and AN YA 'S 940 0.00 ary- sum . 8750 I SM I T H I l G O 8 '.J • [, ,.
? is .00, I ANYA 9400 . u'
Thus we reco m men d not to u se non -gro + - -- - - - - - + -

ii
' up . .
necessary. expr essi ons m GROUP BY
query unless otherwi se

LET US REVISE
<&
-:i

The ORDE~ BY clause lets you arrange the resu


an expre sswn and as per custom sort orde

i The GROUP BY clause combines all those


<& GROUP BY clause is used tn divide the resu
aa
lt set in the order of singl e column, multiple colum
r too.
records that have identical value in a particular
lt in groups.
fie ld or
ns, on the basis o(

a group o( fie lds.

<& A group within another group is


dh
called Nested Group.
% Nested grouping can be done by prov
iding multiple fields in the GRO UP BY expr
essio n.
% All fields containing a NULL value are
considered to have a value and are grou ped to
with the fields containin g non-NULL values. have a va lue and are gro up<'d
% The SELECT list of a group can inclu
de expressions returning singl e va lue per grou
p or constants.
% The HAVING clause is used to specify
filtering condition for grou ps.
% The difference between WHE RE and
HA VJNC clause is that WHERE conditions
ar<' applicable on indiv idual rows
pa

whereas HAVING cond itions are applicable


on groups as form ed by GRO UP BY claus e.

l. Th SQL
e SELECT prov ides clauses for sortr.ng data andfior summari zing res ults. Writ e the 11aJ11 cs of cln 11 scs
for these.
S
olution. The ORD ER BY clau se of SQL SEL t 11 ws to sort the data of resu lt se t.
Th ECT statemen a o .
t0 create sum marized results of g10 . "'
e GROUP BY clau se of SQL SELECT state u ped
men t allow s
data from table.
2. y
ou Al
Want to group the result set based on some co l unm 's value. so, yo u wnnt thnt tile gro 11 pcrf rcs11. lt s/1011./d
appear in a sorted order. In which order will you (fo r sorting n11d fo r S; /'O ll f!/ 11 ~). G, t,c
write the two c1n11ses ,
exain p/e tO ,
support your answer. .
Solut· d ) d ORD ER BY clau se (for sort mg
ion. Whe n we use GRO UP BY clau se (for ino- of ata an
data) grou p o . .
w1·n toge ther, the ORD ER BY clau se alw ays fo II 0 ws othe1 c1auses· That is, the GROUP BY cbu se
come before ORD ER BY clau se.
p 470
COMPUTER SCIENCE WITH
PYTH ON
For exa mp le, . ,.
SELECT use rid , SU M( sco re) AS
tot al_ sco re
FROM use r _sc ore
GROUP BY use rid

3.
'P .
ORDER BY use r id ASC ,·

In a table Ap ply, there is a column


nvate-sector-expenenc. .
e', 'Publzc-
You want to sort the data of table base
namely Experience that can store onl
.
sector-experzen ce,, 'G ovt.-sec tor experie
d on column experience as per this ord
.
y one of these valu es . 'F
nce,. . resher·
.
\
I
1

, . . . er : 'Govt-sector-exp . ,
Publzc-sector-experze . , ,
nce', 'Przvate-sector-experze nce , Fresher ,. enence· 1
Write an SQL que ry to achieve this . ··

ii
Sol utio n.
SELECT * FROM Apply
ORDER BY FIELD (Ex per ien ce, 'Go

4.

aa
What are different types of SQL functio
Sol utio n. (i) Sin gle Ro w (or Sca

(i) Single Ro w Functions wo rk

(ii)
vt. -se cto r-e xpe rie nce ', 'Pu blic
'Pr iva te- sec tor -ex per ien ce' ,
ns ?
lar) fun ctio ns.
(ii) Mu ltip le Row (or Gro up or Ag

wit h a
for eve ry row of a que ried table.
Multiple Row or Group Functions
'Fr esh er' );

gre gat e) fun ctio ns.


-se cto r-e xpe rien ce'

sin gle row at a tim e. A sin gle row


'

fun ctio n returns a result


dh
wo rk wit h dat a of mu ltip le row
agg reg ate d val ue. s at a time and return

5. What is the significance of GROUP BY


clause in a SQL query ?
Sol utio n. The GR OU P BY cla use
com bin es all tho se rec ord s tha t hav
fiel d or a gro up of fields. e ide ntic al val ues in a particul ar
Thi s gro upi ng res ults into one
gro up- fun ctio ns are use d wit h sum ma ry rec ord per group if
it.
6. What is the difference between a WHERE
clause and a HAVING clause of SQL
pa

Sol utio n.
SELECT statement ?
The diff ere nce bet we en WH ER
E and HA VIN G cla use is tha
app lica ble on ind ivid ual row s wh t WH ER E conditions are
ere as HA YIN G con diti ons are app
GR OU P BY clau se. lica ble on gro ups as formed by

7. Write a query to display the Sum, Ave


rage, Highest and Lowest salary of the
Sol utio n.
employees.
mysql> SELECT SUM (sa l), AVG
(sa l), MAX (sa l), MIN (sa l)
FROM empl ;
8. Write a query to display the Sum,
Average, Highest and Lowest salary
department number. of the employees grouped by
Sol utio n. mysql> SELECT SUM (sa l), AVG
(sa l), MAX (sa l), MIN (sa l)
FRO M empl GROUP BY deptno ;
Write a query to disp lay t he Sum, A
9. v~rage, H.zghest an d Lowest salary
t number and sub of the employees groupe d b.11
depar t men -grouped by 70b.

Sol uti on . l SELECT SUM (sa l), AVG (sa l), MAX
mysq > (sa l), MIN (sa l)
FROM empl .
GROUP BY dep t no, Job ;
, i
4 : MORE ON SQ L
,,. ;:)·i

, •te a query to display the 111.nnb .


i\ n e, of emplo 47 1
\t1, yees - ·ti
solution. WI 1 same job.
mys ql> SELECT COUNT(*) crNo
0
FROM emp - f _Emps'\ job
GROUP BY job ;

11 \t\'rite n query to display the difference O;,r 1nghes


.
· /ai1) > 4000. t dl
sa an °west salar 0 r e
Y 'J ach department having maximum
Solution.
mysql> SELECT MAX (sal) _ MIN (
sal) crD 1. f
GROUP BY deptno ference" FROM empl
HAVING MAX (sal) > 4000 .
J

7 Gopi Krishna is using a table Employee. It h ti fi _.

ii
1-• as 1e ollowzng columns ·
Code) Name ) Salary J Deptcode [CBSE D 2014]
·
He wants to display maximum salary department- · H

aa
wise. e wrote the following command :
SELECT Deptcode J Max(Sala ry) FROM Employee ;

But he did not get the desired result.


Rewrite the above query with necessary changes to help him get the desired output.
Solution. SELECT Deptcode J Max(Sala ry)
FROM Employee
GROUP BY Deptcode ;
dh
13. Shanyn Khanna is using a table Employee. It has the following columns : [CBSE OD 2014]
Adm no J Name ) AggJ Stream

[column Agg contains Aggregate marks]


She wants to display highest Agg obtained in each Stream.
She wrote the following statement :
pa

SELECT Stream) MAX(Agg) FROM Employee }


· • d lt R
But she did not get the desire resu . ewn·te the above quenJ with necessary changes to help her get the
desired output.
Solution. SELECT Stream) MAX(Agg)
FROM Employee
GROUP BY Stream ;
14. • t · a orders for each day. (If a salesperson has more
Write a query that counts the number of salespeople regis enn° )
th an one order on a given day, ld be counted on 1y once. .
he or she shou de) FROM orders
Solution. ( I sTINCT salesman_co
SELECT ord_date J count D

15. W . GROUP BY ord_date ; . lfind the highest rating in each city. Put the output in this Jann:
rzte a query on the customers table that wzl .
For the city (city), the highest rating is : (rating). . h t rating is : J J MAX ( rating)
S1 ·t 'the h1g es
o Ution. SELECT 'For the ci tyJ J Cl y J
FROM customer s
GROUP BY city ;
CO MPUTER SCIENCE WI
TH PYTH0 1
GLOSSARY ~ - I i!
::.:::::i

Single Ro w function
A fun cti on tha t wo rks
Multiple Ro w function on a value in si ngl e row
.
A fun cti on tha t works
Group function on valu es of a group
of rows.
Function tha t works on
Aggrega te function a gro up of row s. A mu
ltiple row function .
Functio n tha t works on
ag gre ga te of row s. A
multiple row fun ctio n.

Type A : Short Answ


er Qu es tio ns /C on ce pt
ua l Questions
1. W ha t is the us e of OR

ii
DER BY clause?
2. W ha t is the d efa ult
so rt or de r of ORDER BY
3. W hic h fu nc tio n do clause?
yo u us e in ORDER BY
clauses to specify cu sto
m so rt ord er?

aa
4. W rit e an ex am ple qu
5. W rit e a qu ery tha t

6. W ha t is the dif fer en


7. W ha t is the us e of GR
8. W ha t are ag greg ate
9. W ha t typ e of fu nc tio
ery tha t so rts on three co
so rts the da ta of table stu
se ction (in de sc en din g
order), Marks (in de sce
ce be tw ee n HAVING an
OUP BY clause?
functi on s? W ha t is their
ns can yo u us e wi th GR
lum
de
nd
nt
ns.

ing
on the basis of Pr oje ct- Gr
ord er)
d WHERE clause?
.

us e? Give some ex am ple


OUP BY an d HAVING
s.
ou p (in ascending order),
dh
clauses?
Ty pe B : Ap pl ica tio n
Based Questions
Fo llo wi ng qu es tio ns are
based on these tables :
Table BO OK _I NF OR M AT
IO N Table SALES
Column Na me Column Na me
BO OK ID STORE_ID
pa

BO OK TITLE SALES DATE


PRICE SALES_AMOUNT
Table EX AM _R ES UL TS

STU ID FNAM E LNAME EXAM ID EXAM SCOR E


10 LAURA LYNCH 1 90
10 LAURA LYNCH 2 85
11 GRACE BROWN 1
~ 78
11 GRACE BROWN 2
- 12 JAY JACKSON 1
72
L...- --
95
12 JAY JACKSON 2 92
~
WILLIAM BISHOP 1
13 70
--- W ILLIAM BISHOP 2
13 100
~ CHAR
L - Y - -~ LES PRADA 2 85
Ol< t VI' --''--" ~
4.M
1er 1 .
·roP
" . sQL statement allow s you to find th . 4 73
w111ch e highest
·
J. ) SELECT BOOK_ID, BOOK_TITLE , MAx(PRICE) FR Price from the table BOOK INFORM
(/1 OM BOOK IN - ATION?
ELECT MAX ( PRICE ) FROM BOOK INFORMA - FORMATION; .
(b) S - TION ;
ELECT MA)(IMUM(PRICE) FROM BOOK INF
(C) S - ORMATION ·
ELECT PRICE FROM BOOK_INFORMATION O '
(d) s RDER BY PRICE DEsc.
·ch SQL statement lets you find the sales '
?

Wh1 SELECT STORE_ID, SUM(SALES AMOUNT) amount for each stor ?
FRO e.
(a) - M SALES;
SE LECT STORE_ID, SUM(SALES AMOUNT) FROM
(b) - SALES ORDER BY STORE ID.
(C) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM S - '
ALES GROUP BY STORE ID .
(d) SELECT STORE_ ID , SUM(SALES_AMOUNT) FROM SALE - ,
S HAVING UNIQUE STORE ID .

ii
,,ri.,ch SQL statement lets you list all stores whose t t .
- J
3. vviu O a1 sa1es amount
1s over 5000 ?
(a) SELECT STORE_I D, SUM(SALES_AMOUNT) FROM SALES GROUP BY ST .
SUM(SALES_AMOUNT) > 5000; ORE_ID HAVING

aa
(b) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
GROUP BY STORE_ID HAVING SALES_AMOUNT > 5000;
(c) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE SUM(SALES_AMOUNT) > 5000 GROUP BY STORE_ID;
(d) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE SALES_AMOUNT > 5000 GROUP BY STORE_ID;
dh
4. Which SQL statement lets you find the total number of stores in the SALES table?
(a) SELECT COUNT(STORE_ID) FROM SALES;

(b) SELECT COUNT(DISTINCT STORE_ID) FROM SALES;


(c) SELECT DISTINCT STORE_ID FROM SALES;
(d) SELECT COUNT(STORE_ID) FROM SALES GROUP BY STORE_ID;
5
· Which SQL statement allows you to find the total sales amount for Store ID 25 and the total sales
pa

amount for Store ID 45?


(a) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
WHERE STORE_ID IN (25,45) GROUP BY STORE_ID;
(b) SELECT STORE_ID, SUM(SALES_AMOUNT) FROM SALES
GROUP BY STORE ID HAVING STORE_ID IN (25, 45 );
() - , SUM(SALES_AMOUNT)
c SELECT STORE_ID FROM SA LES WHERE STORE - ID IN (25,45);
(d) SELECT STORE ID SUM(SALES AMOUNT) FROM SALES
- ' - STORE ID·
WHERE STORE ID = 25 AND STORE_ID = 45 GROUP BY - '
6
· What SQL -
statement do we use to find the average exam score for EXAM_ID = 1?
(a) SEL rs·
ECT AVG(EXAM SCORE) FROM EXAM_RESUL ' .
(b) S - ROUP BY EXAM ID WHERE EXAM_ID = l,
ELECT AVG(EXAM SCORE) FROM EXAM_RESULTS G - _ .
(c) S - GROUP BY EXAM ID HAVING EXAM_ID - 1,
ELECT AVG(EXAM SCORE) FROM EXAM_RESULTS -
(d) SEL - SUL TS WHERE EXAM ID = l;
ECT COUNT(EXAM_SCORE) FROM EXAM_RE -
~ 474 CO M PUTE R SC IENC E WI TH PYT u
1• 0 r~
7 Wh ich SQL state men t do w e use to fi nd out
how man y stud en ts took each exam ?
(a) SELECT COUNT(DISTINCT STU_ID) FROM
EXAM_RESULTS GROUP BY EXAM_ID ;
(b) SELECT EXAM_ID, MAX(STU_ID) FROM
EXAM_RESULTS GROUP BY EXAM_ID;
(c) SELECT EXAM_ID, COUNT(DISTINCT STU
_ID) FROM EXAM_RESULTS GROUP BY EXAM
_ID;
(d ) SELECT EXAM_ID, MIN(STU_ID) FROM
EXAM_RESULTS GROUP BY EXAM_ ID;
8. Wha t SQL state men t do w e use to prin
t out the reco rd of all stud ents who se last nam
e start s w i th 'L'?
(a) SELECT * FROM EXAM_ RESUL TS WHERE
LNAME LIKE 'L%' ;
(b) SELECT * FROM EXAM_RESUL TS WHERE LNAM
E LIKE ' L';
(c) SELECT * FROM EXAM_RESUL TS WHERE LNAM
E = 'L ' ;

ii
(d) SELECT * FROM EXAM_RESULTS WHERE LNAM
E <> 'L';
9. Wha t is the resul t of the follo wing SQL
state men t?

aa SELECT MAX( EXAM_SCORE) FROM EXAM_ RESU

(a) 90 (b) 85

10. · Give n the follo wing table :

COACH-ID COACHNAME
L TS GROUP BY EXAM_ID HAVING EXAM_ ID

(c) 100

AGE
(d) 95

Table : CLU B

SPOR TS
= 1;

DATOFAPP PAY SEX


dh
1. KUKREJA 35 KARATE 27/03/1996 1000 M
2. RAVINA 34 KARATE 20/01/1998 1200 F
3. KAR AN 34 SQU ASH 19/02/1998 2000 M
4. TAR UN 33 BASKETBALL 01/01/1998 1500 M
5. ZUB IN 36 SWI MM ING
pa

12/0 1/19 98 750 M


6. KETAKI 36 SWI MM ING 24/0 2/19 98 800 F
7. ANK ITA 39 SQU ASH 20/02/1998 2200 F
8. ZAR EEN 37 KARATE 22/0 2/19 98 1100 F
9. KUS H 41 SWI MM ING
13/0 1/19 98 900 M
10. SHAILYA 37 BASKETBALL
19/0 2/19 98 1700 M
Give the outp ut of follo wing SQL state men
ts :
(i) SELECT COU NT (DISTINCT SPORTS)
FRO M Club ,.
(ii) SEL ECT MIN (Age ) FRO M CLUB WHE
RE Sex = 'F' ,.
(iii) SEL ECT AVG (Pay ) FRO M CLUB WHE
RE Spo rts= 'KAR ATE ' .
,
(iv) SELECT SUM (Pay ) FRO M CLUB WHE
RE Dato fa p p > ' 31/0 l/ , .
98 ,
\ ,e!l the foll ow in
I.I
G1 g ta bl e .
.

No, Name Table . S1


1 K ar an
. Ubf.1,rr 475
2 D iv ak ar an,
,.,
.J D iv ya
4 A ru n e
e
5 S ab in a
6 Jo hn
7 R ob er t
8
2so.oo
R ub in a
450.00 Humanities
9 V ik as Nomne ct·1c
500.00 al

ii
10 M oh an Nomn di
300.00
C A
Give the ou tp ut e cal 92.0 12A
of fo ll ow in SQ
(i) SELECT MIN
.. (A L
g ark) F
}M
st at aaommerce
ements :
67.S 12A
12C
(u ) SELECT SU
M(Stipe d) F R O M ~
n ROM St...,ud
TUDENT WHER
(iii) SELECT AV E AvgM
G(Stipend) FRO ark < 75 .
.1v ) SELE M ent WHERE Gra
de= 'B' .
( CT COUNT(DIS
TINC Student WHER ,
12. In a Databas e, T) FROM Stud E Class = '12A'' .
th ere are two tabl
es gi.ve ,
n below : ent ;
dh
T able · EMPLOY
EE
EMPLOYEE ID
NAME - Tab le : JOB
SALES JOBID
El SUMIT S IN H A - JOBID
JOBTITLE
1100000 102 SALARY
E2 VlJAY S IN G H 101 President
T OM A R 1300000 200000
101 102
E3 AJAY RAJPAL Vice President
1400000 125000
103 103 Administration A
pa

E4 MOHIT R A M N ssistant 80000


ANI
~

1250000 102 104 Accounting Man


E5 SHAILJA S IN G ager 70000
H 1450000 103 105 Accountant
wnt.e SQL Que . 65000
ri es for the follo 106 Sales Manager
wing : 80000
(i) To display em
ployee ids, names
(ii) To display nam of employees, job id
es of employees, sales s with correspondin
and corresponding job g job titles.
(iii) To displa y names and correspond titles wh o ha ve achieved sales more than
ing job titles of those em 1300000.
(iv) Id entify foreig ploy ee s who have 'SINGH' (anywh
ere) in their names.
(v) W ri te S Q L con key in the table EMPLOYEE .
m m an d to ch an
'EMPLOYEE'. ge th e JOBID to 10
4 of the EMPLOY
EE with ID as E4 in
the table
\~ :ow the aver
age sa la ry for al [CBS£ D 1s1
_· splay on ly th l departments w
1 •b ith m or e than 3 people for
l :i· F·ind o t ·t h a job.
e JO s w1 m ax • urn salary greater than or
16 . u im eq ua l to 30 00.
· List th nu m be r of em pl oy ee s ha vi "M
17 . L·1st e count ng anag er" as Job·
th of em pl oy ee s gr
18 . ou.pe d by dep tn (table EMPL)
· list the e su m of d by°-departmen
. em pl oy ee s' sa f la ne s greou pe
t. (tabl
e EMPL)
m ax im um sala gr ou pe d by thei
ry o em p1oye r department nu
mber.
476 COMP UTER SCIEN CE WI TH PYT
HO N
Consider the table s Customers, Parts and Orde rs gi.ven in
solve d probl ems.
Answ er Ques tions 19 to 24 based on these :

ii
19. List the total of custo mers ' order s grou ped by custo
mer (id).
20. List all custo mers (nam e) who have orde rs (use EXIS
TS).
21. List the sum of the totals of order s grou ped by
custo mer and state .

aa
22. List the sum of the totals of order s wher e this sum
is great er than $1000 grou ped by custo mer (id
state and order ed by state.
) an
23. List the custo mers (nam e) and their orde rs' detai ls.
24. List the custo mers (nam e) and the total amou nt of
all their orde rs.

Consider tables EMPL, Dept, SalaryGrade. The Emp l table


has alrea dy been liste d in earli er chapters S h
of tables SalaryGrade and Dept are being show n belo w : · c emn'
dh SALARYGRADE ( Lows al, High sal, Grad e)
Dept (Dep tno, DeptN ame, Loca tion)

Answ er Ques tions 25 and 26 on the basis of these table s


:
25. List the depa rtme nt name s and the num ber of their
empl oyee s.
26. List the empl oyee name s and the name of their depa
rtme nts.
pa

You might also like