0% found this document useful (0 votes)
7 views

SQL Revision Notes Question Bank

The document provides a comprehensive overview of databases, focusing on their structure, advantages, and the use of SQL for data manipulation. It covers key concepts such as database management systems, data models, relational databases, and various SQL commands including DDL and DML. Additionally, it explains data types, constraints, and operations like joins and aggregate functions in SQL.

Uploaded by

amuthavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

SQL Revision Notes Question Bank

The document provides a comprehensive overview of databases, focusing on their structure, advantages, and the use of SQL for data manipulation. It covers key concepts such as database management systems, data models, relational databases, and various SQL commands including DDL and DML. Additionally, it explains data types, constraints, and operations like joins and aggregate functions in SQL.

Uploaded by

amuthavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

PEARLS PUBLIC SCHOOL (CBSE)

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.

Database Management System (DBMS)


A DBMS refers to a software that is responsible for storing, maintaining and utilizing
database. Some examples of the popular database software include MySQL, Microsoft Access,
Microsoft SQL Server, FileMaker Pro, Oracle Database, and dBASE.

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 Data Model


In Relational data model data is organized into tables( rows and columns). Tables in a
relational model is called as Relations. Each row of a relation represents a relationship between
all the values in the row.

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

Relational Database Terminologies


 Tuple/Record: In Relational Database, rows in the Relation/Table are referred as
records
 Attributes/Fields: Columns are referred as Attributes/Fields.
 Cardinality: Total number of records in the relation is called as its Cardinality.
 Degree: Total number of Attributes/Fields in the relation is called as its Degree.
 Domain: permitted range of values of an attribute for an entity.
 Primary key: The attribute or the set of attributes that uniquely identifies records in a
relation is called as the Primary key of the Relation.
 Types of Keys:
 Candidate Key: A Candidate key is a attribute/set of attributes that uniquely
identifies tuples in a relation. A relation may be more then one candidate key.
 Primary Key: A Primary key is a attribute/set of attributes that uniquely
identifies tuples in a relation. All the values in the primary Key need to be unique
and NOT NULL.
 Among all the candidate keys the Database Administrator(DBA) selects one as
Primary key. A relation may have multiple Candidate Keys but ONLY ONE Primary
Key.
 Alternate Key: A alternate is basically is/are those candidate key which is/are
not used as Primary key of the relation.
 Foreign Key: Foreign key is a attribute of a relation(called as Child table) that
refers to the Primary Key of another relation(called as parent table).

What is a Structured Query Language (SQL)?

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 definition Language(DDL): Data Definition Language actually consists of the


SQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of database
objects in the database.
Example: Create, Drop, Alter.

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.

Data Types in MySQL


Data stored in a database table are of different types, As SQL developers we have
chose the suitable data types for each field while defining a table. SQL offers supports a wide
range of data types from which the developer can choose the most appropriate data types for
each column.
 char(size): used for fixed length string data.
Example: A column defined as char(10) , it can contain string values of maximum 10
length. SQL allocates 10 bytes of memory irrespective of legth of data to be stored.
 varchar(size): used for variable length string data.
Example: If a column defined as varchar(10) , SQL allocates maximum 10 bytes to each
value, but bytes allocated may vary depending on the length of data.
 int( ): Used for integer/digits data without decimal. Can accommodate maximum 11
digit numbers.
 float(M,D): Permits real numbers upto M digits, out of which may be D digits after
decimal .
Example: a column data type defined as float(6,3) may have 234.684
 Date: used to store date in YYYY-MM-DD format.

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 Databases: Used to list all existing databases.


Syntax: SHOW Databases;

DROP Database: Used to delete an existing database.


Syntax: DROP Database <databasename>
e.g. DROP Database MyStore;

USE Database: Used to select/enter a existing database.


e.g. USE 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));

Creating a table with multiple constraints:


CREATE TABLE Employee (Eid int(5) Primary Key,
Ename varchar(30) Not Null,
age int(2),
Dept varchar(20) Default “Manufacturing”,
contactno int(10) unique,
Constraint ChkAge Check(Age>18));
DESCRIBE Tables: A DDL command to display the structure of the table.
Syntax: DESCRIBE <table name>;

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.

Adding a column using Alter table:

Syntax: ALTER TABLE <table name> ADD column <Column Name Data type>;

Deleting a column using Alter table:


Syntax: ALTER TABLE <table name> DROP column <Column Name >;

Modify a column using Alter table:


Syntax: ALTER TABLE <table name> MODIFY column <Column Name Data type>;

E.g. MODIFY the data type of an existing column


Adding a Primary Key Constraint using Alter table:
Syntax: ALTER TABLE <table name> ADD Primary Key (<column names>);

Drop Primary Key Constraint using Alter table:


Syntax: ALTER TABLE <table name> DROP Primary Key;

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..);

Insert a new record in the table with specific field value.


Syntax: INSERT INTO <Table Name> (Column1,Column2,..ColumnN) values
(val1,val2,..valN);

SELECT Command:
Used to retrieve and display data from the tables.

Syntax: SELECT column1, column2,..


FROM <Table Name>;
To Select all the columns from the table:
SELECT * FROM <Table Name>;

WHERE Clause:
The WHERE Clause can be used with SELECT command to select the data from
the table based on some condition.

Syntax: SELECT column1, column2,..


FROM <Table Name>
WHERE <condition>;

Operators That Can Be Used In Where Clause :


Mathematical: +, -, *, /
Relational: >, >=, <, <=, =, <>
Logical: AND, OR, NOT

E.g. Select * From cs_students WHERE smark>90;


To select ID and Name of the students whose skill is Database:

Using Logical Operators in Where clause:

IN Operator: Used To specify multiple possible values for a column


E.g. Select * from cs_student where skill in(“Networking”, ”Database”);

BETWEEN Operator: Used To specify values in a certain range.


E.g. Select * from cs_student where smark BETWEEN 95 AND 100;

DISTINCT Clause: Used to retrieve the distinct values in a field.


Syntax: Select * from student where mark is null;
ORDER BY: It is used to sort the data in ascending or descending order.

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;

To delete the records of all the employee working in Sales Department.


DELETE FROM employee WHERE Dept=“salary”;

To delete all rows of employee table


DELETE FROM employee;
Aggregate Functions :
MySql supports the following aggregate/multiple row functions:
 count( ): returns the number of rows in the given column or expression.
 min( ): returns the minimum value in the given column or expression.
 max( ): returns the maximum value in the given column or expression.
 sum( ): returns the sum of values in the given column or expression.
 avg( ): returns the average of values in the given column or expression.
Let us Consider the employee table:

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.

Let us consider the cs_students table,

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

Cartesian Product (X):


The Cartesian Product operation of two tables produces all possible concatenations of
all the rows of both tables.
The Cartesian product(also known as Cross Join) multiplies all rows present in the first
table with all the rows present in the second table
Syntax: SELECT * FROM Table1,Table2;
Or
SELECT * FROM Table1 CROSS JOIN Table2;
The Cardinality of cartesian product of two relations R1 and R2 is equal to the
multiplication of cardinalities of R1 and R2. Whereas The Degree of cartesian Product is equal
to addition of degrees of R1 and R2.

Cartesian Product (X)


Example:
Let us Consider the Cartesian Product/Cross Join the of following Customer and Order Tables

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.

a) SELECT COUNT(*) , CITY FROM COMPANY GROUP BY CITY;


b) SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10;
c) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
d) SELECT PRODUCTNAME, CITY, PRICE FROM COMPANY, CUSTOMER
WHERE COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=”MOBILE”;
Write a Python code to read the following record from the table named employee and displays only
those records who have salary greater than 53500:
Empcode – integer
EmpName – string
8. EmpSalary – integer
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is root@123
• The table exists in a MYSQL database named management.
Ms. Tejasvi has just created a table named “Student” containing columns sname, Class and Mark.
After creating the table, she realized that she has forgotten to add a primary key column in the table.
Help her in writing an SQL command to add a primary key column StuId of integer type to the table
9. Student. Thereafter, write the command to insert the following record in the table:
StuId- 1299
Sname- Shweta
Class: XII
Mark: 98
Consider the table CLUB given below and write the output of the SQL queries that follow

10.

a) SELECT DISTINCT MAKE FROM CAR;


b) SELECT MAKE, COUNT(*) FROM CAR GROUP BY MAKE;
c) SELECT CNAME FROM CAR WHERE CAPACITY>5 ORDER BY CNAME;
A relation Toys is given below :

11.

Write SQL commands to:


a) Display the average price of each type of company having quantity more than 15.
b) Count the type of toys manufactured by each company.
c) Display the total price of all toys
Consider the following tables Consumer and Stationary.

12.

Write SQL statements for (a) to (d)


a) To display the consumer detail in descending order of their name.
b) To display the Name and Price of Stationaries whose Price is in the range 10 to 15.
c) To display the ConsumerName, City and StationaryName for stationaries of "Reynolds"
Company
d) To increase the Price of all stationary by 2 Rupees
13. Define the term Domain with respect to RDBMS. Give one example to support your answer?
Kabir wants to write a program in Python to insert the following record in the table named Student
in MYSQL database, SCHOOL:
 rno(Roll number )- integer
 name(Name) - string
14.
 DOB (Date of birth) – Date
 Fee – float
Note the following to establish connectivity between Python and MySQL:
 Username - root
 Password - tiger
 Host - localhost
The values of fields rno, name, DOB and fee has to be accepted from the user. Help Kabir to write
the program in Python.
15. Give one difference between Primary key and unique key.
Sartaj has created a table named Student in MYSQL database, SCHOOL:
 rno(Roll number )- integer
 name(Name) - string
 DOB (Date of birth) – Date
 Fee – float
16. Note the following to establish connectivity between Python and MySQL:
 Username - root
 Password - tiger
 Host - localhost
Help Sartaj to write the program in python to display the details of the student those who born after
2007
Write the outputs of the SQL queries (a) to (c) based on the relation STOCK

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.

Write outputs for the following SQL queries


a) SELECT dno, MAX(salary) FROM emp GROUP BY dno;
b) SELECT COUNT(DISTINCT gender) from emp;
c) SELECT ename,dname,salary FROM emp,dept WHERE emp.dno = dept.deptno AND
location='B1';
19. Consider the table
TABLE : BOOKS

Note the following to establish connectivity between Python and MYSQL:


 Username - root
 Password - system
 Table - mysql
 Database - Admin
Write a python program to increase the price of book containing C++ by 100.
Based on given table PRODUCTS answer following questions.

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.

What will be the output of the following SQL query statement?


SELECT * FROM BILLED, ITEM;
Write the output of the queries (i) to (iv) based on the table EMPLOYEE given below

24.

i. SELECT DISTINCT DESIGNATION FROM EMPLOYEE;


ii. SELECT CITY, SUM(Salary) FROM EMPLOYEE GROUP BY CITY HAVING SALARY > 50000;
iii. SELECT NAME, SALARY FROM EMPLOYEE WHERE CITY IN (‘DELHI’,’KOLKATA’) ORDER BY NAME
DESC;
iv. SELECT NAME, SALARY, CITY FROM EMPLOYEE WHERE NAME LIKE ‘H%’ AND SALARY
BETWEEN 50000 AND 90000;
Write the outputs of the SQL queries (i) to (iv) based on the relations ENGINEER and SALARY
given below:
Table: ENGINEER

25.

i. SELECT DEPARTMENT, COUNT(*) FROM ENGINEER GROUP BY DEPARTMENT;


ii. SELECT MAX(DOJ), MIN(DOJ) FROM ENGINEER;
iii. SELECT NAME, DEPARTMENT, (BASIC+HRA+DA) AS “TOTALSALARY” FROM ENGINEER, SALARY
WHERE ENGINEER.EID =SALARY.EID;
iv. SELECT NAME, HRA FROM ENGINEER E, SALARY S WHERE E.EID=S.EID AND GENDER = ’F’;
26. Write a command to view the structure of a table
Manoj is working in a mobile shop and assigned a task to create a table MOBILES with record of
mobiles as Mobile code, Model, Company, Price and Date of Launch. After creation of the table, he
has entered data of 5 mobiles in the MOBILES table.

27.

Based on the data given above answer the following questions:


i. Identify the most appropriate column, which can be considered as Primary key.
ii. Write the degree and cardinality of the above table, after removing one column and two more
record added to the table.
iii. Write the statements to add a new column GST with data type integer to the table.
iv. Write the statements to Insert the value of GST in the new column as 18% of PRICE.
v. Write the statements to to insert a new record of mobile as MobileCode – M06, Company
Apple, Model- iPHONE13, Price-110000 and Date of launch – ‘2022-03-01’.
vi. Write the statements to delete the record of mobile with model as NARZO50.
Write a python program to insert the record in the table employee:
 EmpNo – integer
 EmpName – string
 Salary – integer
 City – string
28.
Note the following to establish connectivity between Python and MYSQL:
 Username is root
 Password is tiger
The table exists in a MYSQL database named COMPANY.
The details (EmpNo, EmpName, Salary and City) are to be accepted from the user.
Write a python program to display the record from the table named Product and displays only those
records whose price is greater than 500:
 PNo – integer
 PName – string
29.  Price – integer
Note the following to establish connectivity between Python and MYSQL:
 Username is root
 Password is tiger
The table exists in a MYSQL database named school.
Define constraint in context with Relational Database Management System. Explain any two
30.
constraints of MySQL
Write the output of the queries (i) to (iii) based on the table PRODUCTS given below:

31.

i. SELECT COUNT(TDATE) FROM PRODUCTS;


ii. SELECT MAX(TDATE) FROM PRODUCTS WHERE PRICE BETWEEN 1000 AND 1400;
iii. SELECT ITEM, QTY*PRICE AS TOTAL FROM PRODUCTS WHERE QTY > 200 AND ITEM LIKE
‘%tap%’ ;
Consider the table TRAINER given below:

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.

Write SQL queries for the following:


i. Display the passenger names (PNAME), travel date (TRAVELDATE) and train name (TNAME)
from which each passenger has travelled from PASSENGERS and TRAINS tables.
ii. Display the average age of all passengers gender wise.
iii. Display the details of trains in ascending order of train numbers (TNO)
iv. Display starting stations (START) of TRAINS table without repetition.
34. What is meant by Degree of a table in RDBMS?
Krishna wants to write a program in Python to insert the following record into STAFF table of
COMPANY database using python interface.
 SID (Staff ID) – Integer
 SNAME (Name of staff member) - String
 DOJ (Date of Joining) – Date
 SALARY – Float
35.
Note the following to establish connectivity between Python and MySQL:
 Username - root
 Password - tiger
 Host - localhost
The values of fields SID, SNAME, DOJ and SALARY has to be accepted from the user. Help
Krishna to write the program in Python.
Ms. Ragini has just created a table named “Customer” containing columns Cname, Department and
36.
Salary.
After creating the table, she realized that she has forgotten to add a primary key column in the table.
Help her in writing an SQL command to add a primary key column Custid of integer type to the
table Customer. Thereafter, write the command to insert the following record in the table:
Custid- 555
Cname- Nandini
Department: Management
Salary- 45600
Manish is working in a database named CCA, in which he has created a table named “DANCE”
containing columns danceID, Dancename, no_of_participants, and category. After creating the
37. table, he realized that the attribute, category has to be deleted from the table and a new attribute
TypeCCA of data type string has to be added. This attribute TypeCCA cannot be left blank. Help
Manish to write commands to complte both the tasks.
Write the output of queries i) to iii) based on the table, LOANS given below:

38.

i. Select sum(Loan_Amount) from LOANS where Int_Rate > 10 ;


ii. Select max(Interest) from LOANS;
iii. Select count(*) from LOANS where Int_Rate is NULL;
Consider the table ACTIVITY given below:

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:

i. Display unique quantities of garments.


ii. Display sum of quantities for each CCODE whose numbers of records are more than 1.
iii. Display GNAME, CNAME, RATE whose quantity is more than 100.
iv. Display average rate of garment whose rate ranges from 1000 to 2000 (both values included)
41. Define the term foreign key with respect to RDBMS. Give one example to support your answer.
Kiran wants to write a program in Python to insert the following record in the table named Flight in
MYSQL database KV:
• Flno (Flight number)-varchar
• Source (source)- varchar
• Destination (Destination)-varchar
• Fare (fare)-integer
42.
Note the following to establish connectivity between Python and MySQL:
• User name-root
• Password – KVS@123
• Host-localhost
The values of fields Flno,Source,Destination and Fare has to be accepted from the user. Help Kiran
to write the program in Python.
43. Give the difference between primary key and alternate key
Shivaji has created a table named Game in MYSQL database Sports:
• GID (Game ID)-integer
• Gname( Game name)-varchar
• No_of_Participants (number of participants)- integer
Note the following to stablish connectivity between Python and MySQL:
44.
• Username: root
• Password: KVS@123
• Host: localhost
Shivaji, now wants to display the records of students whose number of participants are more than
10, Help Shivaji to write the program in Python.
Mr. Raja has just created a table named “Employee” containing columns Ename, Department and
Salary. After creating the table, he realized that he has forgotten to add a primary key column in the
45. table. Help him in writing an SQL command to add aprimary key column EmpId of integer type to
the table Employee. Thereafter, write the command to insert the following record in the table:
EmpId- 999 ,Ename- Shweta ,Department: Production, Salary: 26900
A music store MySports is considering to maintain their inventory using SQL to store the data. The
46.
detail is as follow:
Write an SQL statement to modify the no of players to 60 whose SCode is “S006”
Write SQL commands for the following queries (i) to (iii) on the basis of relation Mobile Master
and Mobile Stock.
MOBILE STOCK

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.

(a) SELECT Itemname FROM Furniture WHERE Type="Double Bed";


(b) SELECT MONTHNAME(Dateofstock) FROM Furniture WHERE Type="Sofa";
(c) SELECT Price*Discount FROM Furniture WHERE Dateofstock>31/12/02;
Consider the following table GAMES

54.

Write the output for the following queries :


(i) SELECT COUNT(DISTINCT Number) FROM GAMES;
(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;
Based on given table “DETERGENTS” answer following questions.

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.

i) SELECT D_NAME FROM DOCTOR WHERE GENDER=MALE AND EXPERIENCE=12 ;


ii) SELECT DISTINCT(D_DEPT) FROM DOCTOR ;
iii) SELECT D_NAME , EXPERIENCE FROM DOCTOR ORDER BY EXPERIENCE ;
59. Consider the following Table “TEACHER”
Based on the above table, Write SQL command for the following :
i) To show all information about the teacher of maths department
ii) To list name and department whose name starts with letter ‘M’
iii) To display all details of female teacher whose salary in between 35000 and 50000
Consider the table PRODUCT and CLIENT given below:

60.

Write SQL Queries for the following:


i) Display the details of those clients whose city is DELHI
ii) Increase the Price of all Bath soap by 10
iii) Display the details of Products having the highest price
iv) Display the product name, price, client name and city with their corresponding matching
product Id.
Maya has created a table named BOOK in MYSQL database, LIBRARY
61. BNO(Book number )- integer
B_name(Name of the book) - string
Price (Price of one book) –integer
Note the following to establish connectivity between Python and
MySQL: Username – root, Password – writer,Host – localhost.
Maya, now wants to display the records of books whose price is more than 250. Help Maya to write
the program in Python
62. What is the difference between UNIQUE and PRIMARY KEY constraints ?
Consider the following tables – Employee and Office:

63.

What will be the output of the following statement?


SELECT Name, Dept FROM Emp E, dept d WHERE E.Emp_Id=d.Emp_Id;
Consider the following tables SCHOOL and ADMIN. Give the output the following SQL queries:

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.

 ItemName – character of size 20


 Scode - numeric
 Quantity – numeric
Now Ritika wants to remove the column Quantity from the table CHStore . And she also wants to
display the structure of the table CHStore, i.e, name of the attributes and their respective data types
that she has used in the table. Help her to write the correct command .
Consider the table EXAM given below and write the output of the following SQL queries:

68.

a) SELECT AVG(Stipend) FROM EXAM WHERE DIVISION=”Third”


b) SELECT COUNT(DISTINCT Subject) FROM EXAM;
c) SELECT MIN(Average) FROM EXAM WHERE Subject=”English”;
Consider a table EMPLOYEE with the following data:

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

Write SQL queries for the following:


a) Display the total no. of employees in each department?
b) Display the jobs where the number of employees is less than 3.
c) Display the name of the employee & their department name.
d) Display the maximum salary of the manager.
Ravi wants to write a program in Python to read the records from a table named TRAINER and
increase the salary of Trainer SUNAINA by 2000.
TID -integer
TNAME -string
CITY-string
71. SALARY-integer
Note the following to establish connectivity between Python and MYSQL:
• Host is localhost
• Username is root
• Password is system
• The table exists in a MYSQL database named Admin.

You might also like