Querying and
Operations Using SQL
> Aggregate Functions: Aggregate functions are also called multiple row functions. These functions work on a set of records
as a whole and return a single value For each column of the records an which the Function is applied.
> Aggregate Functions in SQL:
Function Description Example with Output
Returns the largest valve fromthe TyaqI> SELECT RAK (erie) FRON TWVENTORY?
MAx(column) | specified column output
ean
Returns the smallest value From the ayaal> TEETES) PRON TNT
MiN(column) | specified column. output
355205
Returns the average of the values inthe ayaa! TVGTPETSET FRO TH
AVG(column) | ecified column ovtpue
576091
Aetumns the sum of the valuesforthe —[aysal> SELECT SUMTPETEe) PRON INT
sum(column) | speciled column outpur
4608733
Returns the number of values nthe mysql> FF FOW ANCE
COUNT(column) specified column ignoring the NULL values. Ovtpue
eo1O | URNA |
Note: in this example, let us consider a '
MANAGER table having two attributes and | 1 | ASE
four records, 2 | eave.
3 | KAVITA
41 MULL
4 rows in aet (0.00 ace)
aysql> SELECT COUNT MIENNANE) FROM
HRIAGER;
Returns the number of records Ina table.
COUNT)
Note: In order to display the number of
records that matches a particular criter
inthe table, we have to use COUNT(*) with
WHERE clause,
1_row in set_{9.01_s00)
myaql> SELECT COUNTT*T PRON RARAT
cpu
count (*)
ot
L row in set [0.00 see)
> GROUP BY in SQL: We need to Fetch a group of rows on
the basis of common values in a column. This can be done
using a GROUP BY clause. It groups the rows together that
contain the same values in 2 specified column. We can
Use the aggregate Functions (COUNT.MAX, MIN, AVG and
SUM) to work on the grouped values. HAVING clause in
SQL Is used to specify conditions on the rows with GROUP
By clause,
ORDER By in SQL: The ORDER by clause Is used to sort
the result-set in ascending or descending order. it sorts
the records in ascending order by default, To sort the
records in descanding order, we use the DESC keyword.
Operations on Relations: We can perform certain
operations on relations like Union, Intersection and Set
Difference to merge the tuples oF two tables. These
three operations are binary operations as they work upon
two tables. These operations can anly be applied if both
Pe EE EE EE EEtthe relations have the same number of attributes and
corresponding attributes in both tables have the same
domain,
> UNION (\): This operation is used to combine the selected
rows of two tables ata time. IF some rows are the same in
both the tables, then the result of the UNION operation
will show thase rows only once.
AUB
> INTERSECT (7): INTERSECT operation is used to get the
‘common tuples from two tables and is represented by the
symbol“.
a8
» MINUS (-): This operation Is used to get tuples/rows
which are in the First table but not in the second table and
the operation is represented by the symbol ~ (MINUS).
rs 3
Difference of two sets
B-A
> Cartesian Product: Cartesian product operation combines
tuples from two relations. It results in all pairs of rows
from the two Input relations, regardless of wihether or
not they have the same values on common attributes. I Is
denoted as °K’. The cardinality of the resulting relation is,
calculated as the product of the cardinality of relations on,
which cartesian product Is applied.
> Carte
table is to be used in @ query, then we must specify the
table names by separating commas in the FROM clause
‘On execution of such a query, the DaMS(MySql) will First
apply cartesian product on specified tables to have @
single table.
> JOIN on Two Tables: JOIN operation combines tuples
From two tables on specified conditions. This is unlike
Product on Two Tables: When more than one
cartesian product, which make all possible combinations
of tuples. While using the JOIN clause of SQL, we specify
conditions on the related attributes of two tables within
the FROM clause.
> Following are some of the points to be considered while
applying JOIN operations on two or more relations:
> IF two tables are to be joined on equality condition on
the common attribute, Ze, using EQUI JOIN then one
may use JOIN with ON clause or NATURAL JOIN in
FROM clause. IF three tables are to be Joined on equality
condition, then two JOIN or NATURAL JOIN arerequired
> In general, N-1 joins are needed to combine N tables on
equality condition.
> With JOIN clause, we may use any relational operators
to combine tuples of two tables.
nen Practice Exercise
-@ Multiple choice Questions
QL Aggregate functions are also known as: [CBSE 2023}
a. Scalar Functions
bb. Single Row Functions
Multiple Row Functions,
4. Hybrid Functions
2. By default, ORDER BY clause lists the result in
™ order,
a. descending bany
c same d. ascending
3. Consider the following query:
ge 81 employes ORDER BY
polary
To display the salary from greater to smaller and
name in alphabetical order which of the following
options should be used?
a. Asc. Dese
b. Desc. Ase
. Descending. Ascending
4. ther b. or ¢
Q4, Select correct SQL query fram below to find the
temperature in increasing order of all cities.
a. SELECT ity PRON weather ORDER BY
b.seLuct city, tomporature FRON woathors
SELECT clty, tempecatuce FROM weather
ORDER BY cemperacure;
d.SBLeCT city, temperature PROM woathor
ORDER BY city?
Pe EE EE EE EEQs.
V6.
Q7.
8.
Q9.
Qo.
qu
que,
With SQL, how can you return the number of not
NULL records in the Project field of Students’ table?
a. SELECT
(Project) rudent;
b. seLecr INS (Proje Students
€ SELECT CLUS (*) FROM Studenta;
d.SeLECT counT(+) FROM Students;
Which of the following is not a valid aggregate
function in MYSQL? [case2023)
a. COUNT () b.sum ()
MAX () LEN ()
Ravisha has stored the records of all students of
her class in a MYSQL table. Suggest a suitable SQL
clause that she should use to display the names of
students in alphabetical order. [case 2023)
2. SORT BY b. AUGN BY
< GROUP BY ORDER BY
Raj, a Database Administrator, needs to display the
average pay of workers from those departments
which have more than five employees. He is
experiencing a problem while running the following
query:
SELECT DEPT, AVG (SAL) FROM EMP WHERE COUNT
()> 5 GROUP BY DEP
Which of the following is a correct query to perform
the given task? Icase sop 2023-24}
‘a SELECT DEPT. AVG (SAL) FROM EMP WHERE COUNT
(°) > 5 GROUP BY DEPT:
b. SELECT DEPT, AVG (SAL) FROM EMP HAVING
COUNT (?) > 5 GROUP BY DEPT,
¢ SELECT DEPT. AVG (SAL) FROM EMP GROUP By
DEPT WHERE COUNT (*) > 5:
d. SELECT DEPT, AVG (SAL) FROM EMP GROUP BY
DEPT HAVING COUNT (*) > 5:
The HAVING clause does which of the following?
a. Acts EXACTLY like a WHERE clause
b. Acts Uke @ WHERE clause but is used for columns
rather than groups
© Acts lke @ WHERE clause but Is used for groups
rather than rows
d. Acts Uke a WHERE clause but Is used for rows
rather than columns,
Aggregate functions can be used In the select list or
the clause of a select statement. They
cannot be used in a clause.
2. WHERE,HAVING ——_b. HAVING, WHERE
© GROUP BY. HAVING —d. GROUP BY, WHERE
SQL applies conditions on the groups through
. clause after groups have been formed.
a. GROUP BY b.WITH
cc WHERE d. HAVING
Which clause is used with “aggregate functions"?
a. GROUP BY be. SELECT
© WHERE d. Both a. and
Qs.
qua
QIs.
ais.
Quy,
16,
Qu.
Q20.
ga.
zz.
za.
ges.
gas.
What is the meaning of “HAVING” clause in SELECT
query?
2. To filter out the summary groups
bi. To filter aut the column groups
¢ To filter out the row and column values
d. None of the abave
WHERE and HAVING clauses
interchangeably in SELECT queries.
a. True b. False
© Only in views 4. With ORDER BY
Aw is a query that retrieves rows from
more than one table or view.
a. START b.END
<< JOIN d. Allof these
A condition given in a JOIN query Is referred to as,
can be used
2. JOIN in SQL
bi, JOIN Condition
¢ JOIN in SQL and Condition
None of the above
Which of the following is not a join type?
a. Empty join b. Natural jain
. Equi join 4. Right join
‘Which product is returned in a join query having no
Join condition?
2, Equl joln b. Cartesian
Botha. and b d, Natural
‘The cartesian product is also called
join,
2. Equi
Unrestricted
b. Natural
4. Restricted
In which type of join, the join condition contains an
equality operator?
2. Equi join b, Natural join
Left join 4. Right join
In which type of join, duplicate columns are there?
a. Equi join b. Natural
«Left join 4. Right join
In which type of Join, no duplicate columns are
there?
2. Equi joln b. Natural join
«. Loft join 4. Right join
With SELECT statement used for joins, the USING
subclause produces Join.
aEqu —b.Natural cleft Right
With SELECT statement used for joins, the ON
subclause produces. in.
aEqu — b.Natural cleft — d. Aight
What is the correct statement for describing the
UNION operation?
2. It combines the rows of any two different queries
iit combines the unique rows of two different
‘queries which have the same set of attributes In
the SELECT clause.
« Itcombines the rows of two different queries which
have the same condition in the WHERE clause.
4. It gives the cartesian product of the results of any
two queries,
Pe EE EEEQ26.
Qzz.
Q32.
933.
934,
938.
936.
ev
What is the correct statement for describing the
INTERSECT operation?
a. It returns the common values from the results of
any two different queries
bit returns the common rows of two different
Queries which have the same set of attributes In
the SELECT clause,
lt returns the common rows of two different
queries which have the same condition in the
WHERE clause.
d. None of the above
What is the correct statement for describing the
EXCEPT operation?
2. Itexcludes all the rows present in both the queries,
bit includes the rows of the second query but
excludes the results of the first query.
C Itincludes the rows of the first query but excludes
the results of the second query.
d. It includes all the rows of both queries but removes
duplicates,
What Is the other nama of MINUS operator?
2. UNION bb. UNION ALL.
EXCEPT d. INTERSECT
Fill in the Blanks type Questions y
To sort the rows of the result table, the
clause Is specified.
Columns can be sorted in descending sequence by
using the SQL keyword
The SQL built-in function
values in numeric columns.
‘The SQL built-in function .. computes
the average of values in numaric columns.
totals
The SQL built-in fuNCtION snimnmnnnee ObtaINS
the largest value In a numeric column,
The SQL built-in function . . obtains
the smallest value In 2 numeric column,
The SQL buitt-in function... . computes
the number of rows in a table.
‘The SELECT clause. .isused to collect
those rows that have the same value in a specified
column,
Assertion & Reason Type Questions y
Directions (Q. Nos. 37-40): In the questions given
below, there are two statements marked as Assertion
(A) and Reason (R). Read the statements and choose the
correct option
a. Both Assertion (A) and Reason (R) are true and
Reason (Ri) isthe correct explanation of Assertion (A).
b. Both Assertion (A) and Reason (A) are true,
but Reason (R) is not the correct explanation of
‘Assertion (A).
Assertion (A) Is true, but Reason (fi) is false
4d. Assertion (A) is false, but Reason (R) Is true
038. Assertion (A):
Q37. Assertion (A): JOIN operation combines tuples
from two tables on specified conditions. This is
unlike cartesian product, which make all possible
combinations of tuples.
Reason (R): While using the JOIN clause of SQL, we
specify conditions on the related attributes of two
tables within the FROM clause.
Cartesian product operation
combines tuples fram two relations. It results
in all pairs of rows from the two input relations,
regardless of whether or not they have the same
values on common attributes. It is denoted asx.
Reason (R): UNION operation is used to get the
common tuples from two tables and is represented
by the symbol U.
Q.39. Assertion (A): The cardinality of the resulting
relation is calculated as the sum of the cardinality
of relations on which cartesian product is applied.
Reason (R): With JOIN clause, we may use any
relational operators to combine tuples of two
tables.
40. Assertion (A): Aggregate functions are also called
multiple row functions. These functions work on.
a set of records as a whole and return a single
value for each column of the records on which the
function is applied.
Reason (R): If two tables are to be joined on
equality condition on the common attribute, then
‘one may use JOIN with ON clause or NATURALJOIN
in FROM clause.
Answers *
1-2) 3) 48) 8)
6) 2@) Blo) (1H)
Md) (Ba) Ho) TLL)
16.6) 1%) lb) 19. (6) 20.60)
Zu(e)— 22.(b) 23. (d) 24. (a) 25. (b)
26.(0) 22.) 28. (0)
29,0RDERBY 30, DESC
31.SUM 32. AVG
33. MAK 34, MIN
35. COUNT 36. GROUP BY
37(3) 38. (c) 39. (0) 40. (b)
<) Case Study Based Questions w
Case Study 1
Following questions are based on these tables:
Table: BOOK INFORMATION Table: SALES
Column Name Column Name
BOOK 1D STORED
BOOK TIME ‘SALES_DATE
PRICE SALES_AMOUNT
Pe EE EE EEE EEETable: EXAM_RESULTS
‘STUID| FNAME [LNAME [EXAM ID] EXAM SCORE
10 | LAURA |ivncH 1 30.
no _| Laura _|ivncH z 5
a1_| crac |erown [1 78
at_| Grace |prown [2 72
2 JaY__packson| 1 95
2 JAy__ackson| 2 32
73_| WiLUaM [BISHOP 1 70
73 | wiwuam faisHop [2 100
14_| CHARLES [PRADA 2 5
QL. Which SQL statement allows you to find
the highest price from the table BOOK_
INFORMATION?
a, SELBC? BOOK_1D, BOOK_TIT
IPRICE) FRON BOOK
b. senecr MAX(PRICE) FROM BOOK
TnIFORMATION;
sp MAK (PRICE) PROM BOOK
THIEORBIATION)
d. SELECT PRICE FRCD BOOK_INFORAATION
RDER BY PRICE OBSCr
Q2. Which SQL statement lets you find the SALES
‘AMOUNT for each store?
a. SELECT STORE_fD, SUM(SALES_AMOUNT)
on SALES:
b. SELECT STORE_ID, SUM(SALES_AMOUNTY
ROM SALES ORDER BY STORE ID;
c "7 STORE_ID, SUN(SALES_AMOUNT)
SALES GROUP GY STORE_TD;
d "P STORE_ID, SUM(SALBS_AMOUNT)
enc
SALES HAVING UNIQUE STORE
Which SQL statement lets you list all stores
whose total SALES AMOUNT is over 5000?
*T STORE_10, SUN SALES_ANOUNT)
LES GROUP BY STORE_1
HAVING SUM (SALES_AMOUNT) > 50007
LES_ AMOUNT)
"ORE_ID HAVING
Qs.
eROM
FROM SALES GROUP BY 3
SALES_AMOUNT > S000
"P STORE,[D, SUM (9ALES_ANOUNT)
ROM SALES WHERE SUM (SALES_AMOUNT)
> 5000 GROUP BY STO
EO? §TORE_ID, Sut
SALES WHERE
ior
LES_AMOUNT)
SALES_ANOUNT >
eROM
5000 GROUP BY STORE 1Dr
Q4, Which SQL statement lets you find the total
umber of stores in the SALES table?
8, SELECT CONT (STORE_30) FROM SALES)
b, seuecr comrioraTiic? —sToRR_IDy
EROH SALES)
OLBTINCT STORE_10 FRO!
Q5. Which SQL statement allows you to find the
total SALES AMOUNT for STORE ID 25 and
the total SALES AMOUNT for STORE ID 45?
a, SELECT STORE_10, SUM(SALES_AKOUNT)
PROM SALES
WHERE STORE_ID IN (25, 45) GROUP BY
STORE,
b. SELECT STORE_1D, SUM(SALES_ANDUNT!
PROM SALES
GROUP BY STORE_ID HAVING STO!
Te (25, 45);
© SELECT STORE_ID, SUN(SALES_aHOUNT,
PROM SALES WHERE STORE ID IN (25,
45)
d. SELECT STORE_1D, SUM(SALES_AWOUNT)
_ED = 25 AND
STORE_ID = 45 GROUP BY STORE_10)
PROM 5:
WHERE 9708
Answers +
1 (a)
Case
2 30) 40 5)
Study 2
‘A Fashion Store MyStore is considering to
maintain database of their customers in SQL to
store the data, As a Database Administrator Hina
has decided that
Name of the database: MyStore
Name of the table: Customer
‘Auributes of the tables: Ace_No-Numeric, Cust_
Name-Character 25, Cust_City - Character 25,
Cust_Phone-Character 11, Open_Bal-Numeric
‘Table: Customer.
‘Acc_No ]eust_Nome] Cust_City | Cust_Phone [Opon_Bal
TO0I_[Ohechnech| Aabala |S7I0557614| 10000
7902 | Sanya | Patna [e23sas2a3] 15000
T003_| oe [New celni[osTases7e] 13000
yo0d | Hetnal New cerhifoszas0s0s3] 12000
700s | Tahaan [| Agra [os0ae7e798] 19000
QL. With reference to the above given table, give
query for generating following output:
Cust_Name
‘Chashneah
Tehaaa
&. SELECT Nama FROM Customer WHERE
Open_bal < 20000
b. SELECT Namo FROM Cuvtoner mHERE
Cust_Chty LLke ‘wat;
© SELECT Cust_Meme FROM Cuetomee
WHERE Cust_Cley Like ‘wa';
d. SELECT cuat_Name FROM Cuscower
WHERE Cust Now ke ‘au!
Pee EE EE EEEQ2. Give the output of
SELECT Name, Open_Bal ROM
Customer ORDER BY
Case Study 3
Consider the below two tubles for reference and
answer the following questions:
3. Pranay has given the following command to
obtain Highest Opening Balance of each City
Select MAX (Open _Bal) from Customer where
GROUP BY Cust.ci
but he is not getting the desired result. Help
hhim by writing the correct command.
a SELECT NAX(Open_Be}) GROUP BY
citys
b. SELECT MAX(Open_Ba1) FROM Customer
whore GROUP BY Cust_City;
@ T Cust_city, MAX (Open_gal)
avower GROUP AY Cust citys
MAX (Open_al) FROM Cus toner
4. Help Pranay find the total number of records
HAVING open_bal between 15000 to 20000
by selecting the right command.
@ SELECT total FROM customer KAVING
open_bal between 13000 and 200001
b. SELECT COUNT(*) FROM customoc WHERE
open_bal BETHEEN 15000 to 2000!
© SELECT COUNT(*} FROM custoner
WERE openbal betwean 15000 and
20000
d. SeLECT COUNT(*) FROM customer
ORDER BY open_bals
QS. Choose the correct command to display the
first two letters of each customer’s name.
2 SULECT right (cust_nana, 2) PROM
customert
b. SELECT lege (cuat_nane, 2) FROM
© SELWer right (oust_namo, 0, 2) PROM
4. SuLUCE Lefe(oust_nane, 2) eROM
Answers
ue) 2@) 32 4M 5.0)
b.
[cust_Name [Open_Bal] >: [cust_Name]Open_Bal Table-EmployeeDetails
Dhaahaeah [10000 Tehean [19000
Rina Sanya [i000 Empld [FullName] Managerid [Date of Joining] City
oo T3000 wai [Jenn [32 | su@rz0%¢ | Teron
fueinat [22000 =
iranaean|inoon saa | water [996 | soins | California
Write
[cust_Name[Open_Gal] 4: [cust_Name]Open_Bal 21 | Ruldeen | 676 | 27172016 |NewDetn
Dravkmesn] 10000 Bhaatwesh| 10000 ana
Froneaa [18000 Senve [#5000 Table-EmployeeSalary
fioe T3000 Soe Empld_| Project | _Selary | Variable
farinay | ¥2000 fieinar Ta PL 3000 500
ye [#5000 Fanaar Bat P2 70000 1000
a2 Pi 32000 °
Q1. Write an SQL query to fetch the Empld and
FullName of all the employees working under
Manager with Id -'986.
Q2. Write an SQL query to fetch the different projects
available from the EmployeeSalary table.
3. Write an SQL query to fetch the count of
employees working in project P:
Q4. Write an SQL query to find the maximum,
minimum and average salary of the employees.
QS. Write an SQL query to find the employee Id
whose salary lies in the range of 9000 and
15000.
Answers -
1 seLeCT mpi, FulINamo FROM
Enployeovetails WHERE Hanagertd=986)
2, SELECT DISTINCT (Project] FROM
EmpLoyaesal
3, SELECT COUNT(*) RON GnployaeSolary
WHERE Project = ‘PL’;
4, SELECT MAX (Sal.
HM (Salary),
AVG(Salary)
FROW Bmployes Salary:
5. SULUCT Empid, Salary
FROW Employee Salary
WHERE Salary BETWEEN 9000 and 13000
Case Study 4
Consider the below two tables for reference and
answer the following questions
Table-EmployeeDetails
Empla [FullName] Managerld [Date of oining] city
i2i | jonn | 321 | 34/01/2014 | Toronto
Snow
321 Walter | 986 | 30/03/7015 | California
White
421 | Kuldeep | 676 | 27/li/z016 |New Deni
Rana
Pe EE EE EE EETablo-EmployeeSalary
Emplé | Project | Salary | Variable
12 Pi 3000 500
324 P2 10000 1000
a1 PL 12000 0
QL Write an SQL query to fetch those employees
who live in Toronto and work under manager
with Managerld ~ 321.
Q2. Write an SQL query to fetch all the employees
‘who either live in California or work under a
‘manager with Managerld - 986.
Q.3. Write an SQL query to fetch all those employees
‘who work on Project other than P1.
(Q4. Write an SQL query to display the total salary of
each employee adding the Salary with Variable
value.
Q5. Write an SQL query to fetch the employees
‘whose name begins with any two characters,
followed by a text “hn” and ending with any
sequence of characters.
Answers
1. senect enptd, City, Managectd PRON
mployeaDotailo
WHERE City=*Poronto’ AND NanageeTde "321"
2 SELECT Enpd, City, ManagerId PROM
Bnployeadotaile
WHERE City=‘Californta’ OR Managorfde'986+
3, SELECT BmpTd FRON Employeesalar
WHERE NOT Project = *PL":
4 SELect eupid, Salary+varlable as
Totalgalary
PRON Employeesalary:
5. SeLEcT FuliNome FROM Emp.
WHERE PullNane LEKE*
yyeedetalls
hn’?
~ Very Short Answer tupe Questions
QL What is the use of ORDER BY clause?
‘Ans. ORDER BY clause used to arrange the result set of
‘query in ascending or descending order in order
of single or multiple columns. ORDER BY clause Is,
Used In conjunction with SELECT statement.
Q2. What is the defautt sort order of ORDER BY clause?
‘Ans. The OROER BY sorts the recards in ascending arder
by default.
8. What is the use of GROUP BY clause?
‘Ans. The GROUP BY clause combines all thase records
that have Identical value In_a particular field or a
{Eroup of Fields.
a4.
Ans.
as.
Ans.
6.
Ans.
Q7.
Ans.
ge.
Ans.
Qs.
Ans,
quo.
Ans.
Qu.
Ans,
Que,
Ans.
Qs.
Ans.
In SQL, name the clause that is used to display the
tuples in ascending order of an attribute.
[cose sop 2020)
ORDER BY
Which clause is used with a SELECT command in
‘SQL to display the records in ascending order of an
attribute?
ORDER BY
The SQL SELECT provides clauses for sorting data
and for summarising results. Write the names of
clauses for these.
The ORDER BY clause of SQL SELECT statement
allows to sort the data of result set. The GROUP BY
clause of SQL SELECT statement allows to create
summarised results of grouped data from table
What Is the significance of GROUP BY clause In a
SQL query?
The GROUP BY clause combines all those records
that have identical values in a particular fleld or
2 Broup of flelds. This grouping results into one
summary record per group if group-functions are
used with It
What is the difference between a WHERE clause
and a HAVING clause of SQL SELECT statement?
The difference between WHERE and HAVING clause
's that WHERE conditions are applicable on individual
rows whereas HAVING conditions are applicable on
‘groups as formed by GROUP BY clause.
Write a query to display the Sum, Average, Highest
and Lowest salary of the employees.
ayoql > Seve (aly, ave
x (a1), HIN (9a)
‘ROM empls
Write a query to display the Sum, Average, Highest
and Lowest salary of the employees grouped by
department number.
(oat,
myagl > SELECT SUM (sal), AVG (al),
nx (9a), MIN (eal)
FROM ompl GROUP BY deptnoy
Which SQL aggregate function is used to COUNT.
ALL records of a table?
COUNT(*)
Write query to display the number of employees
with same job.
wyaqh>seLEct
[case 2020)
COUNT (*) "No_of Bape”, Job
FROM emp! GROUP BY job)
Write a query that counts the number of
salespeople registering orders for each day. (If a
salesperson has more than one order on a given
day, he or she should be counted only once).
seLect ord_date, STING
aalesnan_code) FROM orders
Gnoue BY ord_datay
count (0)
Pe EE EEE EEEqu.
Ans.
Qs,
Ans.
16.
Ans.
Qu.
Qs.
Ans.
Qs.
20.
Ans.
gal.
Ans.
Define an equi Join. What is non-equi join?
Equi Join: Join in which tables are compared for
equality
‘Non-equl Join: Join in which tables are compared for
pon-equality,
What is join?
A SQL Join Is an query used within the SQL
Structured Query Language) to combine data from
‘nuo table on the basis of a common field
How many different types of joins can you create
in MySQL?
We can create following joins in MySQL
(i) Cross join (iv) Inner join
(i) Natural join (v) Left jain
{l) Equijoin (vi) Right join
There are multiple ways to create cartesian
product of two tables in MySQL. Describe them.
There are following ways to create cartesian product
() SELECT * CRON cIuble 1> CROSS OMI cTuble 25;
(I) SELECT + FROM
, 4000.
mysql >SELECT MAX (sa) -MIN(sal) “Difference”
FROM empl
OUP BY DeptNo
HAVING MAX (a1) > 4000:
Write a query to display the Sum, Average, Highest
and Lowest salary of the employees grouped by
department number and sub-grouped by job.
LECT SUM eal], AVG
1, MIN (sa!
FROM empl
GROUP BY DeptNo, jobs
Gopi Krishna is using a table Employee, It has the
following columns:
Code, Name, Salary, Deptcode
He wants to display maximum salary department
wise, He wrote the following command:
SELECT Deptcode, Max (Salary) FROM Employee;
But he did not get the desired result.
Rewrite the above query with necessary changes to
help him got the desired output.
ELECT DoptCodo, MAX (Salary)
FROM Employee
GROUP BY Deptcode;
Shanya Khanna Is using a table Employee. It has
the following columns:
‘Admno, Name, Agg, Stream
[column Agg contains Aggregate marks}
She wants to display highest Agg obtained in each
Stream.
She wrote the following statement:
SELECT Stream, MAX (Ag) FROM Employee:
But she did not get the desired result.
Rewrite the above query with necessary changes to
help her get the desired output.
SELECT Stroam, MAX (Aga)
PRON Employee
GROUP BY Streams
Write a query on the customers table that will find
the highest rating in each city, Put the output in
this form: For the city (city), the highest rating Is:
(rating).
SELECT ‘For the
sey’, city, ‘the highest
rating 49:1, MAX (rating!
FRON custonera
GROUP BY aity:
QL. What Is a join? How Is natural join different from
‘an equi join?
‘Ans. Join: A join is @ query that combines rows fri
or more tables based on a condition
Natural Join: Join that consists of only one of the
Identical columns, coming from joined tables
Equi Join: Join in which tables are compared for
equality.
112. What is a table alias? What is the purpose of table
alias?
‘Ans. Table Allas: A Table Alias Is a temporary label glven
along with table name in FROM clause
‘The purpose of table alias is To cut down on the
amount of typing required in our queries we can use
aliases for table names In the SELECT and WHERE
clauses.
For Example: if we wanted to use the abbreviation
TT for the table’ in your query all we need to is tell
MySQL that ‘able’ will be referenced by In the
FROM clause.
How is a left join different from a natural join?
Give example.
Left Join: A form of join where all the rows (even
non-matching ones) from the frst _table are
seturned in the result.
Example: select * from Student LEFT Joln
0
Qs.
Ans.
ool on Student xo! ol.
Natural Join: & join where identical column from
both tables Is shown just one in the result
Example: Solect * ¢rom Student atueal Join
pools
How is a cross Join different from natural Join?
Give example.
‘Ans, Cross Jain: A form of join that produces all possible
jons of row from two tables
Qu.
cROss JOIN
Natural Join: A join where Identical column from
both tables Is shown just one in the result.
Example: select * from Student Watural Jota
What Is the difference between ON and USING
JOIN-clauses?
Difference between ON and USING sub-clauses of
JOIN clause of SELECT is that ON clause requires
2 complete join-condition whereas USING clause
requires just the name of a jain Field
ledge BOOSTER
AR, USING sub clauses produces natural joln whereas ON
‘S? clause produces equi join.
Q16. Define the following: (i) Cross join (i) Left join.
Ans. (i) Cross Join: A form of join that produces all
possible combinations of row from two tables
(i) Left Join: A form of join where all the rows (even
non-matching ones) from the first table are
returned in the result
Qs.
Ans.
Pee EE EEE EEEQU. Define the foltowing:
(D) Natural join (i) Equi join
‘Ans. (i) Natural Join: A join where identical column from
both tables is shown just one In the result,
(i) Equi join: & oin based on equality of a common
Field of two tables and in which the identical
column is shawn twice.
Q.18. What will be the join of following two relations?
R1 (A, 8,0): R2 (B,D, E):
ATs fe BpOTE
a 1 |p |S
713 LY a a
R13 [2 re
ciTzfy¥ 7Lal[T
m{1|z
N17 Ty
Ans. Equl jain Natural Join
ATS[c[s]O]e “Alel[c]ole
ifityiifets: 2 S
tilzty¥[ztalr T
Mii{z[ilol[s 5
Nivtv[7lTatr WW T
19. Given two tables:
Employee Pay Table
‘employee_id employee_id
leet_name — ealary
firet_nume department.
middle_name eupervisor
marital_etatus
Find out the salary taken by all SMITH ie.,all those
who have their Last nama as SMITH.
Ans. SELECT
ep.ealary
FRON employee table, employee pay
e.omployee_id, —@.1a0t_name,
WHERE e.employes Id ~ ep.eaployes td
AND o.laet_namo © ‘SuITH"y
Write MySQL queries for the following
() To display ttem_Code, Item Name and
corresponding Brand_Name of those Items,
whose Price is between 20000 and 40000
(both values inclusive).
(ii) To display Item_Code, Price and Brand_Name of
the item, which has Item_Name as “Computer’
Ans, (i) set
Nawe
MM Teen I,
ECT I.ttem Code, Etem Name, Brand
and &
WHERE I, Item Code = &, Item Code
AND Price BETWEEN 2000
Ws
PROM Item 1, Brand B
AND 40000;
ECT T.Ttem_code, Price, Brandvewe
WHERE I.Teom_Code = B.1tem Code
AND Item_Nane -
Q22. Ina Database School there are two tables Member
and Division as shown below:
Table: Member
Empid | Name Pay Divno
1001 | Shankhye | 34000 10
1003 | Ridhima | 32000 50
1002 | Sunish | 45000 20
Table: Division
Divno Divname Location
10 Media TFO2
20 Dance FFO2
30 Production SFOv
(i) Identify the foreign key in the table Member.
What output, you will get, when an equi
join query is executed to get the NAME from
Member Table and corresponding from Division
G20. Write query to produce all the detalls onty for table?
female pets records of pet and event tables Ans. (i) Olvno
{eine 0 — wae] owe
Ans. suet: Shankiya Media
FROM pet
JOT event Sunish Dance
us2N6 (name)
WHERE sox © *8*s
2. Ina Database there are two tables: @ Short Answer Tyoe-t! Questions
Table: ITEM Table: BRAND Q.1. What are aggregate functions? What are their use?
Tom. ] Tem Name] Price ~Teem—] Brand Give some examples.
fois Code | Namo ans. Aggregate functions work with multiple rows of
111 [Relrigerston | Soomn ast Te table a a time and return single aggregate value
zaz_[ Television [75,000 222] Sony it is basleally used to produce summarised data
35 | computer [#2000 333 | ACL irccaurabeine
443[Weshing |"27,000 aaa] FB Basically, there are five aggregate functions
Mastin COUNT 0. AVG 0. MIN Q, MAX () and SUM 0.
Pe EE EEE EEEExamples
SUN (Total) FROM
(il) What SQL statement do we use to print out the
record of all students whose last name starts
with 'L?
AVG (seks) FROM STUDENT,
T DeptNo, MAX | Ans. ()) SELECT AVG(EXAM_SCORE) ROK EXNY
cnc ep RESULTS GROUP BY EXAM_LD HAVING EXAH
GROUP BY DepeNor wes
Q2. Answer the following questions: (i) sececr exaN_10, couvr (orstrNc
Following questions are based on these tables: 20) PROM SxaHH RESULTS GROUP SY BAK
Table: BOOK INFORMATION Table: SALES 10;
aaa aa Calum naa (W) sevect + FRc ExaM_RESULTS WHERE LHAKE
u .
BOOK1D STORE_ID Q3. Arelation vehicles is given below:
BOOK TIME SALES_DATE Vino | Te | Company | Price | Qty
PRICE SALES AMOUNT ‘awi2s | wagon | Maruti | 250000 | 25
Jo0a3 | Jeep | Mahindra | 4000000 | 1s
‘Table: EXAM_RESULTS $9090 suv | Mitsubishi | 2500000 | 18
STU_ID] FNAME | LNAME [EXAM_ID] EXAM_SCORE ‘m0as2 | Minivan | Datsun | 1500000 | 26
70 _| caura | NCH | 1 30 warso | suv [Maruti | 2500000 | 18
70_| cauRA | UNCH | 2 5 2409 | winivan | Mahindra | 350000 | 15
v7_| Grace [erown | 1 78 Write SQL commands to:
11_| Grace [erown | 2 7m (i) Display the average price of each type of
fe | aav_[asensonl on oe vehicle having quantity more than 20.
(i) Count the type of vehicles manufactured by
72_| aay _|uaceson] 2 32 een
13 [wutam| eishor [1 70 (il) Display the total price of all the types of
13 |wiiam] eisHop | 2 700 vehicles. [case s9p 2020-21]
ya Tonartes| Praoa | 2 es Ans. ()) SELECT Type, avg (Price) PROM veh
() What SQL statement do we use to find the
average exam score for EXAM ID = 17
Which SQL statement do we use to find out how
many students took each exam?
OUP B
‘ype HAV
ea
(i) setecr Company, COUNT (distinct
FROM Vehicle GROUP BY Comp
1 Type, SUM (Price +
Vohicke GROUP BY Typo:
> 20
yt
(il):
Q4, Write the output of the SQL queries (i) to (ii) based on the relations Teacher and Posting given below:
Table: Teacher
To Name Age Department | Date_ofjoin | Salary | Gender
T Jugal 34 ComputerSe | 10/01/2017 72000 ™
2 Sharmila 3 History 2470372008 20000 F
3 Sandeep cy Mathematics | 12/12/2016 30000 ™
4 Sangeeta 35 History o1yo72015 "40000 F
5 Rakesh a Mathematics | 05/03/2007 25000 ™
6 Shyam 30 History 27/06/2008 30000 ™
7 ShivOm a ComputerSe [25/02/2017 21000 ™
8 Shalakha 3 Mathematics | 31/07/2018 20000 FTable: POSTING
PID Department Place
7 History Agra
2 Mathematics Raipur
3 | Computerscience | _ delhi
() Setzcr Departmant, count (*), FROM
‘Teacher GROUP BY Department,
(i) Setzer MAX(Date_of Join), MIN(Date_
of_Join) FROM Teacher;
(il) setzcr Teacher.nama, Teacher.Departnent,
Posting.Place FROM Teacher,
Posting WHERE Teacher.Departnent =
Posting. Department AND
Posting. Place = “Delhi’’.
[case sop 2020-21)
Ans. (i) Department | _COUNT(*)
History 3
Computer Science 2
Mathematles 3
(il), MAX-3107/2018 or 2018/07/31
MIN-05/09/2007 or 2007/09/05
(ii) Name] Department | Place
Jugal___| Computerse [Delhi
QS. Write the output (iii) for the following SQL
commands.
Table : FASHION
1 | Product | Price | Qty
Fou | Kajal aE)
Fo2__[Foundation [2100 [15
F03__[Night Cream [1700 _ | 20
Foa__[DayCream [1400 [10
Fos [Shampoo [1200 [25
F06 [Lipstick es0__([32
(i) SELECT COUNT (Product) FROM FASHION;
(il) SELECT SUM (Price Qty) FROM FASHION WHERE
Products “Night Cream";
(ili) SELECT LEFT (Product, 4) FROM FASHION
WHERE Price > 1500; [case 2023)
COUNT (Product)
6
‘SUM (Price * Qy)
34000
LEFT (Product 4)
Foun
Nigh
Q6. Find the output of the following SQL. queries:
() SELECT SUBSTR ("CLIMATE CHANGE", 4,4);
(i) SELECT UCASE(RIGHT ("Pollution’, 3) );
(iii) SELECT LENGTH ("HAPPY") + 3; (Ces 2023]
Ans. ()
‘SUBSTR ('CLIMATE CHANGE’, 4, 4)
MATE
w
UCASE (RIGHT (Pollution’, 3))
TON
(ui)
LENGTH (HAPPY) = 3
8
Q7. Consider the following table GAMES. Write SQL
commands for the following statements:
Table: GAMES
GCode] GameName] Type [Number] Prize] Schedule
IMoney| Date
101 |carromBoard| indoor | 2 | $000|23-Jan-2004,
102 | Badminton Joutdoor| 2 | 12000]12-Dec2003
103 | Table Tennis | indoor | 4 | 8000]14-Feb-2004,
108 | chess | indoor] 2 | 9000] 01-Jan-2004,
108 | LawnTennis outdoor] 4 _| 25000/19-Mar-2004
() To display the name of all GAMES with their
Codes.
(ll) To display details of those GAMES which are
having PrizeMoney more than 7000.
(lil) To display the content of the GAMES table in
ascending order of ScheduleDate.
Ans. (i) seLecr Code PROM GAMES:
(i) seeer © eRow
WHERE PrizeNoney >
(li) seLecr * EROW GAMES
ORDER BY Scheduledate
QB. Consider the following tables CABHUB and
CUSTOMER. Write SQL commands for the following
statements.
7000)
Table: CABHUB
Veode] VehicleName| Make | Colour [Capacity] Charges
100 [innova | Toyota [WHITE 7 15
102 xa suzuki | swue | 4 4
10a | CClass |mercedes| RED | 4 35
10s | Astor | suzuki |ware} 3 4
108 | indigo Tata_|suver| 3 2
Table: CUSTOMER
CCode Name Veode
7 Hemant Sahu 107
2 RajLal 108
3 Feroza shah 105
4 Ketan Ohal 104
Pe EE EE EE EE() To display the names of all the white colored
vehicles.
(i) To display name of vehicle, make and capacity
of vehicles in ascending order of their seating
capacity.
(iil) To display the highest charges at which a
Ans. (i) 3
(i) wax (Scheu ledate! NIN (schadulebate!
19-twar-04 12-Dee-03
CU) ram ACTIVITYNANE
Ravinder Diecuse Throw
ERROR
SQL query is not read properly or there may be error in
finding the output correctly.
10. Consider the following tables GAMES and PLAYER
and answer the following parts of this question:
ww) (chaeges)
PROM CABHUB: Table: GAMES
9. Consider the following tables ACTIVITY and COACH Prize | Schedule
‘and answer the following parts of this question: SC°de|GameName| Type |Numberloney! Date
Table: ACTIVITY 701 [Carrom Board] indoor | 2 | 5000 [23-Jan-2004
‘Acode] Activity |Stadium)Participants] Prize [Schedule 102 | Badminton loutdoo| 2 | 12000 12-0ec2003
Name Num | Money| ate
spar way | Sr “eT iv000 [aadanae 103 | Table Tennis indoor | 4 | 000 14-Feb-2004
100.4 | Annex 10s | chess | indoor} 2 | 9000 Jor-ten-2004
7002 | High | Star 10] 12000 /12-Dec03 108 | Lawn Tennis Joutdoor] 4 | 25000 |19-mar2004
Jump _| annex
1003 [shot Put] Super | 12 | 8000 [i4-Feb-0a Table: PLAYER
—— Pcode Name GCode
7005 | Long | Star 72 | 3000 [orJanoa ST Kibiaivesd Tai
Jump_| Annex L
7008 | Biscuss | Super | 10 | 15000 |19-Maroa 2. pau sail ioe.
Throw | Power 3 “atin 101
‘Table: COACH 4 Nazneen 103
Pode Name ‘Acode Give the output of the following SOL queries:
4 Ahmad Hussain 1001 (i) SELECT COUNT (DISTINCT Number) FROM
2 Ravinder To08 nnes ;
3 Janis 100% (il) seRcY MAX (Scheduiedate) ,
4 Naaz 7003 miu (ScheduleDate) FROM GAMES;
Give the output of the following SQL queries:
() sexucr cour (orsTINcT ParticipantaNun)
FROM ACTIVITY)
(li) Senger MAX (SchoduleDate) , MIN (Schodule
(il) Serger Name,GaneName FROM GANES G,
PLAYER P
WHERE G. Gcode = PB
PrizeMoney > 10000;
coda AND @.
Date) FROM ACTIVITY: ans (2
Oe naan nme hobkehtyuenetrnow aeraaTE (i) MAX (ScheduleDate) _MIN{ScheduleDate)
WERE A. Roode = C.Acode AND. Participanta 19-Mar-2008 12-Dec-2003
Num = 10) (li) Ravi Sahat Lawn Teanis
QIL Consider the tables Patient given below and write SOL commands.
Table: Patient
Patlontid Name city Phone Dateofadm Department
1000001 Ritvik Garg Delhi 69476213 2021-12-10 Surgery
1000002 Rahil Arora ‘Mumbai 36546321 2022-01-08 Medicine
1000003 ‘Mahak Bhatt Delhi 68421879 2022-02-02 Cardiology
1000004 Soumik Rao Delhi 26543266 2022-01-11 Medicine
7000005 ‘Suresh Sood Bengaluru 65432442 2021-03-09 ‘Surgery
Pe EE EEE EEEWrite SQL queries for the following:
() Display the details of all patients who were
admitted in January.
(li) Count the total number of patients from Del
(ii) Display the last 2 digits of the Patientid of all
(ii) Name Pay
Radhe Shyam — 26000
Chander Nath 12000
Q13. Consider the following tables EMPLOYEE and
SALGRADE and answer the following parts of this
patients from Surgery Department. [case 2023) question:
Ans. ())SELECT + FROM Patient WHERE Y Table: EMPLOYEE
Soocooeete) is coe name [ves —feoraoe| bos | bon
(i) seuect count (+) FROW Patient WHERE ‘Abdul 23a%ee Fadenc
city = “oELur"; 101 | ahmed | EXECUTIVE | S03 | “2003 | 1980
sack Mune oeneee ssceaeeye 02 [gt] weamer [soe | 2 Pa
Q12. Consider the following tables WORKER and ohn Ken RECEPTIONIST] S03 | Da-Jun=|24-Fab-
PAYLEVEL and answer the following parts of this 193 2009 | 1983,
question: Nazar 11-Aug- |03-Mar-
Table: WORKER 105 | ameen| © | S02 | "2006 | t998
Econe| wane] oesic puevel] var [woe ar [ mya] —ceo—| Sor} a0ec Hoc
TT] tate bipeven} PODT | sem aun 5 aioe | 3a
Shem an [aa aE RSE
Touma Ope] PE [zee wt
hg Feb scnabe] salary Wea
Sa] Faas [oper] POO | es Teo sor [sexo a
2009 _| 1983 ‘S02 32000 12000
5 [oem rec] PR [2h Par
Ahmed 2006 | 1964 0s 24000, eno
18 Sanya | Clerk 'P002 | 19-Dec- [09Jun- Glve the output of the following SQL queries:
2005 _| 1983 (i) SELECT COUNT (SGRADE), SGRADE FROM
Table: PAYLEVEL EMPLOYEE GROUP BY SGRADE.
PEVEC[ pv TAGWANGE” i} svbetnnoom on) mow aves
a To gency
pode 22000 ‘10000 WHERE £.SGRADE = 8.SGRADE AND B.BCODE
ross | too pe rane |
Give te euput ofthe folowing SOL aries: fms () COUNT ScRaDe
() senect count (PLEVEL), PLEVEL FROM 2 03
Sean eee ; 8
(ii) SELECT MAx(DOB) , MIN(DOJ) FROM WORKER; 1 sol
(iii) SeLwcr Namo, Pay PROM WORKER W, PAYLEVEL P (i 134an-1980 12-Feb-2010
few none erin mower (ae Bah?
fans. () 1000, 2003, 26002 fod armed 24009
(i) Jul987 13-Sep-2004 on
14. ven the allowing tbl
Table: CLUB
far ar amare [arr a
2 RAVINA 34 KARATE 20/01/1998 1200 e
3 KARAN 34 SQUASH 19/02/1998 2000 M
4 TARUN 33 BASKETBALL | 01/01/1998 1500 M.
s ZUBIN 36 ‘SWIMMING 12/01/1998 750 M
5 evan [36 | sing [-2ay7i9s6_| — ann F
7 ANKITA 39 SQUASH 20/02/1998 2200 FE
a eT F
9 KUSH a SWIMMING | 13/01/1998 900) M
10 SHAILYA, 37 BASKETBALL | 19/02/1998 1700 M.
Pe EE EE EE EEGive the output of following SQL statements: Name ES
() sexecr counr(orszicr seoRTs) FRX cit Supplierid
cau; ‘Country UnitPrice
Gi) SeLect MIN (Age) FROM CLUB WHERE Sox = eons
at (i) Consider the Orders and Customers tables given
above. Write an SQL query to list all customer
details (name, phone) along with order date.
ee (ii) Consider the Orders and Orderltems tables
fans. (i) COUNT (OISTINTSPORTS) given above. Write an SQL query to list order
details along with product ids and quantities.
(ii) seuecr ave(pay) FROM CLUB WHERE Sports
4 (ii) Consider the Orders, Orderltems and Products
w MINTAge) tables given above. Write a query to list all
ai orders with product names, quar and
prices, arranged orderld wise.
oe Ans. Name, Clty, Countey, Orderdate
1100.0 Customertd
QS. Given the following tables with their respective Customer.idp
column names: (Wseuecr orders. orderid,
PraductId, Quantity
‘ORDERS ‘ORDERITEMS FRON Orders, Ordertvema
Orderid ‘Orderid Ordertd = Order
jorderoabe Producti (i) si INTEGER, 0.0rderDato,
Customertd ‘Quantity came,
TotalAmount L.Quantity, P.uniePeLee
PROM Orders 0, Producte Py OrderTeans T
‘CUSTOMERS PRODUCTS: WUBRE 0. Ordorld = 1.0rderTa
Customerid Productld AND @, Productid = 1,Produottd
ORDER BY 0. Ordex 1d
Long Answer Type Questions y
QL Consider the following table Schooldata:
Table : Schooldata
‘Rdmne Name Grade ‘cub Marks Gender
20150001 ‘Sargam Singh w STEM 36 ‘Mle
yoia02i2 ‘Alok Kumar 10 SPACE 75 Male
70090234 Mohit Gour 1 SPACE a Mole
70130216 Romi Mall 10 READER 31 ‘Male
20190227 TTanwi Batra rn STEM 70 Female
20120200 ‘Nomita Ranjan 2 STEM ot Female
Write SQL queries for the following: Ans. ()SELECT Gender, avg (Wacko) — ERO®
(i) Display the average Marks secured by each oe ee
Gender. (i) sexect om (orks)
() Display the minimum Marks secured by the WHERE Conde 3 Oty .
aieis ee orsterin, (il) sexecr ciub, count (orstawer ciup'
(iii) Display the total number of students in each PROM Senooddaca GRSUE BY CARB UN
Club where number of students are more than 1, En
Or &
Display the maximum and minimum marks SELECT Gonder, NAX (Marko), MIN (Hark
tected by sach gander. PROM Schooldata GROUP BY Gender,
Pe EE EE EEE EEEQ2. Answer the following questions:
Database table empl
EMPNO | _ENAME J08 MGR | HIREDATE | SAL comm [| _DEPTNO
8369 SMITH CLERK ‘a902 | 1990-12-78 | 800.00 NULL 20
8499 ‘ANYA | SALESMAN | 8698 | 1991-0220 | 160000 | 300.00 30
521 seTH | salesman | 59a | 1991-0222 | 1250.00 | $00.00 30
8565 [MAHADEVAN] MANAGER | 8839 | 1997-08-02 | 798500 NULL 20
8654 MoMIN | SALESMAN | 698 | 1991-09-28 | 1250.00 | 1400.00 30
2698 BINA | MANAGER | 9839 | 1997-05-01 | _zas0.00 NULL 30
8839 AMIR | PRESIDENT | NULL | 1991-11-18 | 5000.00, NULL 10
Baa KuLbeeP | SALESMAN | a698 | 1997-09-08 | 1500.00 0.00 30
ag2__| SHIVANSH | MANAGER | 8839 | 1991-06-09 | 2450.00 NULL 10
8886 ANOOP. CLERK aga8 | 1993-01-12 | 1100.00 NULL 20
2888 scomt | ANALYST as66 | 1992-12-09 | 3000.00 NULL 20
900, JATIN CLERK 3698 | 1991-12-03 | 950.00 NULL 30
902 FAKIR | ANALYST ses | 1991-1203 | 3000.00 NULL 20
934 MITA CLERK paz | 1992-01-23 | 1300.00 NULL 10
() Calculate average salary of all employees listed
In table empl.
Q3. Ina Database, there are two tables given below:
Table: EMPLOYEE
2 eee)
#4 femcsnieccimenichenhirengl. EMPLOYEEID NAME SALES [JOBIO
‘ 1 SumirsiNHA [1100000102
(i) Count number of jobs in table empl. 2 ‘VUAY SINGH TOMAR | 1300000 | 101
(iv) How many distinct jobs are listed in table empl? ss "aga RaJpaL ——[vab0000 [103
(0) Display maximum salary from table empl fa MOHITRAMNANT [1250000102
Ans. () mysal > SELECT AVG (val) “Average” es SHAILIASINGH [1450000 | 103
ol avs Table: JOB
nia OBI JOBTITLE SALARY
Sn 707 President 700000
2075 9757) 102 Vice-President 725000
ro in 99 (0.02 nec 103_| Administration Assistant 30000
(i) ayaqi> seLecr comen(+) “Total” Tor} Recoanting Manager FO
OM emp 105 Accountant $5000
Tove 108 Sales Manager 60000
M Write SOL queries forthe following:
te net (0.00 eee) (i) To display employee ids, names of employees,
\ ou An wee (0.00 ec) . jb ids with corresponding job titles.
(i) ayeal> setecr courrjob) =sob count (ii) To display names of employees, sales and
ROM empl corresponding Job titles who have achleved
ob_ Count sales more than 1300000.
a (ii) To display names and corresponding job
titles of those employees who have ‘SINGH’
1 row in set (0.02 soo? (anywhere) in thelr names.
(Ww) ayeql> setect countiorstiNct (iv) Identity foreign key in the table EMPLOYEE.
net Joba” () Write SOL command to change the JOBID to
pli 4104 of the EMPLOYEE with ID as E4 in the
Dlatinct Job table ‘EMPLOYEE!
7 Ang. () SELECT EMPLOVEELO, ame, sMeLoveE
SOBID, JOBUITLE FROM EMPLOYEE NNTUIAL
Tow In gat (0,00 vec] Jorw Ov 0B:
( ayaqi> sexect MAK (eal) “Maximum (i) setEcr sinMe, sates, sourrrne exoM
EMBLOYEE, JOB WHERE eNBLOYEE.. 20810
Job.JOBID AND SALES> 13000001
(il) SELECT WAME, JOBTITLE FROM &
JOB HHERE EXPLOYEE. JOBIO = JOB.JOBID
AND MAKE DIKE "NSINGHS
(iv) goBrD
(V) UPDATE BHPLOYEE SEY JoBID ~ 104 wHuRE
EMPLOYEEID « "Ba";
Pee EE EE EEE4. Answer the questions based an following tables:
Table: Venuet Table: Venue2
Match_no | City Match no] city
z ELT L HOHALT
z MORALE z NGRLURU
z al si
q HOMBAT 4
5 BENGALOR 5 HORBAT
e CHENNAT é DELHT
T NGRLURD
6 rows in set (0.05 sec) 7 rows in sot (0.05 o0c)
(i) Write an SQL query to union cities from tables
venue and venue2.
(i) Write an SQL query to union cities from tables
venue and venue2.
Write an SQL query to union cities from tables
venue and venue2 containing all the rows.
(iv) Write an SQL query to get cities only in table
venue and not in table venue2.
(i
Write SQL queries for the following
() To display SalesmaniD, names of salesman,
0)
)
tiv)
w)
Ans. ()
) SELECT SALESMANTD,
LocationID with corresponding location
names.
To display names of salesman, sales and
corresponding location names who have
achieved Sales more than 1300000.
‘To display names of those salesman who have
“SINGH'in their names.
Identify Primary key in the table SALES. Give
reason for your choice.
Wirite SQL command to change the LocationID
to 104 of the Salesman with ID as $3 in the
table SALES.
Mane, LocaTrowD,
LOCHTTORIAME,
FROM SALE:
1) LOCATION
WHERE §
L.LOCATIONID:
(i) senecr wave, SALES, LOCATIONNANE
(V) Write an SOL query to get cities common to FROM SALES $, LOCATION L
tables venue and venue2. WHERE S$. LOCATIONED L. Locarror
Ans, (i) seect city FROM venue suo Sauus> 1300000;
ee Gil) seuecr wae
SBLUCT city FROM venue? ae
(ii) SELECT city FROM venuez 4
UntoH WHERE ane LIKE
SBLECT city FRON venuel (wv) Primary Key: SAL
(W) setect cicy eROM venue? Reason: Tt uniquely identifies a1
UNION ALL ROW in the table and does not
SELECT city PRON venus? contain empty/zero or null valves.
(W) setect vi.eity FRON venuer v1 ( opcare sarza
LEE? JOIN venue? v2 saideneionae ~ BS
OW vi.eity ~ v2.city nai
(anes ae rey een WHERE SALESMAN = *99":
(¥) setecr orstincr vi.city Q6. Consider the table and write the output of
FROM Venue) v1 following queries:
INNER JOIN Verve? v2 Table: PRODUCT_MAST
On v1, city = v2.city PRODUCT | COMPANY | QTY | RATE | COST
QS. Ina Database Company, there are two tables given emt Comt 2 10 20
below:
bias SAUES Tem? Com? 3 25 75
SALESMANID[ NAME SALES [LOCATIONID. ems Com 2 30 Gi
st TANITASINGH | 250000 702 Rema Coma 5 20 50
oe items Coma 2 20 40
2 YP.SINGH | 1300000 | 101
3 TINAJAISWAL | 1400000 | _103 Ee Cpmt 3 2s 7s
‘S4___ [GURDEEPSINGH| t2s0000 | __102 Rem? Com 5 30 150
35 simiFaizaL | 1450000 | __103 Temé ‘Comt 3 10 30
Table: LOCATION Remd Com? 2 25 50
TOCATIONIO LOCATIONNAME itemio amt 7 0 Lo
ToT Dall
() senser comer (*)
"192 Mumba FROM PRODUCT_MAST
103 Kolkata (i) sexzcr counr(+)
TOF Ceara FROM PRODUCT_MAST,
WHERE RATED=20;
Pe EE EE EE EEii) SELECT COUNT (DISTINCT COMPANY)
FROM PRODUCT_MAST;
(iv) sexzcr company, counr(*)
FROM PRODUCT_MAST
GROUP BY COMPANY;
(¥) szuacr coMpaNy, counr(*)
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT (#)>2;
ans. (i) 10
(7
(ii) 3
(w) com 5
com2 3
com3 2
(¥) Com 5
com2 3
Q7. Consider the table and answer the output of
following queries:
Table: PRODUCT_MAST
PRODUCT] COMPANY | QTY | RATE | COST
Tomt_| com | 2 | 10 | 2
tema [| com | 3 | 2 | 75
tems | com | 2 | 30 |
Tema [coms | 5 | 10 | 50
tems | com2 | 2 | 20 | 40
Teme | coma | 3 | 2 | 75
Tem? | com | 5 | 30 | 180
Teme | com [3 | 10 | 30
tem | com? | 2 | 2 | 50
Temio_| coma] 4 | 30 | 120
(@ suuacr sum(cost)
FROM PRODUCT_MAST;
(i) sexecr sum(cost)
FROM PRODUCT_MAST
WHERE QTY>3;
Gi) seuecr sum(cost)
FROM PRODUCT_MAST
HERE QTY>3
GROUP BY COMPANY;
(iv) sunecr company, sum (cost)
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST) >1170)
(¥) suuzcr ave(cosz)
FRON PRODUCT_MAST;
Ans. () 670,
(i) 320
{) Comt 150
com2 170
(iv) Comt 335,
Coma 170
(v) 6700
Q8. Consider the table and write the output of
following queries:
Table: EMPLOYEE
EMPID] EMP.NAME | cITY | SALARY AGE
1 [Angeline [Chicago | 200000 | 30
2 | Rober ‘Austin 300000 | 26
3 [Christin [Denver | i00000 | 42
4_[Krsten Washington [500000 | 29
5 | Russell os Angeles | 200000 | 36
6 [Many Canada| 600000 | 48
Table: PROJECT
PROJECT.NO | EMP.ID DEPARTMENT
ii Testing
102 2 Development
103 3 Designing
104 4 Development
() SELECT EMPLOYEE. mMP_NAKE, PROJECT.
DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.ENP_ID:
(I) sexect euproveE.mup NAME, PROJECT
DEPARTMENT
Ans. (i)
(i)
ROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.RMP_ID = ENPLOYEE.EMP_ID;
SELECT EMPLOYEE.EMP_NAME, PROJECT.
DEPARTHEN®
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = ENPLOYEE.EMP_zD;
EMP_NAME | DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
weriston Development
EMP_NAME [DEPARTMENT
‘Angelina [Testing
Rober Development
Christian Designing
Kristen Development
Russell NULL
Mary NULL
Pe EE EE EE EEwi) ‘Ans. () ID | NAME (i) 10 | NAME
co one 7 | ack 1 as
gelina esting ee iar
Robert Development en 3 | Jackson
Christian Designing aceon 3 [Jackson
Kristen Development Stephan 4 T stephan
Q9. Consider the table and answer the following David 5 | David
suestions: (uw) 1D] NAME =D | NAME
The First table __The Second table
1D | NAME 1 | _NAME 3 [Lackson 1 | sack
Wheat 3 _[ieetson 2 | barry
2_[ Harn 4 [Stephan
3 Larteon Sosa (¥) UNION: The SQL UNION operation is used to
() seuzer + FRom First combine the result of two or more SQL SELECT
oNION
SELECT * FROM Second
(ii) setect + FROM First
UNION ALL
SELECT * FROM Second:
i) SELECT * FROM First
INTERSECT
SELECT * FROM Second;
(Wv) setect + FROM First
wrwus
SELECT * FROM Second
(V) Differentiate between UNION AND UNION ALL.
queries. In the UNION operation, all the number
of datatype and columns must be same in both
the tables on which UNION operation Is belong
applied. The UNION operation eliminates the
duplicate rows from its result set.
UNION ALL: UNION ALL operation is equal to
the UNION operation. It returns the set without
removing duplication and sorting the data
x Chapter Test
ww Clause combines records from
two or more tables in a database.
2. EQUIJOIN
b. CARTESIAN
JOIN
NATURAL,
2. Ar is.a specific type of join that uses only
equality comparisons in the join-condition.
2 EQUIJOIN b. CARTESIAN
Both a. and b, d. Natural
JOIN selects all data starting from
the Loft table and matching rows in the right table.
a. EQUI b.NATURAL
c LEFT RIGHT
.. Joln Is a reversed version of the LEFT
JOIN.
a. EQUI b.NATURAL
c Leet o.RIGHT
join produces a data set that
includes only those rows from the left table which
hhave matching rows from the right tablo.
a. UNION b.OUTER
EXCEPT INNER
in the Blanks
a6. .
SELECT queries after removing duplicate rows
between the two SELECT statements,
Q7. The
two SELECT statements and returns only those rows
in the final result, which belong to the first set of the
result,
Q8. The INTERSECT operation can be simulated in
MySQL using. JOIN.
Assertion & Reason Type Questions
. returns all rows from both the
Directions (Q, Nos. 9-10): In the questions given
below, there are two statements marked as Assertion
(A) and Reoson (R).Reod the statements and choose the
correct option
a. Both Assertion (A) and Reason (R) are true and
Feasan (R) isthe correct explanation of Assertion (A).
b.Both Assertion (A) and Reason (R) are true.
but Reason (A) Is not the correct explanation of
Assertion (A).
Assertion (A) Is true. but Reason (R} Is false
4. Assertion (A) Is false. but Reason (R) Is true
Pe EE EE EEE EEEQ9. Assertion (A): UNION (\.) operation is used to
combine the selected rows of two tables at a time.
Hf some rows are the same in both the tables, then
the result of the UNION operation will show those
rows only once.
Reason (R): In order to display the number of
records that matches a particular criteria in the
table, we have to use COUNTBY(") with WHERE
clause.
QUO. Assertion (A): Cartesian product operation
combines tuples from two rows. It results in
all palrs of rows from the two input relations,
regardless of whether or not they have the same
values on common attributes. It is denoted as XY’
Reason (R): While using the JOIN clause of SQL, we
specify conditions on the related attributes of two
tables within the FROM clause.
(vy) The clause is used to list the
attributes desired in the result of a query.
a. WHERE b. Sevect
< FROM DISTINCT
(v) This Query can be replaced by which one of the
following?
SELECT name, course_id
FROM instructor, teaches
WHERE instructor_|D=teaches_ID;
BCT name, course_1d FROM teaches,
RHERE instructor_
dnareu
b. SELECT name, course
Anatructor NATURAL
© SELECT namo,
Anatrue
JOIN teaches
Case Study Based Questions
QL SQL is a language to operate databases; it
Qi2. Consider the below two tables for reference and
answer the following questions:
includes database creation, deletion, fetching
rows, modifying rows, etc. SQL is an ANSI
(American National Standards Institute) standard
language, but there are many different versions
of the SQL language. SQL is Structured Query
Language, which is a computer language for
storing, manipulating and retrieving data stored
in a relational database. SQL is the standard
language for Relational Database System. All
the Relational Database Management Systems
(RDMS) like MySQL, MS Access, Oracle,
Sybase, Informix, Postgres and SQL Server
use SQL as their standard database language.
The standard SQL commands to interact with
relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP.
() Here which of the following displays the unique
values of the column?
SELECT wnsnsnneninn dept_name
FROM Instructor;
a. All b. From
¢. Distinct Name
(i) The clause allows us to select only
those rows in the result relation of the
clause that satisfy a specified predicate.
a WHERE,FROM FROM SELECT
¢ SELECT,FROM ——d. FROM, WHERE
(ill) The query given below will not give an error.
Table-Employee Details
Empld [FullName|ManageriD[Date of Joining] City
at | John | 321 | 31/01/2014 | Toronto
Snow
3a | Walter | 986 | 31/01/2015 | California
White
aii | Kuldeep | 876 | 30/01/2016 [New Delnt
ana
Tablo-EmployeeSalary
Empla Project Salary _|_ Variable
221 PL ‘8000 300
32 Pz 10000 1000
a2 PL 32000 oO
() Write an SQL query to fetch all the Emplds
which are present in either of the tables-
"EmployeeDetails’ and ‘EmployeeSalary:,
Write an SQL query to fetch common records
between two tables,
Write an SOL query to fetch records that are
present in one table but not in another table.
(iv) Write an SQL query to fetch the Emplds that are
present in both the tables~ ‘EmployeeDetails’
and’ EmployeeSalary.
(v) Write an SQL query to fetch the Empids that
are present in EmployeeDetalls but not in
EmployeeSalary.
Short Answer Type Questions
Q13. What does INTERSECT do?
14. What does MINUS operation do?
QI. A table FLIGHT has 4 rows and 2 columns and
another table (AIR HOSTESS) has 3 rows and 4
columns. How many rows and columns will be there
if we obtain the Cartesian product of these two
tables?
Which one of the following has to be replaced to
get the desired output?
SELECT ID, name, dept name, salary * 11
WHERE instructor:
2 SALARY"1T bo
c WHERE INSTRUCTOR
Pe EE EE EEE EEEQ16. Table Employes has 4 records and Table Dept has 3 Table: SAMS
records init. Mr.Jain wants to display all information {code Name Price | Colour | Veode
stored in both ofthese related tables He forgot to ~sogr | —refigerator | 20000 | elue | FOr
Specify equl join condition in the query. How mary —soo2 | mobile Phone | 45000 | lack | pO
rows will get displayed on execution of this query?
5003 \co 0000 | sliver | p03
Short Answer Type-I Questions 8004 | Washing Machine | 12500 | Smoke | P01
QU. Consider the table and answer the output of _so0s | AirConditioner_| 16000 | white | P03
following queries: Table: VENDOR
Table: PRODUCT_MAST Weal AME
PRODUCT | COMPANY] QTY | RATE | COST P01 Satish
emt comt z 10 20 oz Mano}
tem? come 3 25 75 P03 Subodh
items comt 2 30 0 Poa Jacob
tema Coma 5 10 50 () To display ICode, IName and VName of all the
iene on z a i vendors, who manufacture “Refrigerator”
iene San 3 7 ae (i) To display IName, ICode, VName and Price ofall
the products whose price Is more than 20000.
Rem? Comt 5 30 | 150 i
7 z 3 7 0 (il) To display vendor names and names of all items
Fan om z manufactured by vendor whose code is "P03".
nem? __| Com? z 3 50__ 20. in a Database Multiplexes, there are two tables
tent Eoms: 2 30 ae. with the following data. Write MySQL queries for
() sexzcr vax Rare)
FROM PRODUCT MAST;
(il) SELECT MIN (RATE)
FROM PRODUCT_MAST;
(i) and (ii), which are based on Ticket Details and
AgentDetails:
Table: TicketDetails Table: AgentDetalls
QI6. Consider the table and answer the output of —Tede|NAME|TIckets|A.code _ACode | _AName _
following queries: $001 |eenal 7 | aor aot | Mr. Robin
Table: EMPLOYEE so02 | voni | s | 02 — A02 | Mr Ayush
EMPID[EMPLNAME| CITY [SALARY] AGE $003 |Meena| 9 | Aor 03 | Mr. Telok
1 [Angelina [chicago | 200000 [30 S004 |karish) 2 | aos _aoa_| Mr John
2__ | Robert Austin 300000 | 26 S005 | Suraj | 1 Adz
3 [enristian | Oenver 00000 | 42 () To display Teode; Name and Aname of all the
a incon oer coro lat fl
[Russell [Losngeles | 200000 | 36 (i) To display total number of tickets booked by
6 [Marry Canada 600000 | 48 agent “Mr. Ayush”.
(lil) To display Acode, Aname and corresponding
TAGS EREUECT, ‘Teode where Aname ends with "k’
PROJECT_NO EMP_ID DEPARTMENT Long Answer Type Questions
107 1 Testing i Gea ie Galton
i Q21. Consider the following tables RESORT and
102 2 Seis gprs OWNEDBY and answer the question:
103 3 Designing Table : RESORT
108 a Development RCODE| PLACE | RENT | TYPE | STARTDATE
ROOT [GOA T5000] —S STAR | 12-Jan-02
SELECT TMPLOYEE.EMP_NAME, PROJECT 002 J HIMacHat }9000 | 4sTaR | 20-Dec-07
DeBAnsrioniy ros | KERALA | 12500 | $STAR | 10-Mar-06
FROM ENPLOYEE R004 | HIMACHAL | 10500 | 2STAR | 25-Nov-05
womnp ae sooent roos |GuaraT ]000 | 4sTAR | OL-Jon-03
ON PROJECT.EMP_ID = EMPLOYEE.RMP_1D ios. | GOA, ago | getan | soMarte
Short Answer Type-II Questions roo7 JooisHa | 7500 | 2star | 12-Apr-09
Q19. ina Database - SAMS and VENDOR are two tables MON | MMA | Mito | Sst |
with the following information, Write MySQL queries R008 | HIMACHAL | 200 alan! | eccne
for (i) to (ili), based on tables SAMS and VENDOR: ROL0_] GOA 33000_|_SSTAR_| 12-Apr-06
Pe EE EEE EETable : OWNEDBY
Place ‘Owner
GOA RA) RESORTS
KERALA Kroc
HIMACHAL TOC
GUARAT MAHINDRA RESORTS,
OISHA orpe
Write SQL commands for the following
statements:
(2) To display the RCODE and PLACE of all ‘5
STAR’ resorts in the alphabetical order of
tthe place from table RESORT.
(b) To display the maximum and minimum rent
for each type of resort from table RESORT.
(©) Todisplay the details of all resorts which are
started after 31-DEC-05 from table RESORT.
(4) Display the OWNER of all ‘5 STAR’ resorts
from tables RESORT and OWNEDBY.
Give output for the SQL query
SELECT OWNER FROM RESORT OWNED BY
(A.TYPE START’ AND A.PLACE,
B WHERE
B. PLACE}
22. Consider the following tables STORE and SUPPLIERS
and answer the question:
Table: STORE
Tomine om Scode] Qty | Rate | LestBuy
7005 | Shorpener classe 23. J 60 [8 | 31-vun-09
2003 |salipena2s —|22 |so [25 |o1-Feb-io
202
2008
2001
2008
2009
Gel Pen Premium 24-Feb-10,
Gel Pen Cassi 1 Mar-09
Eraser Small 19.4an-09
02-06-09)
racer Big
Ball Pen OS 03-Nowo9
Table: STORE
Scode ‘Shame
a | Premium Stationers
B Soft Plastics
2 Tetra Supply
()) Write SQL commands for the following
statements:
(2) To display detalls of all the items in the
STORE table In ascending order of LastBuy.
(b) To display ItemNo and item name of those
items from STORE table whose Rate is more
than 15 Rupees.
(©) To display the details of those items whose
supplier code (Scode) is 22 or Quantity in
STORE (Qty) is more than TI0 from the table
store.
(@) To display minimum Rate of items for each
supplier individually as per Scode from the
table STORE.
)) Give the output for SQL queries:
SBLECF COUNT(DISTINCT Scode) FROM
STORE; °
Pee EE EE EEE EEE