MySQL Functions and Query Questions
MySQL Functions and Query Questions
SOLVED QUESTIONS
1. What is SQL?
Ans. SQL stands for Structured Query Language. This language is used to create, manage and manipulate
stored records in a table.
2. What is null value in MySQL?
Ans. If a column in a row has no value, then the column is said to be null. Null is used to represent missing values.
3. Which keyword eliminates redundant data from a query result?
Ans. DISTINCT
4. Differentiate between WHERE and HAVING clause.
Ans. WHERE clause is used to select particular rows that satisfy a condition whereas HAVING clause is used
in connection with the aggregate function, GROUP BY clause. For example, SELECT * FROM STUDENT
WHERE MARKS>75; this statement shall display the records for all the students who have scored more
than 75 marks.
On the contrary, the statement — SELECT * FROM STUDENT GROUP BY STREAM HAVING MARKS>75;
shall display the records of all the students grouped together on the basis of stream but only for those
students who have scored marks more than 75.
5. Why is it not allowed to give String and Date type arguments for SUM() and AVG() functions?
Ans. String and dates are not real numbers that we calculate, so SUM() or AVG() functions are not valid
for them.
6. How are NULL values treated by aggregate functions? [HOTS]
Ans. None of the aggregate functions takes NULL into consideration except COUNT(*) function. NULL is simply
ignored by all the aggregate functions.
7. There is a column C1 in a table T1. The following two statements:
SELECT COUNT(*) FROM T1; and SELECT COUNT(C1) FROM T1; are giving different outputs. What may be
the possible reason? [HOTS]
Ans. There may be a null value in a C1 column.
8. What is the purpose of GROUP BY clause?
Ans. GROUP BY clause is used in a SELECT statement in combination with aggregate functions to group the
result based on distinct values in a column.
MOD(AGE,5)
4
1
1
2
POW(3,2)
9
9
9
Table: LOANS
AccNo Cust_Name Loan_Amount Instalments Int_Rate Start_Date Interest
1 R.K. Gupta 300000 36 12.00 19-07-2009 1200
2 S.P. Sharma 500000 48 10.00 22-03-2008 1800
3 K.P. Jain 300000 36 NULL 08-03-2007 1600
4 M.P. Yadav 800000 60 10.00 06-12-2008 2250
5 S.P. Sinha 200000 36 12.50 03-01-2010 4500
6 P. Sharma 700000 60 12.50 05-06-2008 3500
7 K.S. Dhall 500000 48 NULL 05-03-2008 3800
ii. SELECT COUNT(Training Id) FROM TRAINING WHERE Email Id LIKE '%gmail%';
Ans. 2
iii. SELECT AVG (Fee) FROM TRAINING WHERE Topic = "Cyber Security";
Ans. 11000
iv. SELECT Name FROM TRAINING WHERE INSTR (Email Id, '@')=0;
Ans. Ms. Neena
24. Consider the following tables GAMES and PLAYER. Write SQL commands and output for the following
statements.
Table: GAMES
GCode GameName Number PrizeMoney ScheduledDate
101 Kabaddi 2 5000 23-Jan-2007
102 Badminton 2 12000 12-Dec-2013
103 Table Tennis 4 8000 14-Feb-2014
105 Chess 2 9000 1-Jan-2015
108 Table Tennis 4 25000 19-Mar-2014
Table: PLAYER
PCode Name Gcode
1 Ravi Shankar 101
2 Amir 108
3 Jatin 101
4 Shahrukh 103
(a) To display details of those games which have PrizeMoney more than 7000.
Ans. SELECT * FROM GAMES WHERE PrizeMoney>7000;
(b) To display the content of the GAMES table in ascending order of ScheduledDate.
Ans. SELECT * FROM GAMES ORDER BY ScheduledDate;
(c) To display game names along with name of the players.
Ans. SELECT [Link], [Link] FROM GAMES G, Player P WHERE [Link]=[Link];
(d) SELECT COUNT (DISTINCT GameName) FROM GAMES;
Ans.
COUNT(DISTINCT GameName)
4
(e) SELECT MAX(ScheduledDate), MIN(ScheduledDate) FROM GAMES;
Ans.
MAX(ScheduledDate) MIN(ScheduledDate)
01-Jan-2015 23-Jan-2007
Table: FACULTY
Table: COURSES
(a) To display details of those faculty members whose salary is greater than 12000.
Ans. SELECT * FROM FACULTY WHERE SALARY> 12000;
(b) To display the details of courses whose fees is in the range of 15000 to 50000 (both values included).
Ans. SELECT * FROM COURSES WHERE FEES BETWEEN 15000 AND 50000;
(c) To display faculty first name and last name from the Faculty table and course name from the Courses
table whose fees is greater than 20000.
Ans. SELECT [Link],[Link],[Link],[Link] FROM FACULTY F,COURSES C WHERE
F. F ID=C.F ID AND [Link]>20000;
(d) SELECT COUNT (DISTINCT F ID) FROM COURSES;
Ans.
Table: PLAYER
PCODE POINTS
1 50
2 NULL
3 40
AVG(POINTS)
45
(b) SELECT COUNT(POINTS) FROM PLAYER;
Ans.
COUNT(POINTS)
2
27. Kunal has entered the following SQL command on Table 'STUDENT' that has TotalMarks as one of the
columns: [CBSE 2017]
SELECT COUNT(*) FROM STUDENT;
The output displayed is 20.
Then, Kunal enters the following command:
SELECT COUNT(*) FROM STUDENT WHERE TotalMarks < 100;
The output displayed is 15.
Then, Kunal enters the following command:
SELECT COUNT(*) FROM STUDENT WHERE TotalMarks >= 100;
He predicts the output of the above query to be 5. Do you agree with Kunal? Give reasons for your answer.
Ans. Yes, Total rows=20, rows with TotalMarks <100 are 15, so remaining rows left are 20 — 15 = 5
Or
No, the output of the query may not always be 5 as there may be rows with Total Marks as NULL which
would not have been included in either of the two SELECT statements mentioned.
28. What is an ORDER BY clause and GROUP BY clause?
Ans. ORDER BY clause is used to display the result of a query in a specific order (sorted order).
The sorting can be done in ascending or descending order. However, the actual data in the database is
not sorted; only the results of the query are displayed in sorted order. If order is not specified then, by
default, the sorting will be performed in ascending order.
For example,
SELECT Name, City FROM STUDENT
ORDER BY Name;
The above query returns name and city columns of table student sorted by name in ascending order.
For example,
SELECT * FROM STUDENT ORDER BY City DESC;
It displays all the records of table student ordered by city in descending order.
GROUP BY clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group
the results by one or more columns.
For example,
SELECT Name, COUNT(*) AS "NUMBER OF STUDENTS" FROM STUDENT
WHERE Marks>350 GROUP BY City;
29. Consider the following tables Product and Client. Write SQL commands for the statements (a) to (c) and
give outputs for SQL queries (d) to (f).
Table: PRODUCT
P_ID Product Name Manufacturer Price
DISTINCT(City)
Delhi
Mumbai
Bengaluru
(e) SELECT Manufacturer, MAX(Price), MIN(Price), COUNT(*) FROM PRODUCT GROUP
BY Manufacturer;
Ans.
ProductName Price*4
TalcumPowder 160
FaceWash 180
BathSoap 220
Shampoo 480
FaceWash 380
Table: SHOP
RoliNo Name Class DOB Gender City Marks
1 Anand XI 06-06-1997 M Agra 430
2 Chetan XII 07-05-1994 M Mumbai 460
3 Geet XI 06-05-1997 F Agra 470
4 Preeti XII 08-08-1995 F Mumbai 492
5 Saniyal XII 08-10-1995 M Delhi 360
6 Meena XI 12-12-1994 F Dubai 256
7 Neha X 08-12-1995 F Moscow 324
8 Nishant X 12-06-1995 M Moscow 429
(A) State the command that wil give the output as:
Name
Anand
Chetan
Geet
Preeti
(i)
SELECT Name FROM STUDENT WHERE Class='XI' AND Class='XII';
(ii)
SELECT Name FROM STUDENT WHERE NOT Class='XI' AND Class='XII';
(iii)
SELECT Name FROM STUDENT WHERE City="AGRA" OR City="MUMBAI";
(iv)
SELECT Name FROM STUDENT WHERE City IN("AGRA", "MUMBAI");
Choose the correct option:
(a) Both (i) and (ii).
(b) Both (iii) and (iv).
(c) Any of the options (i), (ii) and (iv)
(d) Only (iii)
Ans. (b) Both (iii) and (iv)
SELECT Name FROM STUDENT WHERE City="AGRA" OR City="MUMBAI";
and
SELECT Name FROM STUDENT WHERE City IN ("AGRA", "MUMBAI");
(B) Pinky has given the following command to obtain the highest marks class-wise:
SELECT MAX(Marks) FROM STUDENT WHERE GROUP BY Class;
but she is not getting the desired result. Help her by writing the correct command.
(a)SELECT MAX(Marks) FROM STUDENT WHERE GROUP BY Class;
(b)SELECT Class, MAX(Marks) FROM STUDENT GROUP BY Marks;
(c)SELECT Class, MAX(Marks) GROUP BY Class FROM STUDENT;
(d)SELECT Class, MAX(Marks) FROM STUDENT GROUP BY Class;
Ans.(d) SELECT Class, MAX(Marks) FROM STUDENT GROUP BY Class;
(C) State the command to display the average marks scored by students of each gender who are in Class Xl.
(a)
SELECT Gender, AVG (Marks) FROM STUDENT WHERE Class= "XI" GROUP BY Gender;
(b)
SELECT Gender, AVG (Marks) FROM STUDENT GROUP BY Gender WHERE Class="XI";
(c)
SELECT Gender, AVG (Marks) GROUP BY Gender FROM STUDENT HAVING Class="XI";
(d)
SELECT Gender, AVG (Marks) FROM STUDENT GROUP BY Gender HAVING Class = "XI";
Choose the correct option:
(a) Both (ii) and (iii) (b) Both (ii) and (iv)
(c) Both (i) and (iii) (d) Only (iii)
Ans. (b) Both (ii) and (iv)
SELECT Gender, AVG(Marks) FROM STUDENT GROUP BY Gender WHERE Class="XI";
Or
SELECT Gender, AVG(Marks) FROM STUDENT GROUP BY Gender HAVING Class = "XI";
(D) Help Ritesh write the command to display the name of the youngest student.
(a) SELECT Name,MIN(DOB) FROM STUDENT;
(b) SELECT Name,MAX (DOB) FROM STUDENT;
(c) SELECT Name,MIN(DOB) FROM STUDENT GROUP BY NAME;
(d) SELECT Name,MAXIMUM (DOB) FROM STUDENT;
Ans. (b) SELECT NAME, MAX (DOB) FROM STUDENT;
(E) What will be the output of the following command?
SELECT * FROM STUDENT WHERE GENDER ="F" ORDER BY MARKS;
(a)
RoliNo Name Class DOB Gender City Marks
4 Preeti XII 08-08-1995 F Mumbai 492
3 Geet XI 06-05-1997 F Agra 470
7 Neha X 08-12-1995 F Moscow 324
6 Meena XI 12-12-1994 F Dubai 256
(b)
RoliNo Name Class DOB Gender City Marks
6 Meena XI 12-12-1994 F Dubai 256
7 Neha X 08-12-1995 F Moscow 324
3 Geet XI 06-05-1997 F Agra 470
4 Preeti XII 08-08-1995 F Mumbai 492
(c)
Gender Marks
F 256
F 324
F 470
F 492
(d)
Gender Marks
F 492
F 470
F 324
F 256
Ans. (b)
AREA COUNT(*)
CP 2
GK II 1
Nehru Place 2
MAX(Charges) MIN(Charges)
35 12
COUNT(*) Make
5 Suzuki
(iv) CarName
SX4
C Class
37. Consider the following tables STOCK and DEALERS and answer (a) and (b) parts of this question:
[CBSE D 2010]
Table: STOCK
ItemNo Item Dcode Qty UnitPrice StockDate
5005 Ball Pen 0.5 102 100 16 31-Mar-10
5003 Ball Pen 0.25 102 150 20 01-Jan-10
5002 Gel Pen Premium 101 125 14 14-Feb-10
5006 Gel Pen Classic 101 200 22 01-Jan-09
5001 Eraser Small 102 210 5 19-Mar-09
5004 Eraser Big 102 60 10 12-Dec-09
5009 Sharpener Classic 103 160 8 23-Jan-09
Table: DEALERS
Dcode DName
101 Reliable Stationers
103 Classic Plastics
102 Clear Deals
(a) Write SQL commands for the following statements:
(i) To display details of all items in the Stock table in ascending order of StockDate.
(ii) To display ItemNo and Item name of those items from Stock table whose UnitPrice is more
than 10.
(iii) To display the details of those items whose dealer code (Dcode) is 102 or quantity (Qty) is
more than 100 from the table Stock.
(iv) To display maximum. UnitPrice of items for each dealer individually as per Dcode from the
table Stock.
Ans. (i) SELECT * FROM STOCK ORDER BY StockDate;
(ii) SELECT ItemNo, Item FROM STOCK WHERE UnitPrice>10;
(iii) SELECT * FROM STOCK WHERE Dcode=102 OR QTY>100;
(iv) SELECT Dcode, MAX (UnitPrice) FROM STOCK GROUP BY Dcode;
(b) Give the output of the following SQL queries:
(i) SELECT COUNT (DISTINCT Dcode) FROM STOCK;
(ii) SELECT Qty*UnitPrice FROM STOCK WHERE ItemNo=5006;
(iii) SELECT MIN (StockDate) FROM STOCK;
Ans.
(i) COUNT (DISTINCT Dcode)
3
Qty*UnitPrice
4400
MIN (StockDate)
01-Jan-09
38. Consider the following tables ACTIVITY and COACH. Write SQL commands for the statements (a) to
(d) and give outputs for SQL queries (e) to (h)
Table: ACTIVITY
ACode ActivityName ParticipantsNum PrizeMoney ScheduledDate
1001 Relay 100x4 16 10000 23-Jan-2004
1002 High Jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discus Throw 10 15000 19-Mar-2004
Table: COACH
PCode Name ACode
1 Ahmad Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
(a) To display the name of all activities with their Acodes in descending order.
(b) To display sum of PrizeMoney for each of the number of participants groupings (as shown in column
ParticipantsNum 10,12,16).
(c) To display the coach's name and ACodes in ascending order of ACode from the table COACH.
(d) To display the content of the GAMES table whose ScheduledDate is earlier than 01/01/2004 in
ascending order of ParticipantsNum.
(e) SELECT COUNT(DISTINCT ParticipantsNum) FROM ACTIVITY;
(f) SELECT MAX(ScheduledDate),MIN(ScheduledDate) FROM ACTIVITY;
(g) SELECT SUM (PrizeMoney) FROM ACTIVITY;
(h) SELECT DISTINCT ParticipantsNum FROM COACH;
Ans. (a) SELECT ActivityName FROM ACTIVITY ORDER BY ACode DESC;
(b) SELECT SUM (PRIZEMONEY) FROM ACTIVITY GROUP BY ParticipantsNum HAVING
ParticipantsNum IN (10,12,16);
(c) SELECT Name, Acode FROM COACH ORDER BY ACode;
(d) SELECT * FROM ACTIVITY WHERE ScheduledDate>' 01/01/2004' ORDER BY
ParticipantsNum;
(e)
COUNT(DISTINCT ParticipantsNum)
3
(f)
MAX( Scheduled Date) MIN(ScheduledDate)
19-Mar-2004 12-Dec-2003
(g)
SUM (PrizeMoney)
54000
(h)
DISTINCT ParticipantsNum
16
10
12
39. Consider the following relations MobileMaster & MobileStock:
Table: MOBILEMASTER
M_Id M_Company M_Name M_Price M _ Mf _Date
MB001 Samsung Galaxy 4500 2013-02-12
MB003 Nokia N1100 2250 2011-04-15
MB004 Micromax Unite3 4500 2016-10-17
MB005 Sony XperiaM 7500 2017-11-20
MB006 Oppo SelfieEx 8500 2010-08-21
Table: MOBILESTOCK
S_Id M_Id M_Qty M_Supplier
5001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile Store
5004 MB006 150 A-one Mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Centre
Write the SQL query for questions (a) to (d) and write the output of SQL command for questions (e) to (g)
given below:
(a) Display the mobile company, mobile name and price in descending order of their manufacturing date.
(b) List the details of mobiles whose name starts with "S".
(c) Display the mobile supplier and quantity of all mobiles except "MB003".
(d) To display the names of mobile companies having price between 3000 and 5000.
(e) SELECT M Id, SUM (M Qty) FROM MOBILESTOCK GROUP BY M_Id;
(f) SELECT MAX (M Mf Date), MIN (M Mf Date) FROM MOBILEMASTER;
(g) SELECT AVG (M Price) FROM MOBILEMASTER;
Ans. (a) SELECT M Company, M_Name, M Price FROM MOBILEMASTER ORDER BY M Mf Date DESC;
(b) SELECT * FROM MOBILEMASTER WHERE M_Name LIKE "S%";
(c) SELECT M Supplier, M_Qty FROM MOBILESTOCK WHERE M_Id <> "MB003";
(d) SELECT M Company FROM MOBILEMASTER WHERE M Price BETWEEN 3000 AND 5000;
(e)
M_Id SUM(M_Qty)
M 8004 450
MB003 400
MB001 300
MB006 200
(f)
MAX(M_Mf_Date) MIN(M_Mf_Date)
2017-11-20 2010-08-21
(g) 5450
40. (a) Name any one single row function and any one aggregate function. Also mention the difference in
their working.
Ans. Single row function: Length()
Aggregate function: MAX()
A single row function works on every row of the table and, hence, gives output for each row in the table.
An aggregate function, also known as multiple row function, works on a group of rows and returns only
one output.
(b) Explain why the following queries give different outputs on execution:
(i) SELECT COUNT (ENAME) FROM EMP;
Output: 5
(ii) SELECT COUNT (*) FROM EMP;
Output: 8
Ans. Aggregate functions ignore NULL values. The first query counts the Not Null values in the column ENAME,
hence the output is 5.
But the second query counts all the records present in the table EMP which gives the output as 8.
Hence, this implies that there are 8 rows in the table and the Ename column contains the names of only
5 employees. 8-5 = 3, i.e., 3 names have been left blank. This means that there are 3 null values in the
column ENAME.
41. A user intends to group the result set based on some column's value. Also, it is required that the grouped
result should appear in sorted order. In which order should the user write the two clauses (for sorting
and grouping)? Give an example to support your answer.
Ans. When we use GROUP BY clause (for grouping of data) and ORDER BY clause (for sorting data) together,
the ORDER BY clause always follows other clauses. That is, the GROUP BY clause will come before
ORDER BY clause.
For example,
SELECT EMP ID, SUM (SALARY) AS "ANNUAL SALARY" FROM EMPLOYEE
GROUP BY DEPTID
ORDER BY EMP ID DESC;
42. On the basis of the following table, answer the given questions: [CBSE Sample Paper 2020]
I 1998-02-21 I
(iii) Write the SQL query to delete the row from the table where customer has no accumulated
amount.
Ans. DELETE FROM Customer Details WHERE Accumlt Amt IS NULL;
43. Write commands in SQL for (a) to (d) and output for (e) and (f).
Table: Store
(a) To display names of stores along with SalesAmount of those stores that have 'fashion' anywhere in
their store names.
(b) To display names of the cities and the total amount of sales on the basis of City.
(c) To display the date of opening of the oldest store.
(d) To display the City and the number of stores located in that City, only if number of stores is more
than 2.
(e) SELECT MIN (DateOpen) FROM STORE;
(f) SELECT COUNT (StoreId) , NoOfEmp FROM STORE GROUP BY NoOfEmp HAVING
MAX (SalesAmt)<60000;
Ans. (a) mysql> SELECT Name, SalesAmt FROM STORE WHERE Name LIKE '%fashion%';
(b) mysql> SELECT City, SUM(SalesAmt) FROM STORE GROUP BY City;
(c) mysql> SELECT MIN (DateOpen) FROM STORE;
(d) mysql> SELECT COUNT(*) , City FROM STORE GROUP BY City HAVING COUNT (*) >2;
(e) +
1 MIN(DateOpen) I
1 2015-02-06 1
(f) +
1 COUNT(Storeld) I NoOfEmp 1
I1 110
I1 1 11
I5
I7
UNSOLVED QUESTIONS
1. What are single row and multiple row functions?
2. What is the significance of GROUP BY clause in an SQL query?
3. What is the difference between WHERE and HAVING clause in SQL select command?
4. Write a query to find out the sum, average, lowest and highest marks in Student table.
5. Write a query to find out the sum, average, lowest and highest marks of the students in Student table
grouped by STREAM.
6. Consider the table "Item" given below and give the outputs on the basis of it:
Table: ITEM
Itemno !name Price (Z) Quantity
101 Soap 50 100
102 Powder 100 50
103 Facecream 150 25
104 Pen 50 200
105 Soapbox 20 100
13. Write a query to find out the number of students in each Stream in STUDENT table.
14. Consider the given table Faculty and answer the questions that follow:
Table: FACULTY
F_ID F_Name L_Name Hire_date Salary
102 Amit Mishra 12-10-1998 10000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-05-2001 14000
105 Rashmi Malhotra 11-09-2004 11000
106 Sulekha Srivastava 05-06-2006 10000
(a) To display the details of those Faculty members whose salary is higher than 12000.
(b) To display the details of Faculty members whose salary is in the range of 8000 to 12000 (both values
included).
(c) Count the number of different id from faculty.
(d) Count the number of faculty members getting salary as 10000.
(e) Display details of those faculty members whose names start with S.
(f) Display all records in descending order of Hire date.
(g) Find the maximum and the minimum salary.
(a) To list the names of those students who have obtained Division as FIRST in the ascending order of
NAME.
(b) To display a report listing NAME, SUBJECT and Annual stipend received assuming that the stipend
column has monthly stipend.
(c) To count the number of students who have either Accounts or Informatics as subject.
(d) To insert a new row in the table EXAM: 6, "Mohan", 500, "English", 73, "Second"
(e) SELECT AVG (STIPEND) FROM EXAM WHERE DIVISION = "THIRD";
(f) SELECT COUNT (DISTINCT Subject) from EXAM;
(g) SELECT MIN (Average) FROM EXAM WHERE Subject = "English";
19. Write the SQL query commands based on the following table:
Table: SCHOOLBUS
(a) To show all information of students where capacity is more than the number of students in order of
rtno.
(b) To show area_covered for buses covering more than 20 km, but charge is less than 80000.
(c) To show transporter-wise total no. of students travelling.
(d) To show rtno, area_covered and average cost per student for all routes where average cost per
student is — charges/no. of students.
(e) Add a new record with the following data:
(11, "Moti Bagh", 35,32,10, "Kisan Tours", 35000)
(f) Give the output considering the original relation as given below:
(i) SELECT SUM (Distance) FROM SCHOOLBUS WHERE Transporter= "Yadav Co.";
(ii) SELECT MIN (NoOfStudents) FROM SCHOOLBUS;
(iii) SELECT AVG (Charges) FROM SCHOOLBUS WHERE Transporter= "Anand Travels";
(iv) SELECT DISTINCT Transporter FROM SCHOOLBUS;
20. Answer the questions based on the table given below:
Table: STUDENT
Column Name Data Type Size Constraint
Roll_No NUMBER 4 PRIMARY KEY
Name VARCHAR 20 Not Null
Stipend NUMBER 7 Stipend is greater than 0
Stream VARCHAR 15 Not Null
Grade VARCHAR 1
(a) Write the SQL command to create the above table with constraints.
(b) Insert 2 records with relevant information in the table Student.
(c) Display all the records of the table Student.
(d) Delete the student whose Roll no is 100.
(e) Change the stream of student to 'Computer' whose Roll no. is 536.
(f) Add one column email of data type VARCHAR and size 30 to the table Student.
(g) View structure of the table created by you.
(h) Drop the table Student.
21. Consider the CUSTOMERS table having the following records:
Table: CUSTOMERS
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Bengaluru 4500.00
7 Muffy 24 Indore 10000.00
(a) Write an SQL query to display all records in ascending order of name.
(b) Write an SQL query to display all records in descending order of name.
(c) Write an SQL query to display all records in ascending order of name and descending order of age.
(d) Write an SQL query to display maximum salary.
(e) Write an SQL query to display minimum salary.
(f) Write an SQL query to display total number of records.
(g) Write an SQL query to display average salary.
(h) Write an SQL query to display total salary of all the persons.
(i) Write an SQL query to display names of those persons whose salary is greater than the average
salary.
(i) Write an SQL query to display details of those persons whose age is less than the average age.
22. Consider the following tables WORKER and PAYLEVEL and answer the questions:
Table: WORKER
ECODE NAME DESIG PLEVEL D0.1 DOB
11 Sachin Patel Supervisor P001 13-Sep-2004 23-Aug-1985
12 Chander Nath Operator P003 22-Feb-2010 12-Jul-1987
13 Fizza Operator P003 14-Jun-2009 14-Oct-1983
15 Ameen Ahmed Mechanic P002 21-Aug-200613
1 -Mar-1984
18 Sanya Clerk P002 19-Dec-2005 09-Jun-1983
Table: PAYLEVEL
PLEVEL PAY ALLOWANCE
P001 26000 12000
P002 22000 10000
P003 12000 6000
Table: EVENT
Eventld Event NumPerformers CelebritylD
101 Birthday 10 C102
102 PromotionParty 20 C103
103 Engagement 12 C102
104 Wedding 15 C104
Table: CELEBRITY
CelebritylD CelebrityName Phone FeeCharged
C101 Faiz Khan 99101XXXXX 200000
C102 Sanjay Kumar 89346XXXXX 250000
C103 Neera Khan Kapoor 98116XXXXX 300000
C104 Reena Bhatia 70877XXXXX 100000
(a) Name the Primary keys in both the tables and the Foreign key in Event' table. Can NumPerformers
(Number of performers) be set as the Primary key? Give reason.
(b) How many rows will be present in the Cartesian join of the abovementioned two tables?
(c) Write the commands in SQL:
(i) To display EventId, Event name, Celebrityld for only those events that have more than
10 performers.
(ii) To display Celebrityld and names of celebrities who have "Khan" anywhere in their names.
(iii) To display names of celebrities and fee charged for those celebrities who charge more
than 200000.
24. Consider the following structure of TEACHER and STUDENT table:
Table: TEACHER
TeacherlD TName City Subject Qualification Designation Pay
Table: STUDENT
StdID Name FName Stream TeacherlD
25. Consider the following table and answer the questions that follow:
Table: TEACHER
ID Name Department Hiredate Category Gender Salary
1 Tanya Nanda SocialStudies 1994-03-17 TGT F 25000
2 Saurabh Sharma Art 1990-02-12 PRT M 20000
3 Nandita Arora English 1980-05-16 PGT F 30000
4 James Jacob English 1989-10-16 TGT M 25000
5 Jaspreet Kaur Hindi 1990-08-01 PRT F 22000
6 Disha Sehgal Math 1980-03-17 PRT F 21000
8 Sonali Mukherjee Math 1980-11-17 TGT F 24500
NULL values are generally ignored by most aggregate functions in SQL except for COUNT(*). For example, functions like SUM(), AVG(), and MAX() do not consider NULL values in their calculations. COUNT(*) includes NULLs by including all rows, while COUNT(column) excludes NULLs by counting only the non-NULL entries .
When there are NULL values in a particular column being counted, COUNT(column_name) will exclude those NULLs and only count rows with non-NULL entries, possibly leading to a lower count than COUNT(*), which includes all rows regardless of column content. This discrepancy occurs where NULLs are present in the column, significantly affecting the output count when compared to a row-counting operation .
SUM() and AVG() functions in SQL are designed to perform arithmetic operations, which require numerical inputs. Strings and dates are not numerical and cannot be summed or averaged in a meaningful arithmetic sense, thus they are not valid types for these functions .
The WHERE clause is used to filter records before any grouping is performed in SQL, allowing you to specify conditions on individual rows. In contrast, the HAVING clause is used to place conditions on groups created by the GROUP BY clause, allowing you to filter groups based on aggregate values .
The GROUP BY clause in SQL is used to arrange identical data into groups based on one or more columns, ultimately allowing aggregate functions to be applied to each group. For instance, it can be used to count the number of students in different cities by groups .
NULL values in SQL represent missing or undefined data. They differ from zero or empty strings. To restrict NULL values in a table, the NOT NULL constraint is used when defining a column, ensuring that the column must contain a value in every row .
SQL aggregate functions compute a single result from a set of input values. Common examples include SUM() for summing up values, AVG() for average values, MAX() and MIN() for finding maximum and minimum values among groups, and COUNT() for counting rows. These functions are typically used with the GROUP BY clause to process sets of data .
COUNT(*) considers all rows in the table, including those with NULL values in the specified columns; it simply counts the rows. COUNT(column_name), on the other hand, counts only the rows where the specified column contains non-NULL values; it essentially ignores NULLs in its count .
The DISTINCT keyword in aggregate functions causes them to consider only unique values within the specified column or expression. For example, COUNT(DISTINCT column_name) will count only the distinct non-NULL values in the column, effectively eliminating duplicates from the calculation .
The ORDER BY clause in SQL is used to sort the result set of a query by one or more columns. By default, it sorts results in ascending order, but this can be altered to descending order by using the DESC keyword. It can also handle multiple columns and custom sort orders .