Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

for more details visit : python4csip.

com

WORKSHEET WITH SOLUTION


SQL (CS & IP)
1 What are DDL and DML? Give one command of each.
Ans. DDL stands for Data Definition Language. DDL commands are used to manipulate the
database objects like database, table, views etc. In simple words DDL commands are used to
create table, changing the structure of table or dropping the table. Example: CREATE, ALTER
& DROP
DML stands for Data Manipulation Language. DML commands are used to manipulate the
information stored in a table. Like adding new records, changing existing records or deleting
the records. Example: INSERT, UPDATE & DELETE
2 Which command is used to add new column in existing table?
Ans. ALTER TABLE
3 Which clause is used to search for NULL values in any column?
Ans. IS NULL
4 Which command is used to see information like name of columns, data type, size etc. ?
Ans. DESCRIBE OR DESC
5 Which clause is used for pattern matching? What are the 2 main characters used for
matching the pattern?
Ans. LIKE
% (percent) and _ (underscore)
6 Which clause is used to see the output of query in ascending or descending order?
Ans. ORDER BY
7 Which clause is used to eliminate the duplicate rows from output?
Ans. DISTINCT
8 What is the minimum number of column required in MySQL to create table?
Ans. ONE (1)
9 Which command is used to remove the table from database?
Ans. DROP TABLE
10 Which command is used to add new record in table?
Ans. INSERT INTO
11 Which option of ORDER BY clause is used to arrange the output in descending order?
Ans. DESC
12 Which command is used to change the existing information of table?
Ans. UPDATE
13 Raj is a database programmer, He has to write the query from EMPLOYEE table to search for
the employee whose name begins from letter „R‟, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE NAME=‟R%‟;
But the query is not producing the correct output, help Raj and correct the query so that he
gets the desired output.
Ans. SELECT * FROM EMPLOYEE WHERE NAME LIKE ‟R%‟;
14 Raj is a database programmer, He has to write the query from EMPLOYEE table to search for
the employee who are not getting any commission, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE commission=null;
But the query is not producing the correct output, help Raj and correct the query so that he
gets the desired output.
Ans. SELECT * FROM EMPLOYEE WHERE commission IS null;
15 Raj is a database programmer, has to write the query from EMPLOYEE table to search for the
employee who are working in „Sales‟ or „IT‟ department, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE department=‟Sales‟ or „IT‟;
But the query is not producing the correct output, help Raj and correct the query so that he
gets the desired output.
Ans. SELECT * FROM EMPLOYEE WHERE department=‟Sales‟ or department=„IT‟; OR
SELECT * FROM EMPLOYEE WHERE department IN (‘Sales’,’IT’)

Page :1
for more details visit : python4csip.com

16 The following query is producing an error. Identify the error and also write the correct query.
SELECT * FROM EMP ORDER BY NAME WHERE SALARY>=5000;
Ans. As per MySQL, ORDER BY must be the last clause in SQL QUERY, and in this query ORDER
BY is used before WHERE which is wrong, the correct query will be:
SELECT * FROM EMP WHERE SALARY>=5000 ORDER BY NAME;
17 If Table Sales contains 5 records and Raj executed the following queries; find out the output
of both the query.
(i) Select 100+200 from dual;
(ii) Select 100+200 from Sales;
Ans. (i) 300
(ii) 300
300
300
300
300
18 What is the difference between Equi-Join and Natural Join?
Ans. In Equi join we compare value of any column from two tables and it will return matching
rows. In Equi-join common column appears twice in output because we fetch using (*) not by
specifying column name. for e.g.
In Equi-join it is not mandatory to have same name for column to compare of both table
In natural join also the matching rows will return. In natural join column will appear only
once in output. Then name of column must be same in both table if we are performing
natural join using the clause NATURAL JOIN.
19 Observe the given Table TEACHER and give the output of question (i) and (ii)
TEACHER_CODE TEACHER_NAME DOJ
T001 ANAND 2001-01-30
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20
T004 BALBIR 2010-02-15
T005 JASBIR 2011-01-20
T006 KULBIR 2008-07-11
(i) SELECT TEACHER_NAME,DOJ FROM TEACHER WHERE TEACHER_NAME LIKE „%I%‟
(ii) SELECT * FROM TEACHER WHERE DOJ LIKE „%-09-%‟;
Ans (i)
TEACHER_NAME DOJ
-------------------------------------------------------
AMIT 2007-09-05
ANKIT 2007-09-20
BALBIR 2010-02-15
JASBIR 2011-01-20
KULBIR 2008-07-11

(ii)
TEACHER_CODE TEACHER_NAME DOJ
----------------------------------------------------------------------
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20
20 Which SQL function is used to get the average value of any column?
Ans. AVG()
21 What is the difference between COUNT() and COUNT(*) function
Ans. COUNT() function will count number of values in any column excluding the NULLs
COUNT(*) will count number of rows in query output including NULLs
22 What is the full form of SQL?
Ans. Structured Query Language

Page :2
for more details visit : python4csip.com

23 Query to delete all record of table without deleting the table:


a. DELETE TABLE TABLE_NAME
b. DELETE FROM TABLE_NAME
c. DROP TABLE TABLE_NAME
d. DELETE TABLE FROM TABLE_NAME
Ans. b. DELETE FROM TABLE_NAME
24 Identify the wrong statement about UPDATE command
a. If WHERE clause is missing all the record in table will be updated
b. Only one record can be updated at a time using WHERE clause
c. Multiple records can be updated at a time using WHERE clause
d. None of the above
Ans. b. Only one record can be updated at a time using WHERE clause
25 Identify the correct statement(s) to drop a column from table
a. DELETE COLUMN COLUMN_NAME
b. DROP COLUMN COLUMN_NAME
c. ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME
d. ALTER TABLE TABLE_NAME DROP COLUMN_NAME
Ans. c. ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME
d. ALTER TABLE TABLE_NAME DROP COLUMN_NAME
26 Suppose a table BOOK contain columns (BNO, BNAME, AUTHOR, PUBLISHER), Raj is
assigned a task to see the list of publishers, when he executed the query as:
SELECT PUBLISHER FROM BOOK;
He noticed that the same publisher name is repeated in query output. What could be possible
solution to get publisher name uniquely? Rewrite the following query to fetch unique
publisher names from table.
Ans. Solution is to use DISTINCT clause.
Correct Query : SELECT DISTINCT PUBLISHER FROM BOOK;
27 HOTS
Consider a database table T containing two columns X and Y each of type integer. After the
creation of the table, one record (X=1, Y=1) is inserted in the table.
Let MX and MY denote the respective maximum values of X and Y among all records in the
table at any point in time. Using MX and MY, new records are inserted in the table 128 times
with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after
the insertion, values of MX and MY change. What will be the output of the following SQL
query after the steps mentioned above are carried out?
SELECT Y FROM T WHERE X = 7
A. 127
B. 255
C. 129
D. 257
Ans. A. 127
28 Which SQL function is used to find the highest and lowest value of numeric and date type
column?
Ans. MAX() and MIN()
29 What is the default order of sorting using ORDER BY?
Ans. Ascending
30 What is the difference between CHAR and VARCHAR?
Ans. CHAR is fixed length data type. For example if the column „name‟ if of CHAR(20) then all name
will occupy 20 bytes for each name irrespective of actual data.
VARCHAR is variable length data type i.e. it will occupy size according the actual length of
data

Page :3
for more details visit : python4csip.com

31 Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii) which are based on tables

TABLE: TRANSACT
TRNO ANO AMOUNT TYPE DOT
T001 101 2500 Withdraw 2017-12-21
T002 103 3000 Deposit 2017-06-01
T003 102 2000 Withdraw 2017-05-12
T004 103 1000 Deposit 2017-10-22
T005 102 12000 Deposit 2017-11-06

(i) To display details of all transactions of TYPE Withdraw from TRANSACT table
(ii) To display ANO and AMOUNT of all Deposit and Withdrawals done in month of
„May‟ 2017 from table TRANSACT
(iii) To display first date of transaction (DOT) from table TRANSACT for Account having
ANO as 102
(iv) To display ANO, ANAME, AMOUNT and DOT of those persons from ACCOUNT and
TRANSACT table who have done transaction less than or equal to 3000
(v) SELECT ANO, ANAME FROM ACCOUNT
WHERE ADDRESS NOT IN ('CHENNAI', 'BANGALORE');
(vi) SELECT DISTINCT ANO FROM TRANSACT
(vii) SELECT ANO, COUNT(*), MIN(AMOUNT) FROM TRANSACT
GROUP BY ANO HAVING COUNT(*)> 1
(viii) SELECT COUNT(*), SUM(AMOUNT) FROM TRANSACT
WHERE DOT <= '2017-10-01'
Ans. (i) Select * from TRANSACT where TYPE=’Withdraw’;
(ii) Select ANO, AMOUNT from TRANSACT where DOT like ‘%-05-%’;
(iii) Select MIN(DOT) from TRANSACT where ANO=102
(iv) Select ANO,T.ANO,ANAME,AMOUNT from ACCOUNT A, TRANSACT T where A.ANO = T.ANO and
AMOUNT<=3000;
(v)
ANO ANAME
-------------------------------------
103 Ali Reza
105 Simran Kaur
(vi)
ANO
----------
101
103
102
(vii)

(viii)

Page :4
for more details visit : python4csip.com

32 Consider the following tables EMP and SALGRADE, write the query for (i) to (vi) and output
for (vii) to (x)
TABLE: EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
101 Vikrant Executive S03 2003-03-23 1980-01-13
102 Ravi Head-IT S02 2010-02-12 1987-07-22
103 John Cena Receptionist S03 2009-06-24 1983-02-24
105 Azhar Ansari GM S02 2009-08-11 1984-03-03
108 Priyam Sen CEO S01 2004-12-29 1982-01-19
TABLE: SALGRADE
SGRADE SALARY HRA
S01 56000 18000
S02 32000 12000
S03 24000 8000
(i) To display details of all employee in descending order of their DOJ
(ii) To display NAME AND DESIG of those employees whose sgrade is either „S02‟ or
„S03‟
(iii) To display NAME, DESIG, SGRADE of those employee who joined in the year 2009
(iv) To display all SGRADE, ANNUAL_SALARY from table SALGRADE [where
ANNUAL_SALARY = SALARY*12]
(v) To display number of employee working in each SALGRADE from table EMPLOYEE
(vi) To display NAME, DESIG, SALARY, HRA from tables EMPLOYEE and SALGRADE
where SALARY is less than 50000
(vii) Select MIN(DOJ), MAX(DOB) from employee;
(viii) Select SGrade,Salary+HRA from SalGrade where Sgrade=‟S02‟
(ix) Select count(distinct sgrade) from employee
(x) Select sum(salary), avg(salary) from salgrade
Ans (i) SELECT * FROM EMPLOYEE ORDER BY DOJ DESC
(ii) SELECT NAME,DESIG FROM EMPLOYEE WHERE SGRADE IN ('S02','S03')
OR
SELECT NAME,DESIG FROM EMPLOYEE WHERE SGRADE='S02' OR
SGRADE='S03'
(iii) SELECT NAME,DESIG,SGRADE FROM EMPLOYEE WHERE DOJ LIKE '2009%'
(iv) SELECT SGRADE,SALARY*12 ANNUAL_SALARY FROM SALGRADE
(v) SELECT SGRADE,COUNT(*) FROM EMPLOYEE GROUP BY SGRADE
(vi) SELECT NAME,DESIG,SALARY,HRA FROM EMPLOYEE E,SALGRADE S WHERE
E.SGRADE=S.SGRADE AND SALARY<=50000
(vii) MIN(DOJ) MAX(DOB)
------------------------------------
2003-03-23 1987-07-22
(viii) SGRADE SALARY+HRA
---------------------------------
S02 44000
(ix) COUNT(*)
---------------
3
(x) SUM(SALARY) AVG(SALARY)
--------------------------------------------
112000 37333.33

Page :5
for more details visit : python4csip.com

33

(i) To display details of all Trains which starts from New Delhi
(ii) To display PNR, PNAME, GENDER and AGE of all passengers whose AGE is below
50
(iii) To display total numbers of MALE and FEMALE passengers
(iv) To display records of all passengers travelling in trains whose TNO is 12015
(v) SELECT MAX(TRAVELDATE),MIN(TRAVELDATE) FROM PASSENGERS WHERE
GENDER=‟FEMALE‟;
(vi) SELECT END, COUNT(*) FROM TRAINS GROUP BY END HAVING COUNT(*)>1;
(vii) SELECT DISTINCT TRAVELDATE FROM PASSENGERS;
(viii) SELECT TNAME, PNAME FROM TRAINS T, PASSENGERS P WHERE T.TNO=P.TNO
AND AGE BETWEEN 50 AND 60

Page :6
for more details visit : python4csip.com

Ans (i) SELECT * FROM TRAINS WHERE START='NEW DELHI'


(ii) SELECT PNR,PNAME,GENDER,AGE FROM PASSENGER WHERE AGE<50
(iii) SELECT GENDER,COUNT(*) FROM PASSENGERS GROUP BY GENDER
(iv) SELECT * FROM PASSENGERS WHERE TNO=12015
(v) MAX(TRAVELDATE) MIN(TRAVELDATE)
----------------------------------------------------------
2018-11-10 2018-05-09
(vi) END COUNT(*)
-------------------------------------------
HABIBGANJ 2
AMRITSAR JUNCTION 2
NEW DELHI 4
(vii) TRAVELDATE
-------------------
2018-12-25
2018-11-10
2018-10-12
2018-05-09
(viii) TNAME PNAME
----------------------------------------------------------------------
AJMER SHATABDI P TIWARY
AJMER SHATABDI S TIWARY
AMRITSAR MAIL R N AGRAWAL
AMRITSAR MAIL N S SINGH
SWARNA SHATABDI S K SAXENA
SWARNA SHATABDI S SAXENA
SWARNA SHATABDI J K SHARMA
SWARNA SHATABDI R SHARMA
34 Consider the table SHOPPE and ACCESSORIES, write the query for (i) to (v) and output for
(vi) to (x)

Page :7
for more details visit : python4csip.com

(i) To display Name and Price of all the Accessories in descending order of their Price
(ii) To display Id and Sname of all the Shoppe location in „Nehru Place‟
(iii) To display Name, Minimum and Maximum Price of each Name from ACCESSORIES
table
(iv) To display Name, Price of all Accessories and their respective SName from table SHOPPE
and ACCESSORIES where Price is 5000 or more.
(v) To display all details of accessories where name contains word „Board‟;
(vi) SELECT DISTINCT NAME FROM ACCESSORIES WHERE PRICE>5000;
(vii) SELECT AREA,COUNT(*) FROM SHOPPE GROUP BY AREA;
(viii) SELECT AVG(PRICE), MAX(PRICE) FROM ACCESSORIES WHERE PRICE>=10000;
(ix) SELECT NAME, PRICE*.05 DISCOUNT FROM ACCESSORIES WHERE ID IN („S02‟,‟S03‟)
(x) SELECT * FROM SHOPPE S, ACCESSORIES A WHERE S.ID = A.ID AND PRICE>=10000;
Ans (i) SELECT NAME,PRICE FROM ACCESSORIES ORDER BY PRICE DESC
(ii) SELECT ID,SNAME FROM SHOPPE WHERE AREA='NEHRU PLACE'
(iii) SELECT NAME,MIN(PRICE),MAX(PRICE) FROM ACCESSORIES GROUP BY NAME
(iv) SELECT NAME,PRICE,SNAME FROM SHOPPE S, ACCESSORIES A WHERE
S.ID=A.ID AND PRICE>=5000
(v) SELECT * FROM ACCESSORIES WHERE NAME LIKE „%BOARD%‟
(vi) NAME
-----------
Mother Board
LCD
(vii) AREA COUNT(*)
-------------------------------
CP 2
GK II 1
Nehru Place 2
(viii) AVG(PRICE) MAX(PRICE)
-------------------------------------
12500 13000
(ix) NAME DISCOUNT
-----------------------------------
Keyboard 25
Mother Board 650
Keyboard 20
Hard Disk 225
(x) ID SNAME AREA NO NAME PRICE ID
-------------------------------------------------------------------------------------------------------
S01 ABC Computronics CP A01 Mother board 12000 S01
S02 All Infotech media GK II A05 Mother board 13000 S02

Page :8
for more details visit : python4csip.com

35 a) In a database there are two tables : Write MYSQL queries for (i) to (iii)
Table : Item
ICode IName Price Color VCode
S001 Mobile Phones 30000 Silver P01
S002 Refrigerator 20000 Cherry P02
S003 TV 45000 Black P03
S004 Washing Machine 12000 White P04
S005 Air Conditioner 50000 White P05
Table : Vendor
VCode VName
P01 Rahul
P02 Mukesh
P03 Rohan
P04 Kapil
(i) To display ICode, IName and VName of all the vendors, who manufacture “Refrigerator”.
(ii) To display IName, ICode, VName and price of all the products whose price >=23000
(iii) To display Vname and IName manufactured by vendor whose code is “P04”.
Ans (i) Select ICode, IName,VName from Item I,Vendor V where I.Vcode=V.VCode and
IName='Refrigerator'
(ii) Select IName, ICode,VName from Item I,Vendor V where I.Vcode=V.VCode and
Price>=23000
(iii) Select VName,IName from Item I,Vendor V where I.Vcode=V.VCode and
I.VCode='P04'
b) What will be the output of the following-
1. Select Round(1449.58,-2);
2. Select Round(7.5789,3); IP ONLY
3. Select Substr(“ Hello Rahul”,3,8);
4. Select Dayofmonth(“2020-10-24”);
And 1. 1400
2. 7.579
3. elloh Rah
4. 24
36 In a database there are two tables : Write MYSQL queries for (i) to (vi)
Table : Doctors
DocID DocName Department NoofOpdDays
101 J K Mishra Ortho 3
102 Mahesh tripathi ENT 4
103 Ravi Kumar Neuro 5
104 Mukesh Jain Physio 3
Table : Patients
PatNo PatName Department DocId
1 Payal ENT 102
2 Naveen Ortho 101
3 Rakesh Neuro 103
4 Atul Physio 104
(i) To display PatNo, PatName and corresponding DocName for each patient.
(ii) To display the list of all doctors whose NoofOpdDays are more than 3
(iii) To display DocName, Department,PatName and DocId from both the tables where DocID
is either 101 or 103
(iv) To display total no of different departments from Patients table.

Page :9
for more details visit : python4csip.com

Ans. (i) select PatNo,PatName,DocName from Doctors D,Patients P where D.DocID =


P.DocID
(ii) select * from Doctors where NoofOpdDays>3
(iii) Select DocID,DocName,Department,PatName from Doctor D, Patient P where
D.DocId = P.DocId and DocId in (101,103)
(iv) select count(distinct Department) from Patient
37 Given the Table “BANK” with records, Give the output of given queries –
NAME
SACHIN
RAMESH
DINESH
VIKAASH
RAJU
AMRITESH
i. Select * from BANK where Name Like „%ES%‟;
ii. Select * from BANK where Name Like „_ _ _ _SH‟
Ans i. RAMESH
DINESH
AMRITESH
ii. RAMESH
DINESH
38 Rajesh a database developer at StoreIndia wants to search the record of those employees
whose name starts from „R‟ and they have not allotted any project, for this he has written
the following query-
Select * from Employee where Name = ‘R%’ and Project=Null;
But the query is not producing the correct output. Rewrite the query after correcting the
errors
Ans Select * from Employee where Name like „R%‟ and Project is null
39 Considering the Visitor table data, write the query for (i) to (iv) and output for (v) to (viii)
VisitorID VisitorName Gender ComingFrom AmountPaid
1 Suman F Kanpur 2500
2 Indu F Lucknow 3000
3 Rachana F Haryana 2000
4 Vikram M Kanpur 4000
5 Rajesh M Kanpur 3000
6 Suresh M Allahabad 3600
7 Dinesh M Lucknow
8 Shikha F Varanasi 5000
(i) Write a query to display VisitorName, Coming From details of Female Visitors with
Amount Paid more than 3000
(ii) Write a query to display all coming from location uniquely
(iii) Write a query to insert the following values-
7, „Shilpa‟,‟F‟,‟Lucknow‟,3000
(iv) Write a query to display all details of visitors in order of their AmountPaid from
highest to lowest
(v) Select VisitorName from Visitor where Gender=‟M‟;
(vi) Select AmountPaid+200 from Visitor where VisitorID=6;
(vii) Select Sum(AmountPaid) from Visitor where comingFrom=‟Kanpur‟;
(viii) Select Count(VisitorName) from Visitor where AmountPaid is NULL;

Page :10
for more details visit : python4csip.com

Ans. (i) Select VisitorName,ComingFrom from Visitor where Gender='F' and


AmountPaid>3000
(ii) Select distinct ComingFrom from Visitor
(iii) insert into visitor values(7,'Shilpa','F','Lucknow',3000)
(iv) Select * from visitor order by AmountPaid desc
(v) VisitorName
----------------
Vikram
Rajesh
Suresh
Dinesh
(vi) AmountPaid+200
----------------------
3800
(vii) Sum(AmountPaid)
-----------------------
9500
(viii) Count(VisitorName)
-------------------------
1
40 Write a MySQL query to create the given table (MEMBER)
Column name Datatype Size
ID Char 6
Name Varchar 30
Fee Int 10
DOJ Date
Ans. create table member(id char(6),name varchar(30),fee int(10),doj date)
41 What is the Difference between ALTER Table command and UPDATE command?
Ans. ALTER is DDL command and is used for modifying the schema of table like adding new
column, modifying column definition, dropping column. UPDATE is DML command and is
used for modifying the existing data of table like changing the mobile number, changing the
salary etc.
42 (i) Sanjay was deleting the record of empno=1234, but at the time of execution of command he
forgot to add condition empno=1234, what will be the effect of delete command in this case?
(ii) Sameer is executing the query to fetch the records of employee who are getting salary
between 4000 to 8000, he executed the query as -
Select * from employee where salary between 4000 to 8000;
But he is not getting the correct output, Rewrite the correct query.
Ans. (i) If where clause is missing with DELETE then it will delete all the record of table.
(ii) Select * from employee where salary between 40000 and 80000
43 Write MYSQL command to see the list of tables in current database
Ans. Show tables
44 Sunil decides to delete a PhoneNo column from a MySQL Table (student) after insert the data
into the table. Write the command to delete that particular column in student table.
Ans. ALTER TABLE student drop PhoneNo
45 A table Employee contains 5 Rows and 4 Columns and another table PROJECT contains 5
Rows and 3 Columns. How many rows and columns will be there if we obtain Cartesian
product of these two tables?
Ans. Rows = 5 x 5 = 25
Columns = 4 + 3 = 7
46 Ranjeet created a table named student, He wants to see those students whose name ending
with p. He wrote a query- SELECT * FROM student WHERE name=”p%”;
But the query is not producing the desired output, Help Ranjeet to run the query by removing
the errors from the query and rewriting it.

Page :11
for more details visit : python4csip.com

Ans SELECT * FROM student WHERE name LIE ”p%”;


47 Consider the following EMPLOYEE table write MYSQL command for (i) to (iv) and Outputs for
(v) to (viii)
EMPNO ENAME DEPT SALARY COMM
1 ANKIT HR 20000 1200
2 SUJEET ACCOUNTS 24000
3 VIJAY HR 28000 2000
4 NITIN SALES 18000 3000
5 VIKRAM SALES 22000 1700

(i) To display the name of employees starting from „V‟ in ascending order of their salary
(ii) To display the details of all SALES dept employee who are earning salary more than
20000
(iii) To count distinct department from the table
(iv) Change the salary of NITIN from 18000 to 20000
(v) To insert a new row in the table Employee
„6‟, „SUMIT‟,‟HR‟, 40000,2000
(vi) Select AVG(COMM) from Employee
(vii) Select ENAME,DEPT from Employee where Dept in(„HR‟,‟ACCOUNTS‟)
(viii) Select ENAME, SALARY+100 NEWSAL from Employee
Ans. (i) select ename from employee where ename like 'V%' order by salary;
(ii) Select * from employee where dept='Sales' and salary>20000;
(iii) select count(distinct dept) from employee;
(iv) update employee set salary=20000 where ename='NITIN';
(v) insert into employee values(6,'SUMIT','HR',40000,2000)
(vi) 1980 (including record inserted in (v))
(vii) ENAME DEPT
--------------------------
ANKIT HR
SUJEET ACCOUNTS
VIJAY HR
(viii) ENAME NEWSAL
----------------------------------
ANKIT 20100
SUJEET 24100
VIJAY 28100
NITIN 20100
VIKRAM 22100
SUMIT 40100
48 Write MYSQL command to create the table ENQUIRY including its constraints
Table : ENQUIRY
Name of column Type Size Constraints
visitorID Decimal 4 Primary key
visitorName Varchar 20
visitorMobile Char 10 Not null
visitorAddress Varchar 40
Ans. create table ENQUIRY(visitorID decimal(4) primary key, visitorName varchar(20) visitorMobile
char(10) not null, visitorAddress varchar(40))
49 In a database there are two tables :
Table : Doctor
DocID DocName Specialist
D001 Vimal Jha Cardio
D002 Sunil Bawra Ortho
D003 Mukul Barman Surgeon
D004 Nitesh Solanki Skin

Page :12
for more details visit : python4csip.com

Table : Patient
PatID PatName DateAdm DocID
P001 Kapil 2013-10-10 D002
P002 Susheel 2013-09-01 D001
P003 Wasim 2013-10-15 D002
P004 Sanjay 2013-10-12 D003
P005 Jai 2013-10-17 D003

Write the MySQL queries for the following :


(i) To display PatID, PatName, and corresponding DocName of „Cardio‟ and „Ortho‟
patient
(ii) To display DocName, PatName of those patient who are admitted before 15-Oct-
2013
Ans. (i) select PatID, PatName,DocName from Doctor D, Patient P where D.DocID = P.DocID
and specialist in ('Cardio','Orto');
(ii) select DocName,PatName from Doctor D, patient P where D.DocID =P.DocID and
DateAdm<'2013-10-15'
50 What will be output of following Mysql Queries –
(i) Select Round(55.698,2)
(ii) Select mid(„examination‟,4,4)
(iii) Select Round(4562.778,-2)
IP ONLY
(iv) Select length(trim(„ exam „))

Ans. (i) 55.70


(ii) mina
(iii) 4600
(iv) 4
51 1. Write Query for the following requirements – (STUDENT)
Id NAME STIPEND SUBJECT AVERAGE DIV
1 KARAN 400 PHYSICS 68 1
2 DIVAKAR 450 COMP SC 68 1
3 DIVYA 300 CHEMISTRY 62 2
4 ARUN 350 PHYSICS 63 1
5 SABINA 500 MATHS 70 1
6 JOHN 400 CHEMISTRY 55 2
7 ROBERT 250 PHYSICS 64 1
8 RUBINA 450 MATHS NULL NULL
9 VIKAS 500 COMP SC 62 1
10 MOHAN 300 MATHS 57 2
GUIDE
SUBJECT ADVISOR
PHYSICS ALOK
COMP SC RAJAN
CHEMISTRY MANJU
MATHS SMITA
HISTORY KISHORE
1. TO DISPLAY THE NAME OF STUDENT , SUBJECT AND ADVISOR NAME
2. TO DISPLAY THE STUDENT NAME AND ADVISOR ALL THE STUDENTS WHO ARE
OFFERING EITHER PHYSICS OR CHEMISTRY

Page :13
for more details visit : python4csip.com

Ans. 1. Select Name,Subject,Advisor from Student S,Guide G where S.subject = G.subject;


2. Select Name,Advisor from Student S,Guide G where S.subject = G.subject and
S.subject in ('Physics','Chemistry')
52 DIFFERENCE BETWEEN
1. HAVING AND WHERE
2. % AND _
3. CHAR AND VARCHAR
Ans. (1)
HAVING – this clause is used with GROUP BY to filter the group of records. We can use
aggregate functions with HAVING.
WHERE – this clause is used to apply condition on all the rows of table. We cannot use
aggregate functions with WHERE.

(2) % is a wildcard character used with LIKE and it is used for substituting multiple
characters while matching the pattern. Matching text can be of any length
_ (underscore) is also a wildcard character used with LIKE but it substitute only single
character at given position while matching the pattern. Length will be fixed.

(3) Refer to Answer no. 30


53 OUTPUT –
a. Select Substring(„mysql application‟,3,3)
b. Select instr(„mysql application‟,‟p‟);
c. Select round(7756.452,1); IP ONLY
d. Select round(59999.99,-2);
e. Select right(„mysql application‟,3);
Ans. a. sql
b. 8
c. 7756.5
d. 60000
e. Ion

Page :14
SQL exercises, based on dreamhome database
Datatbase system:
1. Login to mysql database server imc.kean.edu using xxx account
ANS:
mysql -u xxx -p -h imc.kean.edu
2. Switch to database dreamhome
ANS:
use dreamhome;
3. Show all tables in dreamhome database
ANS:
show tables;
4. Show the table structure (column name, datatype, keys, etc) of Staff table
ANS:
desc Staff;

SELECT:
5. Show all the rows and all the columns of Staff table
ANS:
SELECT * FROM Staff;
6. Produce a list of salaries for all staff, showing only the staff number, the first and last names, and
the salary details.
ANS:
SELECT staffNo, fName, IName, salary FROM Staff;
7. List full details of all hotels in London.
ANS:
SELECT * FROM Hotel WHERE city = 'London';
8. List the unique property numbers of all properties that have been viewed.
ANS:
SELECT DISTINCT propertyNo FROM Viewing;
9. Write a SQL query to list the staff who work in London. Please show their first name, last name and
branchno.
ANS:
SELECT fname,lname,b.branchno FROM Staff s, Branch b
WHERE s.branchno=b.branchno and b.city='London';
10. Produce a list of monthly salaries for all staff, showing the staff number, the first and last names,
and the salary details.
ANS:
SELECT staffNo, fName, IName, salary/12 FROM Staff;
11. List all staff with a salary greater than $10,000.
ANS:
SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > 10000;
12. Write a SQL query to display the name for vendor lives in New York with zipcode 07811.
(refer to A_Vendors)
ANS:
SELECT name from A_Vendors where State = 'NY' and Zipcode='07811';
13. Write a SQL query to list the unique position for female staff with salary less than 10000.
ANS:
SELECT distinct position FROM Staff WHERE sex='F' and salary < 10000;
14. List the addresses of all branch offices in London or Glasgow.
ANS:
SELECT street FROM Branch WHERE city = 'London' OR city = 'Glasgow';
15. Write a SQL query to display product names that make profit < 20. (refer to A_Products)
ANS:
SELECT name FROM A_Products WHERE sell_price - cost < 20;
16. List all staff with a salary between $20,000 and $30,000.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary BETWEEN 20000 AND 30000;
ANS 2:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > = 20000 AND salary < = 30000;
17. List all managers and supervisors.
ANS:
SELECT staffNo, fName, IName, position FROM Staff WHERE position IN ('Manager', 'Supervisor');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff WHERE position = 'Manager' OR position =
'Supervisor';
18. What is the output of the following SQL query?
SELECT clientno, propertyno FROM Viewing WHERE comment!='';
ANS:
+----------+------------+
| clientno | propertyno |
+----------+------------+
| CR56 | PA14 |
| CR62 | PA14 |
| CR76 | PG4 |
+----------+------------+
19. List all double or family rooms with a price below 40.00 per night, in ascending order of price.
ANS:
SELECT * FROM Room WHERE price < 40 AND type IN ('double', 'family') ORDER BY price;
20. Find all owners with the string ‘Glasgow’ in their address.
ANS:
SELECT ownerNo, fName, IName, address, telNo
FROM PrivateOwner WHERE address LIKE '%Glasgow%';
21. Write a SQL query to display the total number of Customers living in Union.
ANS:
SELECT count(name) FROM A_Customers WHERE address like '%Union%';
22. List the details of all viewings on property PG4 where a comment has not been supplied.
ANS:
SELECT clientNo, viewDate FROM Viewing WHERE propertyNo = 'PG4' AND comment IS NULL;
23. Produce a list of salaries for all staff, arranged in descending order of salary.
ANS:
SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC;
24. Produce an abbreviated list of properties arranged in order of property type.
ANS:
SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type;
25. List the names and addresses of all guests in London, alphabetically ordered by name.
ANS:
SELECT guestName, guestAddress FROM Guest
WHERE guestAddress LIKE '%London%' ORDER BY guestName;

AGGREGATE FUNCTIONS, GROUP BY:


26. Write a SQL query to display the number of unique products been reviewed (A_Reviews table).
ANS:
SELECT count(distinct p_id) FROM A_Reviews;
27. Write a SQL query to display the total salary of all staff.
ANS:
SELECT SUM(salary) from Staff;
28. What is the output of the following SQL query?
SELECT max(price) as myMax FROM Room WHERE type='family';
ANS:
+-------+
| myMax |
+-------+
| 59.99 |
+-------+
29. What is the output of the following SQL query?
SELECT type, count(*) as ct,max(price) FROM Room group by type having ct > 3;
ANS:
+--------+----+------------+
| type | ct | max(price) |
+--------+----+------------+
| double | 4 | 86.00 |
| single | 5 | 58.00 |
+--------+----+------------+
30. Write a SQL query to list the unique branchno that branch has at least two female staff.
ANS:
SELECT distinct branchno FROM Staff group by branchno,sex having count(sex) >= 2 and sex='F';
31. Write a SQL query to display the total revenues of all products. The output column name should be
“revenue”.
ANS:
SELECT sum(sell_price*quantity) as revenue FROM A_Products;
32. Write the SQL query to show the branchno and the maximum salary for each branch in the Staff
table. The output should be sorted from high to low based on the max salary of each branch;
ANS:
SELECT branchno, max(salary) FROM Staff group by branchno order by max(salary) desc;
33. Can we run the following SQL query without any problem?
SELECT fname FROM Staff WHERE salary > max(salary);
ANS:
NO, the statement invalid use of group function. Aggregation cannot be in WHERE.
34. Write the SQL query to find how many properties cost more than $350 per month to rent?
ANS:
SELECT COUNT(*) AS myCount FROM PropertyForRent WHERE rent > 350;
35. How many different properties were viewed in May 2013?
ANS:
SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing WHERE viewDate BETWEEN '2013-05-01' AND '2013-05-31';
36. Find the total number of Managers and the sum of their salaries.
ANS:
SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff WHERE position =
'Manager';
37. Find the minimum, maximum, and average staff salary.
ANS:
SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg FROM Staff;
38. What is the total revenue per night from all double type rooms if all rooms are booked?
ANS:
SELECT SUM(price) FROM Room WHERE type = 'double';
39. Find the number of staff working in each branch and the sum of their salaries.
ANS:
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY
branchNo ORDER BY branchNo;
ANS 2:
SELECT branchNo, ( SELECT COUNT(staffNo) AS myCount FROM Staff s
WHERE s.branchNo = b.branchNo ), ( SELECT SUM(salary) AS mySum FROM Staff s WHERE
s.branchNo = b.branchNo )FROM Branch b ORDER BY branchNo;
40. For each branch office with more than one member of staff, find the number of staff working in
each branch and the sum of their salaries.
ANS:
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff GROUP BY branchNo HAVING COUNT(staffNo) > 1 ORDER BY branchNo;
41. List the hotel name and the number of rooms in each hotel.
ANS:
SELECT h.hotelname, COUNT(r.roomNo) AS count
FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
42. What is the output of the following SQL statement?
SELECT count(comment) FROM Viewing;
ANS:
+----------------+
| count(comment) |
+----------------+
| 4 |
+----------------+
43. Show the total revenue per night for the double type room if all rooms are booked.
ANS:
SELECT SUM(price) FROM Room WHERE type = 'double';

SUBQUERY:
44. Write a SQL query to find the staff name (first name, last name) who has salary higher than the
average salary of branchno =’B003’;
ANS:
SELECT fname,lname FROM Staff where salary > (select avg(salary) from Staff
WHERE branchno ='B003');
45. Can we run the following query without any problem?
SELECT city FROM Branch WHERE branchNo = (SELECT branchNo FROM Staff where sex='F');
ANS:
Error, Subquery returns more than 1 row. Cannot use =, should use IN
46. What is the output of the following SQL query?
SELECT c.name FROM A_Customers c WHERE c.id NOT in (SELECT c_id FROM A_Reviews);
ANS:
+-------+
| name |
+-------+
| BJ2 |
| BJ3 |
| Judy1 |
| Judy2 |
+-------+
47. What is the output of the following SQL query?
SELECT count(distinct(city)) as myCt FROM Hotel WHERE hotelno in (SELECT hotelno FROM Room
WHERE type='single');
ANS:
+------+
| myCt |
+------+
| 3 |
+------+
48. Write a SQL query to display the staffno and working branch city for the staff who has the lowest
salary.
ANS:
SELECT s.staffno,b.city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and s.salary in (SELECT min(salary) FROM Staff);
49. List the staff who work in the branch at ‘163 Main St’.
ANS:
SELECT staffNo, fName, IName, position FROM Staff
WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff s, Branch b
WHERE s.branchNo = b.branchNo and street = '163 Main St';
50. List all guests staying at the Grosvenor Hotel from April 1st to August 31st, 2004.
ANS:
SELECT * FROM Guest WHERE guestNo in (
SELECT guestNo FROM Booking
WHERE dateFrom >= date('2004-04-01') AND dateFrom <= date('2004-08-31')
AND hotelNo = (SELECT hotelNo FROM Hotel WHERE hotelName = 'Grosvenor'));
51. List all staff whose salary is greater than the average salary, and show by how much their salary is
greater than the average.
ANS:
SELECT staffNo, fName, LName, position, (salary - (SELECT AVG(salary) FROM Staff)) AS salDiff FROM
Staff WHERE salary > (SELECT AVG(salary) FROM Staff);
ANS 2:
SELECT staffNo, fName, LName, position, (salary-a.avg1) AS salDiff
FROM Staff s, (SELECT AVG(salary) as avg1 FROM Staff) a WHERE salary > a.avg1;
52. List the properties that are handled by staff who work in the branch at ‘163 Main St’.
ANS:
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent WHERE staffNo IN (SELECT staffNo
FROM Staff WHERE branchNo = (SELECT branchNo
FROM Branch WHERE street = '163 Main St'));
53. Find all staff whose salary is larger than the salary of at least one member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > SOME (SELECT salary FROM Staff WHERE branchNo = 'B003');
54. Find all staff whose salary is larger than the salary of every member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > ALL (SELECT salary FROM Staff WHERE branchNo = 'B003');
55. Write a SQL query to show client names who didn’t give reviews (Viewing table).
ANS:
SELECT c.fname,c.lname FROM Client c
WHERE c.clientno NOT in (SELECT clientno FROM Viewing);
56. What is the most commonly booked room type for each hotel in London?
ANS:
select hotelname, type, max_ct
from
( select hotelno, max(ct) max_ct from
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) t
group by hotelno ) n,
Hotel h,
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) r
where n.hotelno=h.hotelno and r.hotelno=n.hotelno and h.city='London'and max_ct=ct;

57. Write a SQL query to display the cheapest product name (A_Products table) and its price.
ANS:
SELECT name, sell_price FROM A_Products
WHERE sell_price = (SELECT min(sell_price) FROM A_Products);

(INNSER) JOIN
58. How many rows and columns will be generated from the following SQL query?
SELECT * FROM A_Students, A_Courses;
ANS:
6 columns and 8 rows
59. Write a SQL statement to show the product names provided by vendor “James”.
(refer to A_Products, A_Vendors tables)
ANS:
SELECT p.name FROM A_Products p, A_Vendors v WHERE v.name='James' and p.V_Id=v.V_Id;
60. Write a SQL query to show the first name who works at London and has salary higher than 10000.
ANS:
SELECT fname FROM Branch b, Staff s
WHERE b.branchno=s.branchno and b.city='London' and s.salary > 10000;
61. List the names of all clients who have viewed a property, along with any comments supplied.
ANS:
SELECT c.clientNo, fName, IName, propertyNo, comment
FROM Client c, Viewing v WHERE c.clientNo = v.clientNo;
62. Write a SQL query to list employee names (first name, last name) and their Supervisor names (first
name, last name). The output header must clearly indicates who is employee and Supervisor. (refer
to A_Employee table)
ANS:
SELECT e.fname as E_fname, e.lname as E_lname, m.fname as M_fname, m.lname as M_lname
FROM A_Employee e, A_Employee m WHERE e.super_ssn=m.ssn;
63. For each branch office, list the staff numbers and names of staff who manage properties and the
properties that they manage.
ANS:
SELECT s.branchNo, s.staffNo, fName, IName, propertyNo
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
ORDER BY s.branchNo, s.staffNo, propertyNo;
64. For each branch, list the staff numbers and names of staff who manage properties, including the city
in which the branch is located and the properties that the staff manage.
ANS:
SELECT b.branchNo, b.city, s.staffNo, fName, IName, propertyNo
FROM Branch b, Staff s, PropertyForRent p
WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo
ORDER BY b.branchNo, s.staffNo, propertyNo;
65. Display the product names and the comments that customer BJ1 gave.
(refer to A_Cusomters, A_Reviews, A_Products)
ANS:
SELECT p.name, comments FROM A_Customers c, A_Reviews r, A_Products p
WHERE c.id=r.c_id and p.id=r.p_id and c.name='BJ1' ;
66. List the guestname, hotelname, number of days stayed, and the total amount needed to pay to the
hotel for every guest.
ANS:
select guestname, hotelname, datediff(dateto,datefrom), sum(datediff(dateto,datefrom)*price)
from Guest g, Hotel h, Room r, Booking b
where h.hotelno=b.hotelno and r.roomno=b.roomno and g.guestno=b.guestno
and dateto is not null group by guestname,hotelname;
67. Find the number of properties handled by each staff member, along with the branch number of the
member of staff.
ANS:
SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo ORDER BY s.branchNo, s.staffNo;
68. Find all staff who work in a London branch office.
ANS:
SELECT staffNo, fName, IName, position
FROM Staff s WHERE EXISTS (SELECT * FROM Branch b
WHERE s.branchNo = b.branchNo AND city = 'London');
ANS 2:
SELECT staffNo, fName, IName, position
FROM Staff s, Branch b WHERE s.branFchNo = b.branchNo AND city = 'London';

OUTER JOIN:
69. List all branch offices and any properties that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
70. List all properties and any branch offices that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
71. List the branch offices and properties that are in the same city along with any unmatched branches
or properties.
ANS:
SELECT b.*, p.* FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;
72. How many rows will be generated from the following SQL statement:
SELECT * FROM Staff s RIGHT JOIN Branch b ON s.branchno=b.branchno;
ANS:
8 rows
73. Write a SQL query to display all customer names (A_Customers) and their number of Reviews
(A_Reviews). If a customer didn’t give review, his/her number of review will be 0. The output should
have customer name in alphabetic order from A to Z.
ANS:
SELECT c.name, count(r.c_id) FROM A_Customers c
LEFT JOIN A_Reviews r on r.c_id= c.id group by c.id order by c.name ASC;

SET (UNION, INTERSECT, EXCEPT):


74. Construct a list of all cities where there is either a branch office or a property.
ANS:
(SELECT city FROM Branch WHERE city IS NOT NULL)
UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);
75. Construct a list of all cities where there is both a branch office and a property.
ANS 1:
(SELECT city FROM Branch) INTERSECT (SELECT city FROM PropertyForRent);
ANS 2:
SELECT DISTINCT b.city FROM Branch b,PropertyForRent p WHERE b.city=p.city;
76. Write a SQL query to find the vendor names not providing any products.
(refer to A_Vendors, A_Products tables)
ANS:
SELECT name FROM A_Vendors where V_Id not in (SELECT V_Id from A_Products);
77. Construct a list of all cities where there is a branch office but no properties.
ANS:
(SELECT city FROM Branch) EXCEPT (SELECT city FROM PropertyForRent);
ANS 2:
SELECT DISTINCT city FROM Branch WHERE city NOT IN (SELECT city FROM PropertyForRent);

INSERT:
78. Insert a new row into the Staff table supplying data for all columns.
ANS:
INSERT INTO Staff VALUES
('SG16', 'Alan', 'Brown', 'Assistant', 'M', DATE '1957-05-25', 8300, 'B003');
79. Insert a new row into the Staff table supplying data for all mandatory columns: staffNo, fName,
IName, position, salary, and branchNo.
ANS:
INSERT INTO Staff (staffNo, fName, IName, position, salary, branchNo)
VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B003');
ANS 2:
INSERT INTO Staff VALUES ('SG44’, 'Anne’, 'Jones’, 'Assistant’, NULL, NULL, 8100, 'B003’);
80. Assume that there is a table StaffPropCount that contains the names of staff and the number of
properties they manage: StaffPropCount(staffNo, fName, IName, propCount)
Write a SQL to populate the StaffPropCount table using details from the Staff and PropertyForRent
tables.
ANS:
INSERT INTO StaffPropCount (SELECT s.staffNo, fName, IName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo GROUP BY s.staffNo, fName, IName)
UNION
(SELECT staffNo, fName, IName, 0 FROM Staff s
WHERE NOT EXISTS (SELECT * FROM PropertyForRent p WHERE p.staffNo = s.staffNo));

UPDATE:
81. Give all staff a 3% pay increase.
ANS:
UPDATE Staff SET salary = salary*1.03;
82. Give all Managers a 5% pay increase. (Refer to Staff table)
ANS:
UPDATE Staff SET salary = salary*1.05 WHERE position = 'Manager';
83. Promote David Ford (staffNo = ‘SG14’) to Manager and change his salary to $18,000.
(Refer to Staff table)
ANS:
UPDATE Staff SET position = 'Manager', salary = 18000 WHERE staffNo = 'SG14';

DELETE:
84. Delete all viewings that relate to property PG4.
ANS:
DELETE FROM Viewing WHERE propertyNo = 'PG4';
85. Delete all rows from the Viewing table.
ANS:
DELETE FROM Viewing;
86. Delete the record that has the NULL value in QTY field in the A_Sales table
ANS:
DELETE FROM A_Sales WHERE QTY is null;
87. Create the Staff table with proper data type for each field and staffno is the primary key, branchno
is a foreign key reference to the primary key branchno in the Branch table. All the fields cannot be
NULL.
ANS:
CREATE TABLE Staff (staffno varchar(5) not null, fName varchar(15) not null, lName varchar(15) not
null, position varchar(25) not null, Sex char(1) not null, DOB date not null, salary decimal(8,2) not
null, branchno varchar(8) not null, primary key (staffno), foreign key (branchno) references
Branch(branchno));

ALTER:
88. Add a new column TEL varchar(20) to the staff table;
ANS:
ALTER TABLE Staff ADD TEL varchar(25);
89. Change the Staff table by removing the default of ‘Assistant’ for the position column and setting the
default for the sex column to female (‘F’).
ANS:
ALTER TABLE Staff ALTER position DROP DEFAULT;
ALTER TABLE Staff ALTER sex SET DEFAULT 'F';

VIEW:
90. Create a view vTest listing all double or family rooms with a price below 40.00 per night, in
ascending order of price.
ANS:
CREATE VIEW vTest as SELECT * FROM Room
WHERE price < 40 AND type IN ('double', 'family') ORDER BY price asc;
91. Create a view vTest to list the number of rooms in each hotel.
ANS:
SELECT h.hotelname, COUNT(r.roomNo) AS count
FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
92. Create a view vTest to list the hotel name and the total number of rooms with price per room below
40.00 per night.
ANS:
CREATE VIEW vTest as SELECT h.hotelname,count(*) FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno and r.price < 40 group by h.hotelno;
93. Create a view so that the manager at branch B003 can see the details only for staff who work in his
or her branch office.
ANS:
CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchNo = 'B003';
94. Create a view of the staff details at branch B003 that excludes salary information, so that only
managers can access the salary details for staff who work at their branch.
ANS:
CREATE VIEW Staff3 AS SELECT staffNo, fName, IName, position, sex
FROM Staff WHERE branchNo = 'B003';
95. Create a view vTest to show the first name and the working city for staff who was born after January
first 1960.
ANS:
SELECT fname, city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and birthday > '1960-01-01';
96. Create a view vTest to find the total revenue per night for each hotel and the revenue is higher than
85 dollars. Assume all rooms are booked. Your output needs to show the hotel name and the
amount of revenue.
ANS:
SELECT h.hotelno, SUM(price) as revenue FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno group by h.hotelno having revenue > 85;
97. Create a view of staff who manage properties for rent, which includes the branch number they work
at, their staff number, and the number of properties they manage
ANS:
CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)
AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;

GRANT, REVOKE:
98. Give the user with authorization identifier Manager all privileges on the Staff table.
ANS:
GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION;
99. Give users Personnel and Director the privileges SELECT and UPDATE on column salary of the Staff
table.
ANS:
GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director;
100. Give user xyz from IP ’10.20.30.40’ the privileges SELECT on column salary of the Staff table.
ANS:
GRANT SELECT (salary) ON test TO 'xyz'@'10.20.30.40';
101. Remove user xyz’s SELECT privilege from test the test table.
ANS:
REVOKE SELECT on test from xyz;
102. Remove user xyz’s all privileges from test the test table.
ANS:
REVOKE ALL PRIVILEGES on test from xyz;

DROP:
103. Remove a table Data from the database.
ANS:
DROP TABLE table Data;
104. Remove a view vData from the database.
ANS:
DROP VIEW vData;
105. Remove a stored procedure pTest() from the database.
ANS:
DROP procedure pTest;
106. Remove a stored function fTest() from the database.
ANS:
DROP function fTest;
107. Remove a user xyz from the database.
ANS:
DROP USER xyz;

SQL Syntax and runtime issues:


108. Can the following SQL be run without error?
SELECT staffNo, COUNT(salary) FROM Staff;
Yes, it has no syntax error, but the result is meaningless.
109. Can the following SQL be run without error?
SELECT staffNo FROM Staff where salary=max(salary);
No, this query is illegal because the aggregation function max() cannot be compared directly.
110. Is the following view updatable? CREATE VIEW vTest AS SELECT count(*) as ct FROM Staff;
ANS:
No, because the view is created with an aggregate function count()
111. Is the following view updatable? CREATE VIEW vTest AS SELECT fname, lname as ct FROM
Staff;
ANS:
Yes, because every record in vTest can be traced back to the original record in Staff.
112. Is the following view updatable? CREATE VIEW vTest AS SELECT distinct branchno FROM
Staff;
ANS:
No, because the view is created with the distinct keyword.
113. Is the following view updatable?
CREATE VIEW vTest AS SELECT sex FROM Staff GROUP BY sex;
ANS:
No, because the view is created with GROUP BY.
114. Is the following view updatable?
CREATE VIEW vTest AS SELECT branchno, sum(salary) FROM Staff GROUP BY branchno;
ANS:
No, because the view is created with an aggregate function sum() and GROUP BY.
115. Is the following view updatable?
CREATE VIEW vTest AS SELECT staffno,salary from Staff order by salary;
ANS:
Yes, because every record in vTest can be traced back to the original record in Staff. ORDER BY does
not affect the trace.

VARIABLE, ASSIGNMENTS, COMPARISON:


116. What is the output for the following SQL:
SELECT 2=2,3=2,1=NULL, NULL=NULL, NULL IS NULL;
ANS:
+-----+-----+--------+-----------+--------------+
| 2=2 | 3=2 | 1=NULL | NULL=NULL | NULL is NULL |
+-----+-----+--------+-----------+--------------+
| 1 | 0 | NULL | NULL | 1 |
+-----+-----+--------+-----------+--------------+
117. What is the output for the following SQL:
SELECT @a1:=3, @a2=4, @a3=@a2+1;
ANS:
+--------+-------+-----------+
| @a1:=3 | @a2=4 | @a3=@a2+1 |
+--------+-------+-----------+
| 3 | NULL | NULL |
+--------+-------+-----------+

118. What is the output for the following SQL:


SELECT @a1:=3, @a2:=4, @a3:=@a2+@a1;
ANS:
+--------+--------+--------------+
| @a1:=3 | @a2:=4 | @a3:=@a2+@a1 |
+--------+--------+--------------+
| 3 | 4 | 7 |
+--------+--------+--------------+
119. What is the output for the following SQL:
SELECT null and 1, null and 0, 1 and 0, null or 1, null or 0, 1 or 0, not null;
+------------+------------+---------+-----------+-----------+--------+----------+
| null and 1 | null and 0 | 1 and 0 | null or 1 | null or 0 | 1 or 0 | not null |
+------------+------------+---------+-----------+-----------+--------+----------+
| NULL | 0 | 0 | 1 | NULL | 1 | NULL |
+------------+------------+---------+-----------+-----------+--------+----------+

STORED ROUTINES:
120. Write the SQL statement to run a stored function named fMaxSalary()which will return the
staff’s highest salary.
ANS:
SELECT fMaxSalary();
121. Write a stored function named fMaxSalary() which will return the staff’s highest salary.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary() RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff;
RETURN maxSalary ;
END $$
DELIMITER ;
122. Write a stored function named fMaxSalary(bno) which will return the staff’s highest salary
for a given branch no bno.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(bno varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE branchno=bno;
RETURN maxSalary ;
END $$
DELIMITER ;
123. Write a stored function named fMaxSalary(n) which will return the staff’s highest salary for a
given input that is a partial string in the first name field.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(n varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE fname like concat('%',n,'%');
RETURN maxSalary ;
END $$
DELIMITER ;
124. Write the SQL statement to run a stored procedure named pGetNames()which will display the
Staff’s first name and last name who work at branch located at a given city ‘London’.
ANS: call pGetNames('London');
125. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity.
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END $$
DELIMITER ;
126. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity. If the bcity is empty ‘’, please print a message saying
“The input city cannot be empty.”
call pGetNames(''); call pGetNames('London');
+-----------------------------+ +-------+-------+
| message | | fname | lname |
+-----------------------------+ +-------+-------+
| Input city cannot be empty. | | John | White |
+-----------------------------+ | Julie | Lee |
+-------+-------+
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
if (bcity='') THEN
SELECT 'Input city cannot be empty.' as message;
ELSE
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END IF;
END $$
DELIMITER ;
My SQL Worksheet-1
(DDL – Database Related commands)
1. If a database "Employee" exists, which MySql command helps you to start working in
that database?
Use Employee;

2. Write MySql command will be used to open an already existing database "LIBRARY".
Use Library;

3. Write MySql command to open an existing database.


Use databasename;

4. What does SQL stand for? What is MySQL?


SQL Stands for structured query language.
Mysql is an open source RDBMS (Relational Database Management System)

5. Write two examples of DBMS software.


SQL Server, My SQL, Oracle, Ingres, Postgres

6. Sharmila wants to make the database named ‘COMPANY’ active. Write MySQL
commands for it.
Use Company;

7. What is MySQL ?
Mysql is an open source RDBMS (Relational Database Management System)

8. What is the relationship between SQL and MySQL ?


SQL is a language to give commands in MySQL or any other RDBMS software.

9. Mention any two example of common Database Management System.


SQL Server, Ingres, Postgres, MySQL

10 Suggest Archana suitable command for the following purpose:


. i. To display the list of the database already existing in MySQL.
ii. To use the database named City.
iii. To remove the pre-existing database named Clients.
i. Show Databases;
ii. Use City;
iii. Drop database clients;

11 Write the command to display the name of the active database.


.
Select Database();

12 Write the command to create a new database “School”


.
Create database school;

1
Informatics Practices
My SQL Worksheet-2
(DDL – Table Related commands excluding Alter table)
1. Write an SQL query to create the table 'Menu' with the following structure:

Create table Menu(


ItemCode varchar(5) Primary key,
Itemname varchar(20),
Category Varchar(20),
Price Decimal(5,2));
2. Can a table have multiple primary keys? Can it have multiple foreign keys?
No, a table cannot have multiple primary keys. There can only be one primary
key.
Yes, a table can a multiple foreign keys.

3. In a Student table, out of Roll Number, Name, Address which column can be set as Primary
key and why?
RollNumber can be set as Primary Key as two students cannot have a same roll
number.

4. Ms. Mirana wants to remove the entire content of a table "BACKUP" alongwith its structure
to release the storage space. What MySql statement should she use ?
Drop Table Backup;

5. Write MySql command to create the Table STOCK including its Constraints.
Table STOCK :

Create table Stock(


Id Decimal(4) Primary Key,
Name Varchar(20),
Company Varchar(20),
Price Decimal(8) Not Null);
6. Write one similarity and one diference between CHAR and VARCHAR data types.
Similarity:
Both char and varchar can store alphabets as well as numbers. Both can store
same type of values.

Diference:
Char is a fied length character datatype whereas varchar is a variable length
character datatype.

7. Saumya had previously created a table named ‘Product’ in a database using MySQL. Later
on she forgot the table structure. Suggest her suitable MySQL command through which
she can check the structure of the already created table.
Describe Product;

2
8. Roli wants to list the names of all the tables in her database named ‘Gadgets’. Which
command (s) she should use to get the desired result.
Use Gadgets;
Show tables;
9. Name the SQL commands used to :
(i) Physically delete a table from the database.
(ii) Display the structure of a table.
i) Drop table tablenae;
ii) Describe tablename;
10 Write one similarity and one diference between UNIQUE and PRIMARY KEY constraints.
.
Similarity:
Both Unique and primary key restricts duplicate values in the feld.
Diference:
Unique allows null values whereas Primary doesnot allow null values to be
inserted in the feld.
11 An attribute A of datatype varchar(20) has the value “Amit” . The attribute B of datatype
. char(20) has value ”Karanita” . How many characters are occupied in attribute A ? How
many characters are occupied in attribute B?
A will occupy 4 character space.
B will occupy 20 character space.
12 Mrs. Sharma is the classteacher of Class ‘XII A’ She wants to create a table ‘Student’
. to store details of her class.
i) Which of the following can be the attributes of Student table?
a) RollNo b) “Amit” c) Name d) 25
ii) Name the Primary key of the table ‘Student’. State reason for choosing it.
i) RollNo and Name can be the attributes of student table.
ii) RollNo can become the primary key of the student table as two students
cannot have a same roll number.
13 Write SQL query to create a table ‘Player’ with the following structure:
.

Create table Player(


Playerid integer primary key,
Name varchar(50),
Height integer,
Weight integer,
Datebirth date,
Teamname varchar(50));
14 Anita has created the following table with the name ‘Order’.
.

One of the rows inserted is as follows :

3
(i) What is the data type of columns OrderId and OrderDate in the table Order ?
(ii) Anita is now trying to insert the following row :

Will she be able to successfully insert it ? Give reason.


i)The datatype for orderID feld can be either char or varchar
The datatype for orderDate is date
ii) She will not be able to insert the above record as she is inserting a null
value in the orderdate feld and the orderdate feld have a not null constraint
which cannot accept null values.
15 Write SQL query to create a table ‘Event’ with the following structure :
. Field Type Constraint
EventId Varchar(5) PRIMARY KEY
EventName Varchar(30) NOT NULL
Location Varchar(50)
ClientID Integer
EventDate Date
Create table Event(
EventID varchar(5) Primary Key,
EventName varchar(30) not null,
Location varchar(50),
CleintID Integer,
EventDate date);
16 Observe the given table carefully and answer the following questions:
.

i. Name the column that might have a Primary Key constraint. Justify your answer.
ii. Name the column that might have a Unique constraint. Justify your answer.
i. PanNo might have a Primary Key constraint as two person cannot have
a same Pan Number.
ii. PhoneNo might have a unique constraint as two person will be having
diferent mobile numbers.
17 “ABC” Event Management Company requires data of events that are to be organized.
. Write SQL query to create a table ‘Event’ with the following structure :

4
Create table Event(
EventID Integer Primary Key,
Event Varchar(50),
DateEvent Date,
NumPerformers Integer);
18 suggest her suitable command for the following purpose:
. i. To display the list of the database already existing in MySQL.
ii. To use the database named City.
iii. To remove the pre-existing database named Clients.
iv. To remove all the records of the table named “Club” at one go along with its
structure permanently.
i. Show databases;
ii. Use City;
iii. Drop database Clients;
iv. Drop table Club;
19 While creating a table named “Employee”, Mr. Rishi got confused as which data type he
. should chose for the column “EName” out of char and varchar. Help him in choosing the
right data type to store employee name. Give valid justifcation for the same.
EName feld can have a varchar as a datatype as two employees will not be
having a same length of their names.

Informatics Practices
My SQL Worksheet-3
(DDL – Table Related commands)
1. Sahil created a table in Mysql. Later on he found that there should have been another
column in the table. Which command should he use to add another column to the table?
Alter table tablename add feldname datatype(size);

2. While creating a table 'Customer' Simrita forgot to set the primary key for the table. Give
the statement which she should write now to set the column 'CustiD' as the primary key of
the table?
Alter table customer add primary key(custid);

3. Kuhu has already created a table ‘Hospital’ as shown below:

Now she wants to add a new column ‘Address’ to the above given table. Suggest suitable
MySQL command for the same.
Alter table hospital add address varchar(30);

4. Write SQL command to remove column named ‘Hobbies’ from a table named ‘Student’.

5
Alter table student drop hobbies;

5. While creating the table Student last week, Ms. Sharma forgot to include the column
Game_Played. Now write a command to insert the Game_Played column with VARCHAR
data type and 30 size into the Student table?
Alter table student add game_played varchar(30);

6. Kunal created the following table with the name ‘Friends’ :


Table : Friends

FriendCode Name Hobbies


F101 Bijoy Swimming
F102 Abhinav Reading books
F103 Jyotsna Dancing
Now, Kunal wants to delete the ‘Hobbies’ column. Write the MySQL statement
Alter table friends drop hobbies;

7. Rashi wants to add another column ‘Hobbies’ with datatype and size as VARCHAR(50) in
the already existing table ‘Student’. She has written the following statement. However it
has errors. Rewrite the correct statement.
MODIFY TABLE Student Hobbies VARCHAR;
Alter table student add hobbies varchar(50);
8. Ms. Shalini has just created a table named “Employee” containing columns
Ename, Department, Salary.
After creating the table, she realized that she has forgotten to add a primary key column
in the table. Help her in writing SQL command to add a primary key column empid. Also
state the importance of Primary key in a table.
Alter table employee add primary key(empid);

9. While creating a table 'Customer' Simrita wrongly added a primary key constraint to the
feld “CUSTNAME”. Now she wants to remove the primary key constraint from the
custname feld. Help her in writing the correct command.
Alter table customer ass primary key(custname);

10 Mr. Akshat have added a not null constraint to the “name” feld in “employees” table. But
. now he wants to remove that not null constraint. Write the command to delete the not
null constraint from name feld.
Alter table employee modify name varchar(30) null;

6
Informatics Practices
My SQL Worksheet-4
(DML – INSERT INTO commands)
1. Rama is not able to change a value in a column to NULL. What constraint did she specify
when she created the table?
Not Null, Primary Key

2. Consider the table RESULT given below.

Write command to insert a new row


6, "Mohan", 500, "English", 73, "Second"
Insert into Result values(6, "Mohan", 500, "English", 73, "Second");

3. Consider the Table SHOPPE given below.

To insert a new row in the table Shoppe


'110', 'Pizza' , 'Papa Jones', 120, "Kolkata", 50.0
Insert into Result values('110', 'Pizza' , 'Papa Jones', 120, "Kolkata", 50.0);

4. How is NULL value diferent from 0 ((ero) value?


Null means no value whereas 0 is a value.

5. Consider the following table named "GYM"

Add a new row for a new item in GYM with the details: "G107", "Vibro exerciser” ,21000,
“GTCFitness"
Insert into Result values("G107", "Vibro eierciser” ,21000, “GTCFitness");

6. What is meant by NULL value in MySQL?


Null means no value

7. Rewrite the following SQL statement after correcting error(s). Underline the corrections
made.
INSERT IN STUDENT(RNO,MARKS) VALUE (5,78.5);
INSERT INTO STUDENT(RNO,MARKS) VALUES (5,78.5);

8. Rewrite the following SQL statement after correcting error(s). Underline the corrections
made.
INSERT IN EMP(EMPNO, SALES) VALUE (100, 20078.50);
INSERT INTO EMP(EMPNO, SALES) VALUES(100, 20078.50);

9. Charvi is inserting “Sharma” in the “LastName” column of the “Emp” table but an error is
being displayed. Write the correct SQL statement.
INSERT INTO Emp(‘Sharma’)VALUES(LastName) ;
INSERT INTO Emp(LastName) VALUES(‘Sharma’) ;

10 Anita has created the following table with the name ‘Order’.
.

7
One of the rows inserted is as follows :

(i) What is the data type of columns OrderId and OrderDate in the table Order ?
(ii) Anita is now trying to insert the following row :

Will she be able to successfully insert it ? Give reason.


i)The datatype for orderID feld can be either char or varchar
The datatype for orderDate is date
ii)She will not be able to insert the above record as she is inserting a null value
in the orderdate feld and the orderdate feld have a not null constraint
which cannot accept null values.

11 In today’s digitized world with a need to store data electronically, it is very important to
. store the data in the databases. SQL is used to interact with the Database Management
System.
Classify the following commands according to their type :(DDL/DML)
i. INSERT INTO ii. ALTER TABLE
i. DML ii. DDL

12 Is NULL and 0(zero) same? Jusify your answer.


.
No null is not same as 0. Null means no value. 0 is a value.
Any numerical calculation on null will give null
Any numerical calculation on 0 will do the actual calculation.

13 Write the full forms of the following:


. i. DDL ii. DML
i. Data Defnition Language
ii. Data Manipulation Language

8
Informatics Practices
My SQL Worksheet-5
(DML – UPDATE and DELETE commands)
1. What is the purpose of DROP TABLE command in SOL? How is it diferent from DELETE
command?
Drop table deletes the table along with the structure. Delete deletes the records.

2. In a database there are two tables "Product" as shown below :

Write the command To increase the Price of all the Products by 20.
Update Product set price=price + 20;

3. Write the UPDATE command to change “Sharma” to “Singh” in the “LastName” column in
the Employee table.
Update Employee set Lastname=”Singh” where lastname=”Sharma”;

4. What is the use of UPDATE statement in SQL ? How is it diferent from ALTER statement?
Update command updates the records.
Alter command modifes the structure of the table.

5. Consider the following table named "GYM"

Write command To change the Brandname to "Fit Trend India" of the item, whose ICODE as
"G101 ".
Update Gym set brandname=”Fit Trend India” where Icode=”G101”;

6. Write the UPDATE statement in MySQL to increase commission by 100.00 in the


‘‘Commission’’ column in the ‘Emp’ table.
Update emp set commission=commission + 100.00;

7. Write two examples of DML commands of SQL.


Insert, Update, delete, select

8. In a database there are two tables ‘CD’ and ‘TYPE’ as shown below :

9
Write SQL statement to change the name of Singer ‘‘Sonvi Kumar’’ to ‘‘Sonvi Mehra’’ in all
the places wherever it occurs in CD table.
Update CD set singer=”Sonvi Mehra” where singer=”Sonvi Kumar”;

9. Consider the following table named “GARMENT”.

1) Write command To change the colour of garment with code as 116 to “Orange”.
2) Write command to increase the price of all XL garments by 10%
3) Write command to delete the record with GCode “116”
1) Update Garment set colour=”Orange” where Gcode=116;
2) Update Garment set price=price+price*10/100 where size=”XL”;
3) Delete from garment where gcode=116;
10. In a Database, there are two tables given below :

Write SQL command to change the JOBID to 104 of the Employee with ID as E4 in the table
‘EMPLOYEE’.
Update employee set jobid=104 where employeeID=”E4”;

11. In Marks column of ‘Student’ table, for Rollnumber 2, the Class Teacher entered the marks
as 45. However there was a totaling error and the student has got her marks increased by
5. Which MySQL command should she use to change the marks in ‘Student’ table.
Update student set marks=marks-5 where rollnumber=2;

12. Chhavi has created a table named Orders, she has been asked to increase the value of a
column named salesamount by 20. She has written the following query for the same.
Alter table Orders Add salesamount =salesamount+20;

10
Is it the correct query?Justify.
Update orders set salesamount=salesamount+20’

13. Consider the following table:


Table: PharmaDB

Write commands in SQL to increase the price of “Amlodipine” by 50.


Update PharmaDB set price=price+50 where drugname=”Amlodipine”;

11
Informatics Practices
My SQL Worksheet-6
(DML – SELECT command)
1. Pooja, a students of class XI, created a table "Book". Price is a column of this table. To fnd
the details of books whose prices have not been entered she wrote the following query:
Select * from Book where Price = NULL;
Select * from book where price is null;

2. The LastName column of a table "Directory" is given below:


Based on this information, fnd the output of the following
queries:
a) SELECT lastname FROM Directory WHERE lastname like
"_a%";

b)SELECT lastname FROM Directory WHERE lastname not


like "%a";
A) Lastname
Batra
B) Lastname
Sehgal

3. Consider the table TEACHER given below. Write commands in SQL for (1) to (3) and output
for (4)

i. To display all information about teachers of PGT category.


ii. To list the names of female teachers of Hindi department.
iii. To list names, departments and date of hiring of all the teachers in ascending order of
date of joining
iv. SELECT DISTINCT(category) FROM teacher;
i. Select * from teacher where category=”PGT”;
ii. select name from gym where gender=”F” and department=”Hindi”;
iii. Select name,department,hiredate from teacher order by hiredate;
iv. DISTINCT(Category)
TGT
PRT
PGT

4. The ltem_No and Cost columna of a table "ITEMS" are given below:
Based on this information, fnd the output of the following
queries:
a) SELECT COST +100 FROM ITEMS WHERE ITEM_NO > 103;
Ans. COST+100
6100
NULL

5. Consider the table Projects given below. Write commands in SOL for i) to iii) and output for
iv)

12
i. To display all information about projects of"Medium" ProjSize
ii. To list the ProjSize of projects whose ProjName ends with LITL.
iii. To list ID, Name, Size, and Cost of all the projects in descending order of StartDate.
iv. SELECT DISTINCT ProjSize FROM projects
i. Select * from projects where projsize=”Medium”;
ii. Select projsize from projects where projname like “%LITL”;
iii. Select ID,projName,projSize,cost from projects order by startDate desc;
iv. ProjSize
Medium
Large
Small
6. The Mname Column of a table Members is given below :
Based on the information, fnd the output of the following
queries :
(i) Select Mname from members where mname like "%v" ;
(ii) Select Mname from members where mname like "%e%";

Ans. i) Mname
Hirav
Rajeev
ii) Mname
Sheetal
Rajeev
7. Sarthya, a student of class XI, created a table "RESULT". Grade is one of the column of this
table. To fnd the details of students whose Grades have not been entered, he wrote the
following MySql query, which did not give the desired result.
SELECT * FROM Result WHERE Grade= "Null";
Help Sarthya to run the query by removing the errors from the query and write the correct
Query.
Select * from Result where Grade is null;

8. Consider the table RESULT given below. Write commands in MySql for (i) to (ii)

(i) To list the names of those students, who


have obtained Division as FIRST in the
ascending order of NAME.
(ii) To display a report listing NAME,
SUBJECT and Annual stipend received
assuming that the stipend column has
monthly stipend.
i) Select name from Result where division=”First” order by name;
ii) Select name,subject,stipend*12 from Result;

9. Mr. Janak is using a table with following columns :


Name , Class , Course_Id, Course_name
He needs to display names of students, who have not been assigned any stream or have
been assigned Course_name that ends with "economics". He wrote the following command,
which did not give the desired result.
SELECT Name, Class FROM Students WHERE Course name = NULL OR Course
name="%economics";
Help Mr. J anak to run the query by removing the error and write the correct query.
SELECT Name, Class FROM Students WHERE Course name IS NULL OR Course

13
name LIKE "%economics";

10 Consider the Table SHOPPE given below. Write command in MySql for (i) to (ii)
.
(i) To display names of the items whose name
starts with 'C' in ascending order of Price.
(ii) To display Code, Item name and City of the
products whose quantity is less than 100.
i) Select Item from shoppe where item like “C%” order by price;
ii) Select code,item,city from shoppe where qty<100;

11 What is used in the SELECT clause to return all the columns in the table?
.
* (asterisk) sign

12 In MySQL, Sumit and Fauzia are getting the following outputs of ItemCodes for SELECT
. statements used by them on a table named ITEM.(Both have used the SELECT statements
on the same table ITEM).
Sumit’s Output Fauzia’s Output
101 101
102 102
101 105
105 107
101
107
Which extra keyword has Fauzia used with SELECT statement to get the above output?
Distinct

13 Consider the table ‘PERSONS’ given below. Write commands in SQL for (i) to (iv) and write
. output for (v).

(i) Display the SurNames, FirstNames and


Cities of people residing in Udhamwara
city.
(ii) Display the Person Ids (PID), cities and
Pincodes of persons in descending
order of Pincodes.
(iii) Display the First Names and cities of all
the females getting Basic salaries
above 40000.
(iv) Display First Names and Basic Salaries
of all the persons whose frstnames
starts with “G”.
(v) SELECT Surname FROM Persons Where BasicSalary>=50000;
i) Select surname,frstname,city from persons where city=”Udhamwara”;
ii) Select pid,city,pincode from persons order by pincode desc;
iii) Select frstname,city from persons where gender=”F” and
basicSalary>40000;4
iv) Select frstname,basicSalary from persons where frstname like “G%”;
v) Surname
Sharma
Singh
Alvis
14 Mr. Tondon is using table EMP with the following columns.
. ECODE,DEPT,ENAME,SALARY
He wants to display all information of employees (from EMP table) in ascending order of
ENAME and within it in ascending order of DEPT. He wrote the following command, which
did not show the desired output.
SELECT * FROM EMP ORDER BY NAME DESC,DEPT;

14
Rewrite the above query to get the desired output.
SELECT * FROM EMP ORDER BY ENAME,DEPT;

15 Consider the following table named "GYM" with details about ftness items being sold in the
. store. Write command of SQL for (i) to (ii).

(i) To display the names of all the items whose name


starts with "A".
(ii) To display ICODEs and INAMEs of all items, whose
Brandname is Reliable or Coscore.
i) Select iname from gym where iname like “A%”;
ii) Select ICode,Iname from gym where brandname
in(“Reliable”,”Coscore”);

16 Consider the following table named 'SBOP" with details of account holders. Write
. commands of MySql for (i) to (ii) and output for (iii).

(i) To display Accountno, Name and DateOfopen of


account holders having transactions more than 8.
(ii) To display all information of account holders whose
transaction value is not mentioned.
(iii) SELECT NAME,BALANCE FROM SBOP WHERE NAME
LIKE “%i”;
i) Select AccountNo,Name,Dateofopen from sbop where transaction>8;
ii) Select * from sbop where transaction is null;
iii) Name Balance
Mrs. Sakshi 45000.00

17 When using the LIKE clause, which wildcard symbol represents any sequence of none, one
. or more characters ?
%
18 Consider the table FLIGHT given below. Write commands in SQL for (i) to (iv) and output for
. (v).

(i) Display details of all fights starting from Delhi.


(ii) Display details of fights that have more than 4 number of fights operating.
(iii) Display fight codes, starting place, destination, number of fights in descending order
of number of fights.
(iv) Display destinations along with fight codes of all the destinations starting with ‘A’.
(v) SELECT DISTINCT(NO_STOPS) FROM FLIGHT;
i) Select * from fight where start=”Delhi”;
ii) Select * from fight where no_fights>4;
iii) Select fcode,start,destination,no_fights from fight order by no_fights
desc;
iv) Select destination,fcode from fight where destination like “A%”;
v) NO_STOPS
0
1
2
3

19 What will be the output of the following queries on the basis of Employee table:
.
(i) Select Salary+100 from Employee where EmpId='A002';

15
i) Salary +100
NULL

20 Pranay, who is an Indian, created a table named “Friends” to store his friend’s detail.
. Table “Friends” is shown below.
Write commands in SQL for (i)
to (iii) and output for (iv).

i. To display list of all foreigner


friends.
ii. To list name, city and country in descending order of age.
iii. To list name and city of those friends who don’t have an email id.
iv. Select name,country from friends where age>12 and name like ‘A%’;
i. Selct * from friends where country not in(“India”);
ii. Select name,city,country from friends order by age desc;
iii. Select name,city from friends where email_id is null;
iv. Name Country
Alice USA
Angel USA
Aleiender Australia

21 Consider the following table named “GARMENT”. Write command of SQL for (i)
. to (iv) and output for (v) to (vii).
(i) To display names of those garments that are
available in ‘XL’ size.
(ii) To display codes and names of those
garments that have their names starting with
‘Ladies’.
(iii) To display garment names, codes and
prices of those garments that have
price in the range 1000.00 to 1500.00 (both
1000.00 and 1500.00 included).
(iv) SELECT GNAME FROM GARMENT
WHERE SI(E IN (‘M’, ‘L’) AND PRICE > 1500;
i) Select gname from garment where size=”XL”;
ii) Select gcode,gname from garment where gname like “Ladies%”;
iii) Select gname,gcode,price where price between 1000.00 and 1500.00
iv) Gname
Jeans

22 Consider the table ‘empsalary’.


.
To select tuples with some salary ,Siddharth has written the following
erroneous SQL
statement:
SELECT ID, Salary FROM empsalary WHERE Salary = something;
SELECT ID, Salary FROM empsalary WHERE Salary is not null;
23 Consider the table ‘Employee’.
. Write the SQL command to obtain the following output :

16
Select distinct Location from employee;

24 Table “Emp” is shown below. Write commands in SQL for (i) to (iii) and output for (iv) and
. (v)
and (vi)
i. To display list of all employees below 25
years old.
ii. To list names and respective salaries in
descending order of salary.
iii. To list names and addresses of those
persons who have ‘Delhi’ in their address.
iv. SELECT Name, Salary FROM Emp where
salary between 50000 and 70000;
v. SELECT Name, phone from emp where
phone like ‘99%’;
i. Select * from emp where age<25;
ii. Select name,salary from emp order by salary desc;
iii. Select name,address where address like “%Delhi%”;
iv. Name salary
Siddharth 62000
Karan 65000
v. Name Phone
Chavi 99113423989
Raunaq 99101393576

25 Mrs. Sen entered the following SQL statement to display all Salespersons of the
. cities “Chennai” and ‘Mumbai’ from the table ‘Sales’.
Scode Name City SELECT * FROM Sales WHERE
101 Aakriti Mumbai City=‘Chennai’ AND
City=‘Mumbai’;
102 Aman Chennai
103 Banit Delhi
104 Fauzia Mumbai
Rewrite the correct statement, if wrong or write statement is correct.
SELECT * FROM Sales WHERE City=‘Chennai’ OR City=‘Mumbai’;

26 Write commands in SQL for (i) to (iii) and output for (iv).
. Table : Store
StoreId Name Location City NoOfEmployee DateOpene SalesAmou
S101 Planetfashio KarolBagh Delhi 7 2015-10-16 300000
S102 Trends Nehru Mumbai 11 2015-08-09 400000
Nagar
S103 Vogue Vikas Delhi 10 2015-06-27 200000
Vihar
S104 Superfashio Defence Delhi 8 2015-02-18 450000
n Colony
S105 Rage Bandra Mumbai 5 2015-09-22 600000
(i) To display name, location, city, SalesAmount of stores in descending order of
SalesAmount.
(ii) To display names of stores along with SalesAmount of those stores that have ‘fashion’
anywhere in their store names.
(iii) To display Stores names, Location and Date Opened of stores that were opened before
1st March, 2015.
(iv) SELECT distinct city FROM store;
i) Select name,location,city,salesamount from Store order by salesamount
desc;

17
ii) Select name,salesamount from store where name like “%Fashion%”;
iii) Select name,location,dateOpened from store where dateOpened<”2015-
03-01”;
iv) CITY
Delhi
Mumbai

27 Which clause would you use with Select to achieve the following:
. i.To select the values that match with any value in a list of specifed values.
ii.Used to display unrepeated values of a column from a table.
i. IN
ii. DISTINCT

28 Consider the following table:


. Table: PharmaDB
Write commands in SQL for (i) to (iii) and
output for (iv):
i. To increase the price of “Amlodipine” by
50.
ii. To display all those medicines whose price
is in the range 100 to 150.
iii. To display the Drug ID, DrugName and
Pharmacy Name of all the records in
descending order of their price.
iv. SELECT RxID, DrugName, Price from PharmaDB where PharmacyName IN (“Rx
Parmacy”, “Raj Medicos”);
i. Update PharmaDB set price=price+50 where drugname=”Amlodipine”;
ii. Select * from pharamdb where price between 100 and 150;
iii. Select DrugID,Drugname,pharmacyName from pharmaDB order by price
desc;
iv. RXID DrugName price
R1000 Amlodipine 100.00
R1001 Paracetamol 15.00
R1004 Levocitrezine 110.00

29 Write SQL statement that gives the same output as the following SQL statement but uses
. ‘IN’ keyword.
SELECT NAME FROM STUDENT WHERE STATE = ‘VA’ ;
SELECT NAME FROM STUDENT WHERE STATE IN(‘VA’);

30 Which one of the following SQL queries will display all Employee records containing the
. word “Amit”, regardless of case (whether it was stored as AMIT, Amit, or amit etc.) ?
(i) SELECT * from Employees WHERE EmpName like UPPER ‘%AMIT%’;
(ii) SELECT *from Employees WHERE EmpName like ‘%AMIT%’ or ‘%AMIT%’ OR ‘%amit%’;
(iii) SELECT * from Employees WHERE UPPER (EmpName) like ‘%AMIT%’;
(iii) SELECT * from Employees WHERE UPPER (EmpName) like ‘%AMIT%’;

31 Write Answer to (i). Write SQL queries for (ii) to (vii).


.

18
Note : Columns SID and DOB contain Sales Person Id and Data of Birth respectively.
(i) Write the data types of SID and DOB columns.
(ii) Display names of Salespersons and their Salaries who have salaries in the range
30000.00 to 40000.00
(iii) To list Names, Phone numbers and DOB (Date of Birth) of Salespersons who were born
before 1st November, 1992.
(iv) To display Names and Salaries of Salespersons in descending order of salary.
(v) To display areas in which Salespersons are working. Duplicate Areas should not be
displayed.
(vi) To display SID, Names along with Salaries increased by 500. (Increase of 500 is only to
be displayed and not to be updated in the table)
(vii) To display Names of Salespersons who have the word ‘Kumar’ anywhere in their
names.
i. The data type of SID is either char or varchar
ii. Select name,salary from salesperson where salary between 30000.00 and
40000.00;
iii. Select name,phone,dob from salesperson where dob<”1992-11-01”;
iv. Select name,salary from salesperson order by salary desc;
v. Select distinct area from salesperson;
vi. Select sid,name,salary+500 from salesperson;
vii. Select name from salesperson where name like “%Kumar%”;

32 Write the following statement using ‘OR’ logical operator :


. SELECT frst_name, last_name, subject FROM studentdetails WHERE subject IN (‘Maths’,
‘Science’);
Select frst_name, last_name, subject from studentDetails Where
subject=”Maths” or subject=”Science”;

33 Consider the Table “Gym” shown below. Write commands in SQL for (i) to (vi) :
.

(i) To display Mname, Age, FeeGiven of those members whose fee is above 12,000.
(ii) To display Mcode, Mname, Age of all female members of the Gym with age in
descending order.
(iii) To list names of members and their date of admission of those members who joined
after 31st December, 2015.
iv) To display the Mname, FeeGiven of all those members of the Gym whose age is less
than 40 and are monthly type members of the Gym.
(v) To display names of members who have ‘mit’ anywhere in their names. For example :
Amit, Samit.
(vi) To display types of memberships available. Duplicate values should not be displayed.
i) Select mname, age, feegiven from gym where feegiven>12000;
ii) Select mcode,mname,age from gym where gender=”Female” order by
age desc;
iii) Select mname,dtAdmit from gym where dtAdmit>”2015-12-31”;
iv) Select mname,feegiven from gym where age<40 and type=”Monthly”;
v) Select mname from gym where mname like “%mit%”;
vi) Select distinct type from gym;

19
34 Consider the following table:
. Write commands in SQL for (i) to (iv) and output
for (v):
i. To display the details of all those students
who have IP as their optional subject.
ii. To display name, stream and optional of all
those students whose name starts with ‘A’.
iii. To give an increase of 3 in the average
of all those students of humanities section who
have Maths as their optional subject.
iv. To display a name list of all those
students who have average more than 75.
v. Select name from students where optional IN (‘CS’,’IP’);
i. Select * from student where optional=”IP”;
ii. Select name,stream,optional from student where name like “A%”;
iii. Update student set average=average+3 where stream=”Humanities”;
iv. Select name from student where average>75;
v. Name
Shrishti
Aditya
Ritu Raj
Saumya
Ashutosh
Aman

20
Informatics Practices
My SQL Worksheet-7
(Single Row Functions)
1. Write the output of the following SQL queries:
a) SELECT ROUND(6.5675, 2); 6.57
b) SELECT TRUNCATE(5.3456, 1); 5.3
c) SELECT DAYOFMONTH('2009-08-25'); 25
d) SELECT MID('Class 12', 2,3); las
2. Write the output of the following SQL queries :
(i) SELECT INSTR(‘UNICODE’,’CO’); 4
(ii) SELECT RIGHT(‘Informatics’,3); ics
3. State diference between date functions NOW( ) and SYSDATE( ) of MySql.

Now() Sysdate()

Now displays the date and Sysdate() displays the date and
time at the beginning of the time at the eiact time of the
command. eiecution of the command.

It always displays the same It displays the eiact date and time
date and time in a single sql at which it is eiecuted within the
command. No matter how single command.
many times it is being
eiecuted.

Eiample:

4. Name a function of MySql which is used to remove trailing and leading spaces from a string.

trim

5. Consider the following table named 'SBOP" with details of account holders. Write output

(i) SELECT ROUND(Balance,-3) FROM SBOP WHERE


AccountNo=”SB-5”;

Ans. i)
ROUND(Balance,-3)
63000
6. Write the output of the following SQL queries :
(i) SELECT RIGHT(‘software’, 2); re
(ii) SELECT INSTR(‘twelve’,‘lv’); 4
(iii) SELECT DAYOFMONTH(‘2014-03-01’); 1
(iv) SELECT ROUND(76.987, 2); 76.99
7. Write the output of the following SQL queries:
i. SELECT INSTR(‘INTERNATIONAL’, ‘NA’); 6
ii. SELECT LENGTH(CONCAT(‘NETWORK’,’ING’)); 10
iii.SELECT ROUND(563.345,-2); 600
iv. SELECT DAYOFYEAR(‘2014-01-30’); 30
8. Pranay, who is an Indian, created a table named “Friends” to store his friend’s detail.
Table “Friends” is shown below. Write output for (i) and (ii).

21
i. Select ucase(concat(name,”*”,city)) from friends where country like ‘Denmark’;
ii. Select mid(name,1,4) as “UID” from friends where country like ‘USA’;
i. ucase(concat(name,”*”,city))
CHARLES*COPENHAGEN
JETTE*NYKOBING
ii. UID
Alic
Ange

9. Write the output of the following SQL queries:


i) SELECT TRUNCATE(8.975,2); 8.97
ii) SELECT MID(‘HONESTY WINS’,3,4); NEST
iii) SELECT RIGHT(CONCAT(‘PRACTICES’,’INFORMATICS’),5); ATICS
iv) SELECT DAYOFMONTH(‘2015-01-16’); 16
10. Write the output of the following SQL queries :
(i) SELECT MID(‘BoardExamination’,2,4); oard
(ii) SELECT ROUND(67.246,2); 67.25
(iii) SELECT INSTR(‘INFORMATION FORM’,‘FOR’); 3
(iv) SELECT DAYOFYEAR(‘2015-01-10’); 10
11. Write output.
Table : Store
StoreI Name Location City NoOfEmploye DateOpen SalesAmou
S101 Planetfashi KarolBag Delhi 7 2015-10- 300000
S102 Trends Nehru Mumb 1 2015-08- 400000
Nagar ai 1 09
S103 Vogue Vikas Delhi 1 2015-06- 200000
Vihar 0 27
S104 Superfashio Defence Delhi 8 2015-02- 450000
n Colony 18
S105 Rage Bandra Mumb 5 2015-09- 600000
(i) SELECT Name, length (name), left (name, 3) FROM Store where NoOfEmployees<3;
i) Empty Set

12. Write the output of the following SQL queries:


SELECT POW(INSTR(‘My_Database’,’_’),2); 9
13. Consider the table given below :
Write output.

(i) SELECT Name, LENGTH(Name) FROM


Salesperson;

Ans.
Name Length()
Amit Kumar 10
Deepika Sharma 14
Vinay Srivastav 15
Kumar Mehta 11
Rashmi Kumar 12
14. Identify Single Row functions of MySQL amongst the following :
TRIM(), MAX(), COUNT(*), ROUND()
Trim() and Round() are single row functions

15. Consider the Table “Gym” and write output

(i) SELECT MID(Mname,1,2)from Gym;

Ans.

22
MID(Mname,1,2)
Am
Ra
Ge
Fa
Sa
La
Su
Mi
Da
Aj
16. Observe the given table named “Loan” carefully
and predict the output of the
following queries:
i. SELECT concat(left(fle_no,2), right(cust_name,2)) AS “ID” from loan where Bank='ICUCI
Ltd.';
ii. select round(loan_amt-loan_amt*10/100) As "Discounted Payment" from loan where
loan_amt>700000;
i) ID
23mi
43et
ii) Discounted Payment
728888
671164

Informatics Practices
My SQL Worksheet-8
(Aggregate Functions)
1. Consider the table TEACHER given below. Write commands in SQL for (1) and output for (2) to (5)

i. To count the number of teachers in English department.


ii. SELECT MAX(Hiredate) FROM Teacher;
iii. SELECT DISTINCT(category) FROM teacher;
iv. SELECT COUNT(*) FROM TEACHER WHERE Category = "PGT"
v. SELECT Gender,AVG(Salary) FROM TEACHER group by Gender;
i. Select count(*) from teacher where department=”English”;
ii. Mai(Hiredate)
1994-09-02
iii. Distinct(Category)
TGT
PRT
PGT
iv Count(*)
1
v. Gender avg(salary)
M 24000
F 24500

2. The ltem_No and Cost column of a table "ITEMS" are given below:

23
Based on this information, fnd the output of the following
queries:
a) SELECT AVG(COST) FROM ITEMS;
b) SELECT COST +100 FROM ITEMS WHERE ITEM_NO > 103;

A) AVG(Cost)
5000
B) Cost+100
6100
Null

3. "PrincipaiName" is a column in a table "Schools". The SOL queries


SELECT count(*) FROM Schools;
and
SELECT count( Principal) FROM schools;
Give the result 28 and 27 respectively. What may be the possible reason for this? How many records
are present in the table-27 or 28?
The possible reason could be that one of the value in Principal feld will be NULL
There are 28 records

4. Consider the table Projects given below. Write commands in SOL fori) and output for i) to iii)

i. To count the number of projects of cost less than 100000.


ii. SELECT SUM(Cost) FROM projects;
iii. SELECT ProjSize, COUNT(*) FROM Projects GROUP BY ProjSize;
i. Select count(*) from projects where cost<100000;
ii. Sum(cost)
980000
iii. Projesize count(*)
Medium 3
Large 2
Small 1

5. Consider the table RESULT given below. Write output

(i) SELECT AVG(Stipend) FROM EXAM WHERE


DIVISION= "THIRD”;
(ii) SELECT COUNT(DISTINCT Subject) FROM EXAM;
(iii) SELECT MIN(Average) FROM EXAM WHERE
Subject= "English";
i) AVG(Stipend)
475
ii) Count(distinct subject)
6
iii) Min(Average)
38

6. What is the purpose of ORDER BY clause in MySql ? How is it diferent from GROUP BY clause?

Order by displays the records in ascending/descending order of feld.


Group By, groups the records according to a feld and then fnds the maiimum or
minimum or counts or fnds the sum or average.
7. Consider the Table SHOPPE given below. Write command in MySql for (i) and output for (ii) to (iii).

(i) To count distinct Company from the table.

24
(ii) Select Count(distinct (City)) from Shoppe;
(iii) Select MIN (Qty) from Shoppe where City="Mumbai";
i) Select count(distinct company) from shoppe;
ii) Count(distinct (city))
3
iii) Min(Qty)
56

8. Consider the table ‘PERSONS’ given below. Write commands in SQL for (i) to (iv) and write output for
(i) to (iii).

(i) SELECT SUM(BasicSalary) FROM Persons Where


Gender=’F’;
(ii) SELECT Gender,MIN(BasicSalary) FROM Persons
GROUP BY gender;
(iii) SELECT Gender,Count(*) FROM Persons GROUP
BY Gender;

i) SUM(BasicSalary)
132000
ii) Gender MIN(BasicSalary)
F 40000
M 33000
iii) Gender Count(*)
F 3
M 4

9. There is a column HOBBY in a Table CONTACTS. The following two statements are giving diferent
outputs. What may be the possible reason ?
SELECT COUNT(*) FROM CONTACTS;
SELECT COUNT(HOBBY)FROM CONTACTS;
The possible reason could be that some of the values in the hobby feld would be NULL.

10. Consider the following table named "GYM" with details about ftness items being sold in the store.
Write output

(i) SELECT COUNT (DISTINCT (BRANDNAME)) FROM GYM;


(ii) SELECT MAX (PRICE ) FROM GYM;

Ans. i) COUNT (DISTINCT (BRANDNAME))


6
ii) Mai(Price)
30000
11. Consider the following table named 'SBOP" with details of
account holders. Write output.

(i) SELECT COUNT(*) FROM SBOP;

Ans. COUNT(*)
5
12. Given ‘Employee’ table as follows :

What values will the following statements return ?


SELECT COUNT(*) FROM Employee;
SELECT COUNT(Commission) FROM Employee;

Ans. Count(*)
3
Count(Commission)
1
13. Consider the table FLIGHT given below. Write output.

(i) SELECT MAX(NO_FLIGHTS) FROM FLIGHT;


(ii) SELECT START, COUNT(*) FROM FLIGHT GROUP
BY Start;

25
i) MAX(NO_FLIGHTS)
7
ii) START COUNT(*)
Delhi 3
Mumbai 2
Kanpur 1
Indore 1

14. What will be the output of the following queries on the basis of
Employee table:

(i)Select avg(Salary) from Employee;


(ii) Select Salary+100 from Employee where EmpId='A002';
i) Avg(Salary)
5300
ii) Salary+100
NULL

15. Consider the following table named “GARMENT”. Write output

(i) SELECT COUNT(DISTINCT (SI(E)) FROM GARMENT;

(ii) SELECT AVG(PRICE) FROM GARMENT;

Ans. i) COUNT(DISTINCT (SIZE))


3
ii) AVG(PRICE)
1800
16. Consider the table ‘Teacher’ given below.
What will be the output of the following queries on the basis of the above table:

(i)Select count(Department) from Teacher;


(ii)Select count(*) from Teacher;

Ans. count(Department)
2
count(*)
3
17. (i) Name two Aggregate (Group) functions of SQL.
(ii) Consider the table :
Table : Company What output will be displayed by the
SID SALES following SQL statement ?
SELECT AVG(SALES) FROM Company;
S101 20000
S103 NULL AVG(SALES)
15000
S104 10000
S105 15000
18. Consider the table ‘Hotel’ given below :
Table : Hotel Mr. Vinay wanted to display average
EMPID Category Salary salary of each Category. He entered the
following SQL statement. Identify error(s)
E101 MANAGER 60000
and Rewrite the correct SQL statement.
E102 EXECUTIVE 65000 SELECT Category, Salary FROM Hotel
E103 CLERK 40000 GROUP BY Category;
E104 MANAGER 62000
Select category,avg(salary) from hotel
E105 EXECUTIVE 50000 group by category;
E106 CLERK 35000
19. Explain why the following queries give diferent outputs on execution:
i. SELECT COUNT(ENAME) FROM EMP;
Output: 5
ii. SELECT Count(*) FROM EMP;
Output: 8

26
The ename feld in emp table will be having 3 NULL values

20. Kunal has entered the following SQL command on Table ‘STUDENT’ that has TotalMarks as one of the
columns.
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 as 5. Do you agree with Kunal ? Give reason for your
answer.
Yes, the output for select count(*) from student where totalMarks>=100 will be 5 as there
are 20 students out of which 15 have totalMarks less than 100 so 5 students will have a
totalMarks greater than or equal to 100
21. Consider the table given below :
Write command for (i) and output for (ii)
(i) To display Area along with number of Salespersons
working in that area.
(ii) SELECT Area, COUNT (*) FROM Salesperson GROUP BY
Area HAVING COUNT (*) > 1;

i) Select area,count(*) from salesperson group by


area;
ii) Area Count(*)
North 2
South 2

22. Observe the given table named “Loan” carefully and


predict the output of the
following queries:
select count(fle_no)-count(loan_amt) from loan;

count(fle_no)-count(loan_amt)
1

27
Informatics Practices
My SQL Worksheet-9
(Joins)
1. In a database there are two tables 'Customer' and 'Bill' as shown below:

(i) How many rows and how many columns will be there in the Cartesian product of these two
tables?
(ii) Which column in the 'Bill' table is the foreign key?
i) There will be 5 columns and 15 rows in the Cartesian product of these two tables.
ii) CustID in the bill table is a foreign key

2. Consider the tables HANDSETS and CUSTOMER given below:

With reference to these tables, Write commands in SQL for (i) and (ii) and output for (iii) below:
(i) Display the CustNo, CustAddress and corresponding SetName for each customer.
(ii) Display the Customer Details for each customer who uses a Nokia handset.
(iii) select SetNo, SetName from Handsets, customer where SetNo = SetCode and CustAddress =
'Delhi';
i) Select custno, custaddress, setname
from handsets, customer
where setcode=setno;
ii) Select customer.*
from handsets, customer
where setcode=setno and setname like “Nokia%”;
iii) SetNo SetName
N2 Nokia 3G
B1 BlackBerry

3. In a database there are two tables "Company" and "Model" as shown below:

(i) Identify the foreign key column in the table Model.


(ii) Check every value in CompiD column of both the tables. Do you fnd any discrepancy?
i) ComID is the foreign key in model table
ii) The discrepancy is a value 4 in the compID feld of Model table.

4. Consider the tables DOCTORS and PATIENTS given below:

28
W1th reference to these tables, wnte commands m SQL for (1) and (II) and output for (iii) below:
(i) Display the PatNo, PatName and corresponding DocName for each patient
(ii) Display the list of all patients whose OPD_Days are MWF.
(iii) select OPD_Days, Count(*) from Doctors, Patients where Patients.Department =
Doctors.Department Group by OPD_Days;
i) Select PatNo, patName, DocName
From Doctors, Patients
Where Doctors.DocID=Patients.DocID;
ii) Select Patients.*
From Doctors, Patients
Where Doctors.docID=Patients.DocID amd OPD_Days=”MWF”;
iii) OPD_Days Count(*)
TTS 2
MWF 3

5. In a database there are two tables "Product" and "Client" as shown below :

Write the commands in SQL queries for the following :


(i) To display the details of Product whose Price is in the range of 40 and 120 (Both values included)
(ii) To display the ClientName, City from table Client and ProductName and Price from table
Product, with their corresponding matching P ID.
(iii) To increase the Price of all the Products by 20.
i) Select *
From Product
where price between 40 and 120;
ii) Select clientName,city,productName,price
From Product,Client
Where Product.P_ID=Client.P_ID;
iii) Update Product
Set price=price+20;

6. In a. Database School there are two tables Member and Division as show below.

(i) Identify the foreign key in the table Member.


(ii) What output, you will get, when an equi-join query is executed to get the NAME from Member
Table and corresponding DivName from Division table ?
i) DivNo is a foreign key in member table
ii) Name Divname
Shankhya Media
Sunish Dance

7. In a Database there are two tables :

29
Table ITEM:

Write MySql queries for the following :


(i) To display ICode, IName and corresponding Brand of those Items, whose Price is between 20000
and 45000 (both values inclusive).
(ii) To display ICode, Price and BName, of the item which has IName as "Television".
(iii) To increase the price of all the Items by 15%.
i) Select ICode,IName,Brand
From Item,Brand
Where Item.Icode=Brand.ICode and price between 20000 and 45000;
ii) Select ICode,Price,Brand
From Item,Brand
Where IName IN(“Television”);
iii) Update Item
Set Price=Price + Price *15/100;

8. In a Database there are two tables :


Table MAGA(INE:

(i) Which column can be set as the PRIMARY KEY in the MAGA(INE table?
(ii) Which column in the ‘MAGA(INE’ table is the foreign key?
(iii) How many rows and columns will be there in the Cartesian product of the above 2 tables.
(iv) Write command in SQL to display the mag_code, Mag_Title and corresponding types for all the
Magazines.
(v) Write the output :
(vi) Select Mag_Code, Mag_Title, Number_of_Pages, Type From MAGA(INE,MAGTYPE Where
Magazine.Mag_Category=Magtype.Mag_Category and Type=’Spiritual’;
i) Mag_Code can be set as primary key in magazine table
ii) Mag_category is the foreign key in magazine table
iii) In the Cartesian product of these two tables there will be 6 columns and 16
rows.
iv) Select Mag_Code, Mag_Title, Type
From Magazine, magType
Where magazine.mag_category=magType.category;
v) Mag_Code Mag_Title Number_of_Pages Type
1 Good Deeds 60 Spiritual

9. In a Database Kamataka_Sangam there are two tables with the instances given below :

Write SQL queries for the following :


(i) To count how many addresses are not having NULL values in the address column of students

30
table.
(ii) To display Name, Class from STUDENT table and the corresponding Grade from SPORTS table.
(iii) To display Name of the student and their corresponding Coachnames from STUDENTS and
SPORTS tables.
i) Select count(*)
from students
where address is not null;
ii) Select Name,Class,Grade
From students, sports
Where students.admno=sports.admno;
iii) Select Name,Coachname
From students, sports
Where students.admno=sports.admno;

10. In a Database Multiplexes, there are two tables with the following data. Write MySQL queries for (i)
to (iii), which are based on TicketDetails and AgentDetails :

(i) To display Tcode, Name and Aname of all the records where the number of tickets sold is more
than 5.
(ii) To display total number of tickets booked by agent “Mr. Ayush”
(iii) To display Acode, Aname and corresponding Tcode where Aname ends with “k”.
(iv) With reference to “TicketDetails” table, which column is the primary key ? Which column is the
foreign key? Give reason(s)
i) Select TCode, Name, AName
From TicketDetails, AgentDetails
Where A_Code=Acode and tickets>5;
ii) Select sum(Tickets)
From TicketDetails, AgentDetails
Where A_Code=Acode and aName=”Mr. Ayush”;
iii) Select Acode, AName, Tcode
From TicketDetails, AgentDetails
Where A_Code=Acode and Aname like “k%”;
iv) In TicketDetails TCode is Primary Key and A_code is foreign key as two tickets
cannot have same no. whereas the Agent code i.e. A_Code is referencing its
values from the Acode feld in AgentDetails table.
11. In a database there are two tables ‘CD’ and ‘TYPE’ as shown below :

(i) Name the Primary key in ‘‘CD’’ table.


(ii) Name the foreign key in ‘‘CD’’ table.
(iii) Write the Cardinality and Degree of ‘‘TYPE’’ table.
(iv) Check every value in CATEGORY column of both the tables. Do you fnd any discrepancy ? State
the discrepancy.
i) Code
ii) Category
iii) Cardinality = 4 and Degree = 2 of the Type table
iv) Yes, the discrepancy is a value 77 in category feld in CD table.

31
13. Consider the tables ‘Flights’ & ‘Fares’ given below:
Flights
FNO SOURCE DEST NO_OF_FL NO_OF_STO
P
IC301 MUMBAI BANGALORE 3 2
IC799 BANGALORE KOLKATA 8 3
MC101 DELHI VARANASI 6 0
IC302 MUMBAI KOCHI 1 4
AM812 LUCKNOW DELHI 4 0
MU499 DELHI CHENNAI 3 3
Fares
FNO AIRLINES FARE TAX
IC301 Indian Airlines 9425 5
IC799 Spice Jet 8846 10
MC101 Deccan Airlines 4210 7
IC302 Jet Airways 13894 5
AM812 Indian Airlines 4500 6
MU499 Sahara 12000 4
With reference to these tables, write commands in SQL for (i) and (ii) and output for (iii)
below:
i. To display fight number, source, airlines of those fights where fare is less than Rs.
10000.
ii. To count total no of Indian Airlines fights starting from various cities.
iii. SELECT FLIGHTS.FNO, NO_OF_FL, AIRLINES FROM FLIGHTS,FARES WHERE FLIGHTS.FNO =
FARES.FNO AND SOURCE=’DELHI’;
i) Select Flights.FNO, Source,airlines
From Flights, Fares
Where Flights.FNO=Fares.FNO and fare<10000;
ii) Select Sum(No_of_Fl)
From Flights, Fares
Where Flights.FNO=Fares.FNO and airlines=”Indian Airlines”;
iii) FLIGHTS.FNO NO_OF_FL AIRLINES
MC101 6 Deccan Airlines
MU499 3 Sahara

14. A table STUDENT has 5 rows and 3 columns. Table ACTIVITY has 4 rows and 2 columns.
What will be the cardinality and degree of the Cartesian product of them ?
The degree will be 5
The cardinality will be 20

15. Consider the following table named “GARMENT”.

What is the degree and cardinality of ‘Garment’ table ?

Degree=5
Cardinality=6
16. In a Database, there are two tables given below :

Write SQL Queries for the following :


(i) To display employee ids, names of employees, job ids with corresponding job titles.
(ii) To display names of employees, sales and corresponding job titles who have achieved sales
more than 1300000.
(iii) To display names and corresponding job titles of those employee who have ‘SINGH’ (anywhere)
in their names.

32
(iv) Identify foreign key in the table EMPLOYEE.
i) Select EmployeeID, Name, JobID, JobTitle
From Employee, Job
Where Employee.jobid=job.jobid;
ii) Select Name, Sales, Jobtitle
From Employee, Job
Where Employee.jobid=job.jobid and sales>1300000;
iii) Select Name, Jobtitle
From Employee, Job
Where Employee.jobid=job.jobid and name like “%Singh%”;
iv) JobID

17. Consider the tables given below.


Salesperson Orders

i. The SalespersonId column in the "Salesperson" table is the Primary Key.The


SalespersonId column in the "Orders" table is a Foreign KEY.
ii. Can the ‘SalespersonId’ be set as the primary key in table ‘Orders’. Give reason.
Ii. No salespersonID cannot be set as the primary key in orders table as two
salesperson can give multiple orders, so the ordered will be primary key and
salespersonID will be the foreign key which will refer its values from the
salespersonid feld of salesperson table.
18. With reference to the above given tables, Write commands in SQL for (i) and
(ii) and output for (iii) below:
i. To display SalespersonID, names, orderids and order amount of all salespersons.
ii. To display names ,salespersons ids and order ids of those sales persons whose names
start with ‘A’ and sales amount is between 15000 and 20000.
iii. SELECT Salesperson.SalespersonId, name, age, amount FROM Salesperson, orders
WHERE Salesperson.salespersonId= Orders.salespersonId AND AGE BETWEEN 30 AND
45;
i. Select Salesperson.salespersonID, Name, OrderID
From Salespersons, orders
Where Salesperson.salespersonID=Orders.SalespersonID;
ii. Select Salesperson.salespersonID, Name, OrderID
From Salespersons, orders
Where Salesperson.salespersonID=Orders.SalespersonID
and name like “A%” and amount between 15000 and 20000;
iii. Salesperson.SalespersonId name age amount
2 Sunil 34 54000
5 Chris 34 24000

19. Consider the tables given below :


Table : Faculty
TeacherId Name Address State PhoneNumber
T101 Savita Sharma A-151, Adarsh Delhi 991019564
Nagar
T102 Deepak Ghai K-5/52, Vikas Mumbai 893466448
Vihar
T103 MahaLakshmi D-6 Delhi 981166568
T104 Simi Arora Mumbai 658777564
Table : Course
CourseId Subject TeacherId Fee
C101 Introductory Mathematics T101 4500
C103 Physics T101 5000

33
C104 Introductory Computer Science T102 4000
C105 Advance Computer Science T104 6500
(i) Which column is used to relate the two tables ?
(ii) Is it possible to have a primary key and a foreign key both in one table ? Justify your answer
with the help of table given above.
i) TeacherID
ii) Yes, it is possible to have both Primary and foreign key in one table. For Example in the
above course table CourseID is a primary key and teacherid is the foreign key.
20. With reference to the above given tables, write commands in SQL for (i) and (ii)
and output for (iii) :
(i) To display CourseId, TeacherId, Name of Teacher, Phone Number of Teachers living in Delhi.
(ii) To display TeacherID, Names of Teachers, Subjects of all teachers with names of Teachers
starting with ‘S’.
(iii) SELECT CourseId, Subject,Course.TeacherId,Name,PhoneNumber FROM
Faculty,Course WHERE Faculty.TeacherId = Course.TeacherId AND Fee>=5000;
i) Select coursed, Course.TeacherID, Name, PhoneNumber
From Faculty, Course
Where Faculty.TeacherID=Course.TeacherID and state=”Delhi”;
ii) Select Faculty.TeacherID, Name, Subject
From Faculty, Course
Where Faculty.TeacherID=Course.TeacherID and name like “S%”;
iii) CourseId Subject Course.TeacherId Name
PhoneNumber
C105 Advance Computer Science T104 Simi Arora
658777564
21. Consider the tables given below which are linked with each other and maintains referential
integrity:
Table: SAP

Table : Store

With reference to the above given tables, write commands in SQL for (i) and (ii) and output for (iii)
below:
i. To display the ItemCode,ItemName and ReceivedDate of all the items .
ii. To display SAPID,ItemName,ItemStorageLocation of all the items whose Received date is
after 2nd May 2016.
iii. SELECT SAPID,ItemName,STOREID FROM SAP,Store WHERE
SAP.ItemCode=Store.ItemCode AND StoreLocation = “Hauz Khas”
iv. What will be the degree and cardinality of the cartesian product formed while combining
both the above given tables ‘SAP’ and ‘Store’ ?
v. Sangeeta is not able to add a new record in the table ‘Store’ through the following query:
Insert into store values (1206,1006,’Karol Bagh’, ‘2016/07/25’);
Identify the error if there is any
i. Select SAP.ItemCode, ItemName, ReceivedDate
From SAP, Store
Where SAP.ItemCode=Store.ItemCode;
ii. Select SapID, ItemName, storeLocation
From SAP, Store
Where SAP.ItemCode=Store.ItemCode and ReceivedDate>”2016-05-02”;
iii. SAPID ItemName STOREID
S1001 Receiver 1201
S1004 Inverter 1204
iv. The degree will be 8
The cardinality will be 25

34
v. She will not be able to insert the record as 1006 ItemCode is not there in the
itemCode feld in SAP table and since ItemCode in store table is a foreign key
so it will refer its value from the itemcode feld of SAP table.

35
Informatics Practices
My SQL Worksheet-10
(Transaction)
1. Which command is used in MySql to make the changes in database permanent?

Commit

2. Give one diference between ROLLBACK and COMMIT commands used in MySql.

Rollback reverses all the changes being done using insert, update or delete after
starting the transaction.
Commit saves all the changes being done by Inssert, Update or delete after starting the
transaction.
3. A table named ‘GAMES’ has the following contents:

Write the output that will be displayed by statements (i) and (ii).
SELECT * FROM GAMES;
SET AUTOCOMMIT = 0;
INSERT INTO GAMES VALUES(105,'CHESS’,2,9000);
ROLLBACK;
SAVEPOINT S1;
SELECT * FROM GAMES; ------------ (i)
INSERT INTO GAMES VALUES(108,'LAWN TENNIS’,4,25000);
SAVEPOINT S2;
INSERT INTO GAMES VALUES(109,'CRICKET’,11,20000);
ROLLBACK TO S2;
SELECT * FROM ITEM; ------------ (ii)
i)
GCod GameNam Number_of_Play PrizeMon
e e ers ey
101 Carom 2 5000
Board
102 Badminton 2 12000
103 Table 4 8000
Tennis
ii)
GCod GameNam Number_of_Play PrizeMon
e e ers ey
101 Carom 2 5000
Board
102 Badminton 2 12000
103 Table 4 8000
Tennis
108 Lawn 4 25000
Tennis
4. Consider the Stu table

The following SQL queries are executed on the above table

INSERT INTO Stu VALUES(5,'Gagan'); COMMIT;


UPDATE Stu SET name='Abhi' WHERE Rollno = 4

SAVEPOINT A;
INSERT INTO Stu VALUES(6,'Chris'); SAVEPOINT B;
INSERT INTO Stu VALUES(7,'Babita'); SAVEPOINT C;

ROLLBACK TO B;
What will be the output of the following SQL query now:

36
SELECT * FROM Stu;

RollN Name
o
1 Ashi
2 Bimmi
4 Abhi
6 Chris

5. Given below is the ‘Stu’ table :


RNO NAME
1 Amit
2 Bhishm
The following statements are entered :
SET AUTOCOMMIT = 0;
INSERT INTO Stu VALUES(5, ‘Rahul’); COMMIT;
UPDATE Stu set name=‘Rahuliya’ where Rno= 5; SAVEPOINT A;
INSERT INTO Stu VALUES(6, ‘Cristina’); SAVEPOINT B;
INSERT INTO Stu VALUES(7, ‘Fauzia’); SAVEPOINT C;
ROLLBACK TO B;
Now what will be the output of the following statement ?
SELECT * FROM Stu;
RNo Name
1 Amit
2 Bhishm
5 Rahuliya
6 Cristina
6. Geetanjali had created a table “Customer” in the database “Test”. Immediately after the successful
creation of the database, she wrote the Rollback command to undo the creation of the table. Did
she execute rollback successfully? Explain.
No, She did not eiecute the command successfully as rollback command only reverses
the changes done using INSERT, UPDATE or DELETE.

7. Given below is the ‘Department’ table :


SET AUTOCOMMIT = 0;
UPDATE Department SET DEPNAME = ‘OFFICE’ WHERE DEPNAME
=
‘ADMIN’;
INSERT INTO Department VALUES (104, ‘HRD’);
UPDATE Department SET DEPNAME = ‘FRONT OFFICE’ WHERE
DEPNAME = ‘RECEPTION’;
COMMIT;
DELETE FROM Department WHERE DEPNAME = ‘FRONT OFFICE’;
ROLLBACK;
SELECT * FROM Department;
What will be the output of the above given SELECT statement ?
DepCod DepName
e
101 OFFICE
102 FRONT
OFFICE
103 PERSONNEL
104 HRD

37
38

You might also like