SQL Revision Notes Question Bank
SQL Revision Notes Question Bank
ARUMUGANERI
STANDARD XII
SQL - REVISION NOTES
What is a Database?
Database is a systematic collection of organized data or information typically stored on a
electronic media in a computer system. With database data can be easily accessed, managed,
updated, controlled and organized.
Many website on the world wide web widely use database system to store and manage
data (commonly referred as backend).
Advantages of Database
Minimize Data Redundancy: In traditional File processing system same piece of data
may be held in multiple places resulting in Data redundancy (duplicates). Database
system minimizes redundancy by data normalization.
Increased Data consistency: When multiple copies of same data do not match with one
another is called as data inconsistency.
Data Security: Database allows only the authorized user to access data in the database.
Data Sharing: Database allow its users to share data among themselves.
Data Integrity: Data in the database accurate and consistent.
Data Model:
A data model is the way data is organized in a database. There are different types data
models controls the representation of data in a database, these are:
Relational Data model
Network Data Model
Hierarchical Data Model
Object Oriented Data Model
The Relational data Model is far being used by most of the popular Database
Management Systems. In his course we limit our discussion on Relational data model.
Relational Database:
A relational database is collection of multiple data sets organised as tables. A relational
database facilitates users to organize data in a well defined relationship between database
tables/relations. It uses Structured Query Language(SQL) to communicate with the database
and efficiently maintain data in the database.
Relation & Associated Terminologies
SQL is a standard language for storing, retrieving and manipulating data on a relational
database. All the relational database like MySql, Oracle, MS Access, SQL server uses Structured
query language(SQL) for accessing and manipulating data.
SQL provides wide range of effective command to perform all sort of required
operations on data such as create tables, insert record, view recodes, update, alter, delete,
drop, etc.
What is DDL and DML?
All the SQL commands are categorized into five categories: DDL,DML,DCL,DQL,TCL. In
this course we are going to cover only DDL and DML commands in detail.
Data Manipulation Language(DML): The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation Language
and this includes most of the SQL statements.
Example: Insert, Delete, Update.
Constraints In SQL
constraints are used to specify rules for the data in a table. Commonly used constraints
are:
Not Null- Ensures that a column cannot have a NULL value
Unique- Ensures that all values in a column are different
Primary Key- A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
Foreign Key- Prevents actions that would destroy links between tables
Check – Ensures that the values in a column satisfies a specific condition
Default- Sets a default value for a column if no value is specified
MySql Commands
CREATE Database: Used to create a new database.
Syntax: CREATE DATABASE <database name>
e.g. CREATE Database MySchool;
Show Tables: After a database has been selected this command can be Used to list all the
tables in the database.
e.g. SHOW TABLES;
CREATE Table:
Syntax: CREATE TABLE <table name>( column1 datatype, column2 datatype,
…….. columnN datatype,
PRIMARY KEY( one or more columns ) );
E.g. CREATE TABLE cs_students
(sid int(3),
sname varchar(30),
sclass int(2),
smark int(3),
skill varchar(30),
primary key(sid));
ALTER Tables:
ALTER TABLE is a DDL command that can change the structure of the table.
Using ALTER TABLE command we can add, delete or modify the attributes/constraints of a
table.
Syntax: ALTER TABLE <table name> ADD column <Column Name Data type>;
DROP Tables: DROP TABLE is a DDL command used to delete a table from the database.
Syntax: DROP TABLE <table name>;
E.g. DROP Table Employee;
INSERT INTO:
INSERT is a DML command used to insert a new record/row in an existing table.
Syntax: INSERT INTO <Table Name> values (val1,val2,val3..);
SELECT Command:
Used to retrieve and display data from the tables.
WHERE Clause:
The WHERE Clause can be used with SELECT command to select the data from
the table based on some condition.
By default ORDER BY sort the data in ascending order, for descending order we need to
use ”DESC”.
Handling NULL Values: To handle NULL entries in a field we can use “IS” and “IS NOT”, as
NULL value is a Value which is Unknown so we can use =, <> operators to select NULL values.
Lets Consider the Employee table above, to select all the employees whose salary is specified as
NULL in the salary field we must use IS NULL operator.
LIKE OPERATOR
LIKE is used for string matching in MySql, it can be used for comparison of character
strings using pattern. LIKE uses the following two wildcard characters to create string patterns.
Percent(%): used to match a substring of any length.
Underscore( _ ): Used to match any single character.
The LIKE keyword selects the rows having column values that matches with the wildcard
pattern.
Update Command
UPDATE is a DML command used to change values in the rows of a existing table. It
specifies the rows to be changed using WHERE clause and the new values to be updated using
SET keyword.
Syntax: UPDATE <Table Name> SET column=<new value> WHERE <condition>
E.g. To change the salary to 70000 of the employee having Eid 204.
UPDATE employee SET salary=70000 WHERE Eid=204.
To change the Department of an employee
UPDATE employee SET Dept=“Marketing” where Ename=“Kunal”;
Delete Command :
Delete is a DML command used to delete rows of an existing table. It specifies the rows
to be deleted using WHERE clause.
Syntax: DELETE FROM <Table Name> WHERE <condition;
To delete the record/row of the employee having Eid 204.
DELETE FROM employee WHERE Eid=204;
E
SELECT sum(salary) FROM employee;
Result: 80000
SELECT avg(salary) FROM employee;
Result: 26666.6666
SELECT max(salary) FROM employee;
Result: 32000
SELECT min(salary) FROM employee;
Result: 23000
SELECT count(salary) FROM employee;
Result: 3
SELECT count(*) FROM employee;
Result: 5
GROUP BY:
GROUP BY clause combines all those records that have identical values in a particular
field or a group of fields.
It is used in SELECT statement to divide the table into groups. Grouping can be done by a
column name or with aggregate functions.
For Example let up consider the cs_students table,
To find the number of students in each skill, we can use the command.
SELECT skill, count(*) from cs_students GROUP BY skill;
Let us now consider the Employee Table
To find the average salary of employees of each department, we can use the command.
SELECT dept, avg(salary) from employee GROUP BY dept;
HAVING Clause:
HAVING clause is used to apply conditions on groups in contrast to WHERE clause which
is used to apply conditions on individual rows.
To find the average marks of the group of students having a particular skill , where the skill
group must have at least 5 students.
SELECT skill, avg(smark) FROM cs_students GROUP BY skill HAVING count(*)>=5;
Let us consider the employee table,
To find the average salary of employees of each department, where the average age of all the
employees working in the department is less then 32.
SELECT dept,avg(salary) FROM employee GROUP BY dept HAVING avg(age)>32;
JOIN:
A JOIN clause combines rows from two or more tables. In a join query, more then one table are
listed in FORM clause.
Types of Join Operation:
Cartesian product on two tables,
Equii-join
Natural join
Equii Join :
To perform Equii/Inner Join on two relations R1 and R2, we have to specify a equality
condition using the common attribute in both the relations R1 and R2.
Syntax: SELECT * FROM R1 , R2 WHERE CUSTOMER.CUSTID=ORDERS.CUSTID;
Natural Join :
The Join in which only one of the identical columns(coming from joined tables) exists, is
called as Natural Join.
The Equii Join and Natural join are equivalent except that duplicate columns are
eliminated in the Natural Join that would otherwise appear in Equii Join.
Syntax: SELECT * FROM Table1 Natural Join Table2
JOIN Examples:
QUESTION BANK
Which of the following commands is not a DDL command?
1.
(a) DROP (b) DELETE (c) CREATE (d) ALTER
Which of the following SQL statements is used to open a database named “SCHOOL”?
2. (a) CREATE DATABASE SCHOOL; (b) USE DATABASE SCHOOL;
(c) USE SCHOOL; (d) SHOW DATABASE SCHOOL;
A relation can have only one______key and one or more than one______keys.
3. (a) PRIMARY, CANDIDATE (b) CANDIDATE, ALTERNATE
(c )CANDIDATE ,PRIMARY (d) ALTERNATE, CANDIDATE
What are the minimum number of attributes required to create a table in MySQL?
4.
(a) 1 (b) 2 (c) 0 (d)3
SUM(), ANG() and COUNT() are examples of ______functions.
5. (a) single row functions (b) multiple row functions
(c) math function (d) date function
What are the mandatory arguments which are required to connect a MySQL database to python?
(a) username, password, hostname, database name
6. (b) username, password, hostname
(c) username, password, hostname, port
(d) username, password, hostname, database name
The correct definition of column ‘alias’ is
7. a) A permanent new name of column b) A new column of a table
c) A view of existing column with different name d) A column which is recently deleted
In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table, Beta has
degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian product of
8.
Alpha and Beta?
a. 5,3 b. 8,15 c. 3,5 d. 15,8
Which function is used to display the unique values of a column of a table?
9.
a) sum() b) unique() c) distinct() d) return()
The statement which is used to get the number of rows fetched by execute() method of cursor:
10. a) cursor.rowcount b) cursor.rowscount()
c) cursor.allrows() d) cursor.countrows()
Select the correct statement, with reference to SQL:
a) Aggregate functions ignore NULL
11. b) Aggregate functions consider NULL as zero or False
c) Aggregate functions treat NULL as a blank string
d) NULL can be written as 'NULL' also.
Fill in the blank
12. _____________ command is used to modify the primary key in a relation in MySql.
a) update b) change c) alter d) modify
A table has initially 10 columns and 5 rows. Consider the following sequence of operations
performed on the table –
i. 8 rows are added ii. 2 columns are renamed
13.
iii. 3 rows are deleted iv. 1 column is added
What will be the cardinality and degree of the table at the end of above operations?
(a) 10,13 (b) 10, 11 (c) 13,10 (d) 11,10
Which of the following constraint checks if data is entered for a field in a table.
14.
(a) Not Null (b) Default (c) Primary Key (d) Unique
The structure of the table/relation can be displayed using __________ command.
15.
(a) view (b) describe (c) show (d) select
Which of the following are wildcard characters used in MySQL
16.
(a) %,_ (b) *,- (c) %,- (d) *,_
17. Module to be imported to establish connection between Python and MySql is _______________.
Fill in the blank: -
18. _____________ command is used to add a new column into an existing table in SQL.
(a) UPDATE (b) INSERT (c) ALTER (d) CREATE
Which of the following command is a DDL command?
19.
(a) SELECT (b) GROUP BY (c) DROP (d) UNIQUE
Fill in the blank:
20. Number of records/ tuples/ rows in a relation or table of a database is referred to as ________
(a) Domain (b) Degree (c) Cardinality (d) Integrity
The __________________ clause is used for pattern matching in MySQL queries.
21.
(a) ALL (b) DESC (c) MATCH (d) LIKE
Which of the following query is incorrect? Assume table EMPLOYEE with attributes
EMPCODE, NAME, SALARY and CITY.
(a) SELECT COUNT(*) FROM EMPLOYEE;
22.
(b) SELECT COUNT(NAME) FROM EMPLOYEE;
(c) SELECT AVG(SALARY) FROM EMPLOYEE;
(d) SELECT MAX(SALARY) AND MEAN(SALARY) FROM EMPLOYEE;
Which one of the following syntax is correct to establish a connection between Python and MySQL
database using the function connect( ) of mysql.connector package?
Assume that import mysql.connector as mycon is imported in the program
23. (a) mycon.connect(host = “hostlocal”, user = “root”, password = “MyPass”)
(b) mycon.connect(host = “localhost”, user = “root”, passwd = “MyPass”, database = “test”)
(c) mycon.connect(“host”=“localhost”, “user”= “root”, “passwd”=”MyPass”, “database”= “test”)
(d) mycon.connect(“localhost” = host, “root”=user, “MyPass”=passwd)
BETWEEN clause in MySQL cannot be used for ___________
24.
a) Integer Fields b) Varchar fields c) Date Fields d) None of these
State True or False
25.
“A table in RDBMS can have more than one Primary Keys”
COUNT(*) function in MySQL counts the total number of _____ in a table.
26.
a) Rows b) Columns c) Null values of column d) Null values of a row
Which of the following is not a method for fetching records from MySQL table using Python
27. interface?
a) fetchone() b) fetchrows() c) fetchall() d) fetchmany()
What is the maximum width of numeric value in data type int of MySQL.
28.
a) 10 digits b) 11 digits c) 9 digits d) 12 digits
In MYSQL database, if a table, Student has degree 2 and cardinality 3, and another table, Address
has degree 5 and cardinality 6, what will be the degree and cardinality of the Cartesian product of
29.
student and address?
a) 6,18 b) 7,18 c) 10,9 d) 12,15
Which of the following keywords will you use in the following query to display the unique values
of the column dept_name?
30.
SELECT ____________ dept_name FROM Company;
(a)All (b) key (c) Distinct (d) Name
Which SQL command is used to change some values in existing rows?
31.
a) update b) insert c) alter d) order
In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table, Beta has
degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian product of Alpha
32.
and Beta?
a) 5,3 b) 8,15 c) 3,5 d) 15,8
Select correct collection of DDL Command?
33. (a) CREATE, DELETE, ALTER, MODIFY (b) CREATE, DROP, ALTER, UPDATE
(c) CREATE, DROP, ALTER (d) CREATE, DELETE, ALTER, UPDATE
Which of the following constraint is used to prevent a duplicate value in a record?
34.
(a) Empty (b) check (c) primary key (d) unique
The structure of the table/relation can be displayed using __________ command.
35.
(a) view (b) describe (c) show (d) select
Which of the following clause is used to remove the duplicating rows from a select statement?
36.
(a) or (b) distinct (c) any (d)unique
Which of the following method is used to create a connection between the MySQL database and
37. Python?
(a) connector ( ) (b) connect ( ) (c) con ( ) (d) cont ( )
In MYSQL database, if a table, BOOK has degree 8 and cardinality 7, and another table, SALE has
degree 4 and cardinality 7, what will be the degree and cardinality of the Cartesian product of
38.
BOOK and SALE ?
a) 32 , 49 b) 12, 49 c) 12 ,14 d) 32,14
Fill in the blanks:
39.
The SQL keyword ____________ is used in SQL expression to select records based on patterns
In the relational models , cardinality actually refers to __________.
40.
a) Number of tuples b) Number of attributes c) Number of tables d) Number of constraints
The attribute which have properties to be as referential key is known as.
41.
(a) foreign key (b)alternate key (c) candidate key (d) Both (a) and (c)
If you want to add a new column in an existing table, which command is used. For example, to add
a column bonus in a table emp, the statement will be given as:
42.
a) ALTER table bonus ADD (emp Integer); b) CHANGE table emp ADD bonus int;
c) ALTER table emp ADD bonus int; d) UPDATE table emp ADD bonus int;
The data types CHAR (n) and VARCHAR (n) are used to create ___________ and __________
43. length types of string/text fields in a database.
a) Fixed, Variable b) Equal, Variable c) Fixed, Equal d) Variable, Equal
Which of the following is not an Aggregate function.
44.
a) COUNT b) MIN c) MAX d) DISTINCT
In a table in MYSQL database, an attribute Aof datatype char(20)has the value “Rehaan”. The
attribute B of datatype varchar(20) has value “Fatima”. How many characters are occupied by
45.
attribute A and attribute B?
a. 20,6 b. 6,20 c. 9,6 d. 6,9
SECTION - B,C,D,E
1. Differentiate between CHAR(N) and VARCHAR(N).
2. Differentiate between WHERE and HAVING with appropriate examples.
3. Differentiate between COUNT() AND COUNT(*) with appropriate examples.
4. Write SQL query to add a column total price with datatype numeric and size 10, 2 in a table product
Consider the following tables SCHOOL and ADMIN.
Give the output the following SQL queries:
5.
a) SELECT Designation COUNT (*) FROM Admin GROUP BY Designation HAVING COUNT
(*) <2;
b) SELECT max (EXPERIENCE) FROM SCHOOL;
c) SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY TEACHER;
d) SELECT COUNT (*), GENDER FROM ADMIN GROUP BY GENDER;
write SQL Queries for the following:
a) To display TEACHERNAME, PERIODS of all teachers whose periods are more than 25.
b) To display all the information from the table SCHOOL in descending order of experience.
c) To display DESIGNATION without duplicate entries from the table ADMIN.
d) To display TEACHERNAME, CODE and corresponding DESIGNATION from tables
SCHOOL and ADMIN of Male teachers
Sonal needs to display name of teachers, who have “0” as the third character in their name. She
wrote the following query.
6.
SELECT NAME FROM TEACHER WHERE NAME = “$$0?”;
But the query is’nt producing the result. Identify the problem.
Write output for (i) & (iv) based on table COMPANY and CUSTOMER.
7.
10.
11.
12.
17.
a) To display details of all items in the stock table in descending order of Stkdate.
b) To display the details of those items whose Dcode (Dealer Code) is 102 and Qty (Quantity) is
more than 50 from the table stock.
c) To display the itname, dcode and qty for all the stocks whose qty is in the range 50 to 100
(both inclusive)
Consider the following table EMP and DEPT
18.
20.
a) Write SQL statement to display details of all the products not manufactured by Samsung
b) Write SQL statement to display name of the Smartphone manufactured by Samsung.
c) Write SQL statement to display the name of the Product whose price is more than 20000
d) Write SQL statement to display name of all such Product which start with letter ‘W’
Explain the Relational Database Management System terminologies- Degree and Attribute of a
21.
relation. Give example to support your answer.
22. Explain the use of GROUP BY clause in MySQL with an appropriate example
Consider the following tables – BILLED and ITEM
23.
24.
25.
27.
31.
32.
Based on the given table, write SQL queries for the following:
(i) Display TNAME, CITY and HIREDATE of those trainers who were hired in the year 2001
(ii) Change the name of city as MUMBAI wherever name of city is BOMBAY
(iii) Add primary key constraint in the existing TRAINER table, to make TID as primary key.
Consider PASSENGERS and TRAINS tables given below:
33.
38.
39.
Based on the given table, write SQL queries for the following:
i. Display the details of all activities in which prize money is more than 9000 (including 9000)
ii. Increase the prize money by 5% of those activities whosw schedule date is after 1st of March
2023.
iii. Delete the record of activity where participants are less than 12.
Consider the following tables and answer the questions a and b:
40.
Table: Garment
Write SQL queries for the following:
47.
(i) Display the Mobile Company, Name and Price in descending order of their manufacturing ate
(ii) List the details of mobile whose name starts with “S” or ends with “a”
(iii) Display M_Id and sum of Moble quantity in each M_Id.
Consider the tables STORE and SUPPLIERS given below:
48.
i) To display ItemNo, Item Name and Sname from the tables with their corresponding matching
Scode.
ii) Display the structure of the table store.
iii) Display the average rate of Premium Stationary and Tetra Supply.
iv) Display the item, qty, and rate of products in descending order of rates
Karthik wants to write a program in Python to create student table in MYSQL database, SCHOOL:
▪ rno (Roll number)- integer
▪ name (Name) - string
▪ DOB (Date of birth) – Date
▪ fees – float
49.
Note the following to establish connectivity between Python and MySQL:
▪ Username - root
▪ Password - root
▪ Host - localhost
Help Kabir to write the program in Python to create the above table.
Rojalina Gamango has created a table named Student in MYSQL database, SCHOOL:
• rno (Roll number)- integer
• name (Name) - string
• DOB (Date of birth) – Date
• Fee – float
50. Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password – root
• Host – localhost
Rojalina Gamango now wants to display the records of students whose fee is more than 3500.
Rojalina Gamango to write the program in Python
51. Differentiate between DDL and DML
52. Write the main difference between INSERT and UPDATE Commands in SQL
Write the outputs of the SQL queries (a) to (c) based on the relation Furniture
53.
54.
55.
a) Write SQL statement to display details of all the products not manufactured by HL.
b) Write SQL statement to display name of the detergent powder manufactured by HL.
c) Write SQL statement to display the name of the Product whose price is more than 50
c) Write SQL statement to display name of all such Product which start with letter ‘N’
Satheesh has created a database “school” and table “student”. Now he wants to view all the
56. databases present in his laptop. Help him to write SQL command for that , also to view the structure
of the table he created
Meera got confused with DDL and DML commands. Help her to select only DML command from
57. the given list of command. UPDATE , DROP TABLE, SELECT , CREATE TABLE , INSERT
INTO, DELETE , USE
Consider the following table DOCTOR given below and write the output of the SQL Queries that
follows :
58.
60.
63.
64.
I) SELECT Designation, COUNT (*) FROM Admin GROUP BY Designation HAVING COUNT (*) <2;
Ii) SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY TEACHER DESC;
Write the outputs of the SQL queries (i) to (iv) based on the relations CLUB and STUDENT given
65.
below:
i) SELECT SPORTS, MIN(PAY) FROM Club Group by SPORTS ;
ii) SELECT MAX(DATEOFAPP), MIN(DATEOFAPP) FROM CLUB;
iii) SELECT CNAME, PAY, C.COACHID, SPORTS FROM CLUB C, STUDENT S WHERE C.COACHID
=S.COACHID AND PAY>=1500;
iv) SELECT SName, CNAME FROM Student S, CLUB C WHERE Gender =’F’ AND
C.COACHID=S.COACHID;
(v) Write SQL command to list all databases.
Mubarak creates a table Items with a set of records to maintain the details of items. After creation of
the table, he has entered data of 5 items in the table.
66.
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If 3 columns are added and 2 rows are deleted from the table , what will be the new degree and
cardinality of the above table?
(iii) Write a SQL statement to insert the following record into the table as (2024, Point Pen, 20, 11,
350, 15-NOV-2022).
(iv) Write a SQL statement to increase the rate of the items by 2% whose name ends with ‘c’.
(v) Write a SQL statement to delete the record of items having rate greater than equal to 10.
(vi) Write a SQL statement to add a column REMARKS in the table with datatype as varchar with 50
characters
City Hospital is considering to maintain their inventory using SQL to store the data. As a database
administer, Ritika has decided that :
• Name of the database - CH
• Name of the table - CHStore
The attributes of CHStore are as follows:
ItemNo - numeric
67.
68.
69.
Based on the given table, write SQL queries for the following:
a) Write a query to increase the salary of the Clerk by 5%.
b) Write down a query to display the information of those employees whose joining is in between
01/01/1985 and 31/03/2000.
c) Write a query to delete the details of Managers.
70. Consider the relations/tables EMP and DEPT and give the correct answer of following queries.
Relation: DEPT