Question Bank-Mysql (Expected Board Questions)
Question Bank-Mysql (Expected Board Questions)
2. Write MySql command will be used to open an already existing database "LIBRARY".
Use Library;
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)
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:
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 :
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:
.
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 :
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);
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);
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
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");
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 :
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
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.
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.
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”;
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”;
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’
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;
3. Consider the table TEACHER given below. Write commands in SQL for (1) to (3) and output
for (4)
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)
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).
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).
16 Consider the following table named 'SBOP" with details of account holders. Write
. commands of MySql for (i) to (ii) and output for (iii).
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).
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).
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
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
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%’;
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%”;
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
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
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
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)
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
4. Consider the table Projects given below. Write commands in SOL fori) and output for i) to iii)
6. What is the purpose of ORDER BY clause in MySql ? How is it diferent from GROUP BY clause?
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) 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
Ans. COUNT(*)
5
12. Given ‘Employee’ table as follows :
Ans. Count(*)
3
Count(Commission)
1
13. Consider the table FLIGHT given below. Write output.
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:
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;
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
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:
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 :
6. In a. Database School there are two tables Member and Division as show below.
29
Table ITEM:
(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 :
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 :
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
Degree=5
Cardinality=6
16. In a Database, there are two tables given below :
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
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
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
37
38