0% found this document useful (0 votes)
13 views56 pages

Database Management Q and A

The document contains a series of SQL questions and answers related to database management, including commands for creating tables, inserting records, and querying data. It covers topics such as the use of SELECT statements, aggregate functions, and DDL commands, along with practical examples of SQL commands. Additionally, it includes tasks for modifying tables and retrieving specific information from the database.

Uploaded by

Memerboy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views56 pages

Database Management Q and A

The document contains a series of SQL questions and answers related to database management, including commands for creating tables, inserting records, and querying data. It covers topics such as the use of SELECT statements, aggregate functions, and DDL commands, along with practical examples of SQL commands. Additionally, it includes tasks for modifying tables and retrieving specific information from the database.

Uploaded by

Memerboy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Database Management Q & A (From Board QP)

1 The SELECT statement when _______ combined with clause, returns records 2024 1
without repetition.
(a) DISTINCT (b) DESCRIBE
(c) UNIQUE (d) NULL
Ans. (a) DISTINCT
2 In SQL, the aggregate function which will display the cardinality of the table is 2024 1
________
(a) sum ( ) (b) count(*)
(c) avg ( ) (d) sum(*)
Ans. (b) count(*)
3 Which of the following is not a DDL command in SQL? 2024 1
(a) DROP (b) CREATE
(c)UPDATE (d) ALTER
Ans. (c)UPDATE
4 (A) Ms. Veda created a table named Sports in n MySQL database, containing 2024
columns Game_Id, P_Age and G_name. After creating the table, she realized
that the attribute, Category has to be added. Help her to write a command to
add the Category column. Thereafter, write the command to insert the following
record in the table:

Game_ld: G42
P_Age: Above 18
G_name: Chess
Category: Senior
Ans.: alter table Sports add category varchar(15);
or
alter table Sports add column category varchar(15);
Insert into Sports values ('G42', 'Above 18', 'Chess', 'Senior');

To remove the column category:


alter table Sports drop category;
OR
alter table Sports drop column category;
4 (B) Write the SQL commands to perform the following tasks: 2024 2
(i) View the list of tables in the database, Exam

Ans.:
USE Exam;
Show tables;
(ii) View the structure of the table, Term1.

Ans:
DESC Term1;

5 Consider the table ORDERS given below and write the output of the SQL queries 2024 3
that follow:

ORDNO ITEM QTY RATE ORDATE


1001 RICE 23 120 2023-09-10

1002 PULSES 13 120 2023-10-18

1003 RICE 25 110 2023-11-17

1004 WHEAT 28 65 2023-12-25

1005 PULSES 16 110 2024-01-15

1006 WHEAT 27 55 2024-04-15

1007 WHEAT 25 60 2024-04-30

(i) SELECT ITEM, SUM (QTY) FROM ORDERS GROUP BY ITEM;


(ii) SELECT ITEM, QTY FROM ORDERS WHERE ORDATE BETWEEN
'2023-11-01' AND '2023-12-31'
(iii) SELECT ORDNO, ORDATE FROM ORDERS WHERE ITEM =
'WHEAT' AND RATE>=60;

Creating Database, Creating Table and Inserting records in Table before 3


executing the queries:
mysql> CREATE DATABASE CBSE2024;
Query OK, 1 row affected (0.16 sec)

mysql> USE CBSE2024;


Database changed
mysql> SHOW TABLES;
Empty set (0.01 sec)

mysql> CREATE TABLE ORDERS (ORRNO INT, ITEM VARCHAR(7), QTY INT, RATE INT,
ORDATE DATE);
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO ORDERS VALUES(1001,'RICE',23,120,'2023-09-10');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO ORDERS VALUES(1002,'PULSES',13,120,'2023-10-18');


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ORDERS VALUES(1003,'RICE',25,110,'2023-11-17');

Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ORDERS VALUES(1004,'WHEAT',28,65,'2023-12-25');

Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ORDERS VALUES(1005,'PULSES',16,110,'2024-01-15'


);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ORDERS VALUES(1006,'WHEAT',27,55,'2024-04-15');

Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ORDERS VALUES(1007,'WHEAT',25,60,'2024-04-30');

Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM ORDERS;


+-------+--------+------+------+------------+
| ORRNO | ITEM | QTY | RATE | ORDATE |
+-------+--------+------+------+------------+
| 1001 | RICE | 23 | 120 | 2023-09-10 |
| 1002 | PULSES | 13 | 120 | 2023-10-18 |
| 1003 | RICE | 25 | 110 | 2023-11-17 |
| 1004 | WHEAT | 28 | 65 | 2023-12-25 |
| 1005 | PULSES | 16 | 110 | 2024-01-15 |
| 1006 | WHEAT | 27 | 55 | 2024-04-15 |
| 1007 | WHEAT | 25 | 60 | 2024-04-30 |
+-------+--------+------+------+------------+
7 rows in set (0.00 sec)

mysql> SELECT ITEM, SUM(QTY) FROM ORDERS GROUP BY ITEM;


+--------+----------+
| ITEM | SUM(QTY) |
+--------+----------+
| RICE | 48 |
| PULSES | 29 |
| WHEAT | 80 |
+--------+----------+
3 rows in set (0.01 sec)

mysql> SELECT ITEM, QTY FROM ORDERS WHERE ORDATE BETWEEN '2023-11-01' AND
'2023-12-31';
+-------+------+
| ITEM | QTY |
+-------+------+
| RICE | 25 |
| WHEAT | 28 |
+-------+------+
2 rows in set (0.00 sec)

mysql> SELECT ORDNO, ORDATE FROM ORDERS WHERE ITEM = 'WHEAT' AND RATE>=60;
ERROR 1054 (42S22): Unknown column 'ORDNO' in 'field list'
mysql> ALTER TABLE ORDERS RENAME COLUMN ORRNO TO ORDNO;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0

SELECT ORDNO, ORDATE FROM ORDERS WHERE ITEM = 'WHEAT' AND RATE>=60;
+-------+------------+
| ORDNO | ORDATE |
+-------+------------+
| 1004 | 2023-12-25 |
| 1007 | 2024-04-30 |
+-------+------------+
2 rows in set (0.00 sec)

6 Consider the table Projects given below:

Table: Projects

P_id Pname Language Startdate Enddate


P001 School Python 2023-01-12 2023-04-03
Management
System
P002 Hotel C++ 2022-12-01 2023-02-02
Management
System
P003 Blood Bank Python 2023-02-11 2023-03-02
P004 Payroll Python 2023-03-12 2023-06-02
Management
System

Based on the given table, write SQL queries for the following:
(i) Add the constraint, primary key to column P_id in the existing table
Projects.
(ii) To change the language to Python of the project whose id is P002.
(iii) To delete the table Projects from MySQL database along with its data.

Ans:
Creating the above table in database CBSE2024
mysql> CREATE TABLE PROJECTS (P_id CHAR(4), Pname VARCHAR(27), Language
VARCHAR(7), Startdate DATE, Enddate DATE);
Query OK, 0 rows affected (0.20 sec)

mysql> INSERT INTO PROJECTS VALUES('P001','School Management


System','Python','2023-01-12','2023-04-03');
Query OK, 1 row affected (0.03 sec)

mysql> INSERT INTO PROJECTS VALUES('P002','Hotel Management


System','C++','2022-12-01','2023-02-02');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO PROJECTS VALUES('P003','Blood Bank','Python','2023-02-


11','2023-03-02');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO PROJECTS VALUES('P004','Payroll Management


System','Python','2023-03-12','2023-06-02');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM PROJECTS;


+------+---------------------------+----------+------------+------------+
| P_id | Pname | Language | Startdate | Enddate |
+------+---------------------------+----------+------------+------------+
| P001 | School Management System | Python | 2023-01-12 | 2023-04-03 |
| P002 | Hotel Management System | C++ | 2022-12-01 | 2023-02-02 |
| P003 | Blood Bank | Python | 2023-02-11 | 2023-03-02 |
| P004 | Payroll Management System | Python | 2023-03-12 | 2023-06-02 |
+------+---------------------------+----------+------------+------------+
4 rows in set (0.00 sec)

mysql> DESC PROJECTS;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| P_id | char(4) | YES | | NULL | |
| Pname | varchar(27) | YES | | NULL | |
| Language | varchar(7) | YES | | NULL | |
| Startdate | date | YES | | NULL | |
| Enddate | date | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.02 sec)

(i) Add the constraint, primary key to column P id in the existing


table Projects.
Ans.:
mysql> ALTER TABLE PROJECTS ADD PRIMARY KEY P_id;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near '' at line 1
mysql> ALTER TABLE PROJECTS ADD PRIMARY KEY(P_id);
Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESC PROJECTS;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| P_id | char(4) | NO | PRI | NULL | |
| Pname | varchar(27) | YES | | NULL | |
| Language | varchar(7) | YES | | NULL | |
| Startdate | date | YES | | NULL | |
| Enddate | date | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
6
mysql> SELECT * FROM PROJECTS;
+------+---------------------------+----------+------------+------------+
| P_id | Pname | Language | Startdate | Enddate |
+------+---------------------------+----------+------------+------------+
| P001 | School Management System | Python | 2023-01-12 | 2023-04-03 |
| P002 | Hotel Management System | C++ | 2022-12-01 | 2023-02-02 |
| P003 | Blood Bank | Python | 2023-02-11 | 2023-03-02 |
| P004 | Payroll Management System | Python | 2023-03-12 | 2023-06-02 |
+------+---------------------------+----------+------------+------------+
4 rows in set (0.00 sec)

mysql> UPDATE PROJECTS SET Language='Python' WHERE P_id='P002';


Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT * FROM PROJECTS;
+------+---------------------------+----------+------------+------------+
| P_id | Pname | Language | Startdate | Enddate |
+------+---------------------------+----------+------------+------------+
| P001 | School Management System | Python | 2023-01-12 | 2023-04-03 |
| P002 | Hotel Management System | Python | 2022-12-01 | 2023-02-02 |
| P003 | Blood Bank | Python | 2023-02-11 | 2023-03-02 |
| P004 | Payroll Management System | Python | 2023-03-12 | 2023-06-02 |
+------+---------------------------+----------+------------+------------+
4 rows in set (0.00 sec)
(ii) To change the language to Python of the project whose id is P002.
Ans.: mysql> UPDATE PROJECTS SET Language='Python' WHERE P_id='P002';
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0

(III) To delete the table Projects from MySQL database along with its data.

Ans:
mysql> DROP TABLE PROJECTS;
Query OK, 0 rows affected (0.08 sec)

mysql> SHOW TABLES;


+--------------------+
| Tables_in_cbse2024 |
+--------------------+
| orders |
+--------------------+
1 row in set (0.01 sec)

mysql> DROP TABLE PROJECTS;


ERROR 1051 (42S02): Unknown table 'cbse2024.projects'
mysql>
(Table Projects is deleted)
7 Consider the tables Admin and Transport given below: Table: Admin 2024

Table: Admin
S_id S_Name Address S_type
S001 Sandhya Rohini Day Boarder
S002 Vedanshi Rohtak Day Scholar
S003 Vibhu Raj Nagar NULL
S004 Atharva Rampur Day Boarder

Table: Transport
S_id Sub_no Stop_name
S002 TSS10 Sarai Kale Khan
S004 TSS12 Sainik Vihar
S005 TSS10 Kamla Nagar

Write SQL queries for the following:


(i) Display the student name and their stop
name from the tables Admin and
Transport.
(ii) Display the number of students whose
S_type is not known.
(iii) Display all details of the students
whose name starts with 'V'.
(iv) Display student id and address in
alphabetical order of student name,
from the table Admin.

Ans. Creating Tables Admin and Transport in database CBSE2024.


mysql> USE CBSE2024;
Database changed
mysql> CREATE TABLE ADMIN(S_is CHAR(4), S_name VARCHAR(9), Address
VARCHAR(10), S_type VARCHAR(12));
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO ADMIN VALUES('S001', 'Sandhya', 'Rohini', 'Day


Boarder');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO ADMIN VALUES('S002','Vedanshi', 'Rohtak', 'Day


Boarder');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ADMIN VALUES('S003','Vibhu','Raj Nagar',NULL);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO ADMIN VALUES('SS004','Atharva', 'Rampur','Day


Boarder');
ERROR 1406 (22001): Data too long for column 'S_is' at row 1
mysql> INSERT INTO ADMIN VALUES('S004', 'Atharva', 'Rampur', 'Day
Boarder');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM ADMIN;


+------+----------+-----------+-------------+
| S_is | S_name | Address | S_type |
+------+----------+-----------+-------------+
| S001 | Sandhya | Rohini | Day Boarder |
| S002 | Vedanshi | Rohtak | Day Boarder |
| S003 | Vibhu | Raj Nagar | NULL |
| S004 | Atharva | Rampur | Day Boarder |
+------+----------+-----------+-------------+
4 rows in set (0.00 sec)

mysql> DESC ADMIN;


+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| S_is | char(4) | YES | | NULL | |
| S_name | varchar(9) | YES | | NULL | |
| Address | varchar(10) | YES | | NULL | |
| S_type | varchar(12) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> ALTER TABLE ADMIN RENAME COLUMN S_is TO S_id;


Query OK, 0 rows affected (0.03 sec)

mysql> CREATE TABLE TRANSPORT(S_id CHAR(4), Bus_no CAHR(5),


Stop_name VARCHAR(16));
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'CAHR(5), Stop_name VARCHAR(16))' at line 1
mysql> CREATE TABLE TRANSPORT(S_id CHAR(4), Bus_no CHAR(5),
Stop_name VARCHAR(16));
Query OK, 0 rows affected (0.08 sec)

mysql> INSERT INTO TRANSPORT VALUES('S002','TSS10', 'Sarai Kale


Khan');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO TRANSPORT VALUES('S004','TSS12', 'Sainik Vihar');


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO TRANSPORT VALUES('S005','TSS10', 'Kamla Nagar');


Query OK, 1 row affected (0.01 sec)

mysql> DESC TRANSPORT;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| S_id | char(4) | YES | | NULL | |
| Bus_no | char(5) | YES | | NULL | |
| Stop_name | varchar(16) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM TRANSPORT;


+------+--------+-----------------+
| S_id | Bus_no | Stop_name |
+------+--------+-----------------+
| S002 | TSS10 | Sarai Kale Khan |
| S004 | TSS12 | Sainik Vihar |
| S005 | TSS10 | Kamla Nagar |
+------+--------+-----------------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM ADMIN;


+------+----------+-----------+-------------+
| S_id | S_name | Address | S_type |
+------+----------+-----------+-------------+
| S001 | Sandhya | Rohini | Day Boarder |
| S002 | Vedanshi | Rohtak | Day Boarder |
| S003 | Vibhu | Raj Nagar | NULL |
| S004 | Atharva | Rampur | Day Boarder |
+------+----------+-----------+-------------+
4 rows in set (0.00 sec)

Write SQL queries for the following:


(i) Display the student name and their stop name from the tables
Admin and Transport.
Ans.:
mysql> SELECT S_name, Stop_name FROM Admin A, Transport T WHERE
A.S_id=T.S_id;
OR
mysql> SELECT S_name, Stop_name FROM Admin, Transport WHERE
Admin.S_id=Transport.S_id;
+----------+-----------------+
| S_name | Stop_name |
+----------+-----------------+
| Vedanshi | Sarai Kale Khan |
| Atharva | Sainik Vihar |
+----------+-----------------+
2 rows in set (0.00 sec)

(ii) Display the number of students whose S_type is not known.


Ans.:
mysql> SELECT COUNT(*) FROM Admin WHERE S_type IS NULL;
+----------+
| COUNT(*) |
+----------+
| 1 |
+----------+
1 row in set (0.01 sec)

mysql> SELECT COUNT(*) FROM Admin WHERE S_type = NULL;


(It will not give correct output)
+----------+
| COUNT(*) |
+----------+
| 0 |
+----------+
1 row in set (0.01 sec)
(iii) Dislay all details of the students whose name starts with 'V'.
Ans.:
mysql> SELECT * FROM Admin WHERE S_name LIKE 'V%';
+------+----------+-----------+-------------+
| S_id | S_name | Address | S_type |
+------+----------+-----------+-------------+
| S002 | Vedanshi | Rohtak | Day Boarder |
| S003 | Vibhu | Raj Nagar | NULL |
+------+----------+-----------+-------------+
2 rows in set (0.00 sec)

(iv) Display student id and address in alphabetical order of


student name, from the table Admin.
Ans.:
mysql> SELECT S_id, Address FROM Admin ORDER BY S_name ASC;
OR
mysql> SELECT S_id, Address FROM Admin ORDER BY S_name;
+------+-----------+
| S_id | Address |
+------+-----------+
| S004 | Rampur |
| S001 | Rohini |
| S002 | Rohtak |
| S003 | Raj Nagar |
+------+-----------+
4 rows in set (0.00 sec)
8 (A) (i) Define Cartesian Product with respect to RDBMS. 2024 1

Ans.: Cartesian product

The Cartesian product is used to combine each


row in one table with each row in the other
table. It is also known as a cross product.
It is denoted by X. In Cartesian Product the
Degrees are added and Cardinalities are
multiplied.

mysql> select * from transport;


+------+--------+-----------------+
| S_id | Bus_no | Stop_name |
+------+--------+-----------------+
| S002 | TSS10 | Sarai Kale Khan |
| S004 | TSS12 | Sainik Vihar |
| S005 | TSS10 | Kamla Nagar |
+------+--------+-----------------+
3 rows in set (0.00 sec)

mysql> select * from admin;


+------+----------+-----------+-------------+
| S_id | S_name | Address | S_type |
+------+----------+-----------+-------------+
| S001 | Sandhya | Rohini | Day Boarder |
| S002 | Vedanshi | Rohtak | Day Boarder |
| S003 | Vibhu | Raj Nagar | NULL |
| S004 | Atharva | Rampur | Day Boarder |
+------+----------+-----------+-------------+
4 rows in set (0.00 sec)

mysql> select * from transport, admin;


+------+--------+-----------------+------+----------+-----------+-------------+
| S_id | Bus_no | Stop_name | S_id | S_name | Address | S_type
|
+------+--------+-----------------+------+----------+-----------+--------
-----+
| S002 | TSS10 | Sarai Kale Khan | S001 | Sandhya | Rohini | Day
Boarder |
| S004 | TSS12 | Sainik Vihar | S001 | Sandhya | Rohini | Day
Boarder |
| S005 | TSS10 | Kamla Nagar | S001 | Sandhya | Rohini | Day
Boarder |
| S002 | TSS10 | Sarai Kale Khan | S002 | Vedanshi | Rohtak | Day
Boarder |
| S004 | TSS12 | Sainik Vihar | S002 | Vedanshi | Rohtak | Day
Boarder |
| S005 | TSS10 | Kamla Nagar | S002 | Vedanshi | Rohtak | Day
Boarder |
| S002 | TSS10 | Sarai Kale Khan | S003 | Vibhu | Raj Nagar | NULL
|
| S004 | TSS12 | Sainik Vihar | S003 | Vibhu | Raj Nagar | NULL
|
| S005 | TSS10 | Kamla Nagar | S003 | Vibhu | Raj Nagar | NULL
|
| S002 | TSS10 | Sarai Kale Khan | S004 | Atharva | Rampur | Day
Boarder |
| S004 | TSS12 | Sainik Vihar | S004 | Atharva | Rampur | Day
Boarder |
| S005 | TSS10 | Kamla Nagar | S004 | Atharva | Rampur | Day
Boarder |
+------+--------+-----------------+------+----------+-----------+--------
-----+
12 rows in set (0.01 sec)

8 (A) (ii) Sunil wants to write a program in Python to update the quantity to 20 of the 2024 4
records whose item code is 111 in the table named shop in MySQL database
named Keeper.
Tho table shop in MySQL contains the following attributes:
• Item_code: Item code (Integer)
• Item_name: Name of item (String)
• Qty: Quantity of item (Integer)
• Price: Price of item (Integer)
Consider the following to establish connectivity between Python and MySQL:
• Username: admin
• Password: Shopping
• Host: localhost
mysql> USE KEEPER;
Database changed
mysql> CREATE TABLE Shop (Item_code INT, Item_name VARCHAR(10), Qty INT,
Price INT);
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO SHOP VALUES (111, 'CHAIR', 10, 200);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO SHOP VALUES (222, 'TABLE', 15, 400);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO SHOP VALUES (333, 'BED', 5, 4000);


Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM SHOP;


+-----------+-----------+------+-------+
| Item_code | Item_name | Qty | Price |
+-----------+-----------+------+-------+
| 111 | CHAIR | 10 | 200 |
| 222 | TABLE | 15 | 400 |
| 333 | BED | 5 | 4000 |
+-----------+-----------+------+-------+
3 rows in set (0.00 sec)

Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd='yadav', database='keeper')
#Change Username: admin, Password: Shopping, Host: localhost as per the
question

cur=con.cursor()
query='update shop set qty= 20 where Item_code=111'
cur.execute(query)
con.commit()
cur.execute("select * from shop")
Records=cur.fetchall()
count=cur.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
con.close()

Output:
8 (B) (i) Give any two features of SQL. 1

Ans.: Features of SQL


SQL (Structured Query Language) is a domain-specific language used for
managing and manipulating relational databases. It offers several key
features that make it a powerful tool for working with data:
(i) User-friendly data retrieval
(ii) Data modification with ease
(iii) Data integrity and constraints
(iv) Joining tables for comprehensive insights

8 (B) (ii) Sumit wants to write a code in Python to display all the details of the 2024 4
passengers from the table flight in MySQL database, Travel. The table contains
the following attributes:

F_code: Flight code (String)


F_name: Name of flight (String)
Source: Departure city of flight (String)
Destination: Destination city of flight (String)
Consider the following to establish connectivity between Python and MySQL:
• Username: root
• Password: airplane
• Host: localhost
Ans.: Creating database Travel and table Flight. Inserting records in table
Flight.
mysql> CREATE DATABASE Travel;
Query OK, 1 row affected (0.02 sec)

mysql> USE TRAVEL;


Database changed
mysql> CREATE TABLE FLIGHT (F_code CHAR(5), F_name
VARCHAR(10), Source VARCHAR(10), Destination
VARCHAR(10));
Query OK, 0 rows affected (0.10 sec)

mysql> INSERT INTO FLIGHT


VALUES('EK505','EMIRATES','DUBAI','MUMBAI');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO FLIGHT


VALUES('EK504','EMIRATES','MUMBAI','DUBAI');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO FLIGHT VALUES('AI504','AIR


INDIA','DELHI','DUBAI');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO FLIGHT VALUES('AI505','AIR


INDIA','DUBAI','DELHI');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM FLIGHT;


+--------+-----------+--------+-------------+
| F_code | F_name | Source | Destination |
+--------+-----------+--------+-------------+
| EK505 | EMIRATES | DUBAI | MUMBAI |
| EK504 | EMIRATES | MUMBAI | DUBAI |
| AI504 | AIR INDIA | DELHI | DUBAI |
| AI505 | AIR INDIA | DUBAI | DELHI |
+--------+-----------+--------+-------------+
4 rows in set (0.00 sec)

Program:

import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd='yadav',database='travel')

#Chnage Username: root, Password: airplane, Host: localhost as per the


question

cur=con.cursor()
cur.execute("select * from flight")
Records=cur.fetchall()
count=cur.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
con.close()

Output:
9 Fill in the blank: COMPT 1
In a relational model, tables are called _________, that store data for different 2023
columns.
(a) Attributes (b) Degrees (c) Relations (d) Tuples
Ans.: (c) Relations
10 Fill in the blank: _________ statement of SQL is used to insert new records in a COMPT 1
table. 2023
(a) ALTER (b) UPDATE (c) INSERT (d) CREATE
Ans.:(c) INSERT
11 fetchone() method fetches only one row in a ResultSet and returns a __________. COMPT 1
(a) Tuple (b) List (c) Dictionary (d) String 2023
Ans (a) Tuple
12 Explain the usage of HAVING clause in GROUP BY command in RDBMS with the COMPT 2
help of an example. 2023
Ans.:
HAVING is used for including conditions based on aggregate functions on
groups.
SELECT DEPT, COUNT(*) FROM EMPLOYEE GROUP BY DEPT HAVING
COUNT(*)>1;
Above command will return the number of employees in each department for
the departments having more than 1 employee.
13 (a) Differentiate between IN and BETWEEN operators in SQL with appropriate COMPT 2
examples. 2023
Ans.:
IN() function in MySQL finds a match in the given arguments.
Exprs IN (value1, value2, ...)
The function returns 1 if Exprs is equal to any of the values in the IN list,
otherwise, returns 0.
Example:
SELECT NAME, SECTION FROM STUDENTS WHERE SECTION IN (‘C’ , ‘D’);

Whereas BETWEEN operator in MySQL selects values within a given range.


The values can be numbers, text, or dates.
Range values are inclusive, both begin and end values are included.
Example:
SELECT ROLL, MARKS FROM RESULT WHERE MARKS BETWEEN 75 AND 100;
13 (b) Which of the following is NOT a DML command. DELETE, DROP, INSERT, COMPT 2
UPDATE 2023
Ans.: DROP
(2 Marks for mentioning the correct answer) (Deduct ½ mark for writing each
wrong answer, if written along with DROP)
14 (a) Consider the following tables - Student and Sport: COMPT 1
Table: Student 2023

Table: Sport

What will be the output of the following statement?


SELECT * FROM Student, Sport;

Ans.:
Creating Database CBSE2023Compt and creating tables
Student and Sport and inserting records:

mysql> create database cbse2023compt;


Query OK, 1 row affected (0.06 sec)

mysql> use cbse2023compt;


Database changed
mysql> CREATE TABLE Student(ADMNO INT, NAME VARCHAR(
7), CLASS VARCHAR(4));
Query OK, 0 rows affected (0.14 sec)

mysql> INSERT INTO STUDENT VALUES (1100,'MEENA','X')


;
Query OK, 1 row affected (0.03 sec)

mysql> INSERT INTO STUDENT VALUES (1101,'VANI','XI')


;
Query OK, 1 row affected (0.01 sec)

mysql> CREATE TABLE Sport( ADMNO INT, GAME VARCHAR(1


0));
Query OK, 0 rows affected (0.08 sec)
mysql> INSERT INTO SPORT VALUES(1100,'CRICKET');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO SPORT VALUES(1103,'FOOTBALL');


Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM STUDENT;


+-------+-------+-------+
| ADMNO | NAME | CLASS |
+-------+-------+-------+
| 1100 | MEENA | X |
| 1101 | VANI | XI |
+-------+-------+-------+

mysql> SELECT * FROM SPORT;


+-------+----------+
| ADMNO | GAME |
+-------+----------+
| 1100 | CRICKET |
| 1103 | FOOTBALL |
+-------+----------+

mysql> SELECT * FROM STUDENT, SPORT;


+-------+-------+-------+-------+----------+
| ADMNO | NAME | CLASS | ADMNO | GAME |
+-------+-------+-------+-------+----------+
| 1100 | MEENA | X | 1100 | CRICKET |
| 1101 | VANI | XI | 1100 | CRICKET |
| 1100 | MEENA | X | 1103 | FOOTBALL |
| 1101 | VANI | XI | 1103 | FOOTBALL |
+-------+-------+-------+-------+----------+

mysql> SELECT * FROM SPORT,STUDENT;


+-------+----------+-------+-------+-------+
| ADMNO | GAME | ADMNO | NAME | CLASS |
+-------+----------+-------+-------+-------+
| 1100 | CRICKET | 1100 | MEENA | X |
| 1103 | FOOTBALL | 1100 | MEENA | X |
| 1100 | CRICKET | 1101 | VANI | XI |
| 1103 | FOOTBALL | 1101 | VANI | XI |
+-------+----------+-------+-------+-------+
14 (b) Write the output of the queries (i) to (iv) based on the table, GARMENT given COMPT
below: 2023
TABLE: GARMENT

(i) SELECT DISTINCT(COUNT(FCODE))FROM GARMENT;


(ii) SELECT FCODE, COUNT(*), MIN(PRICE) FROM
GARMENT GROUP BY FCODE HAVING COUNT(*)>1;
(iii) SELECT TYPE FROM GARMENT WHERE ODR_DATE
>'2021-02-01' AND PRICE <1500;
(iv) SELECT * FROM GARMENT WHERE TYPE LIKE 'F%';

Creating table GARMENT in database cbse2023compt and


inserting records:

mysql> create database cbse2023compt;


Query OK, 1 row affected (0.06 sec)

mysql> use cbse2023compt;


Database changed

mysql> CREATE TABLE GARMENT (GCODE CHAR(4), TYPE


VARCHAR(15), PRICE INT, FCODE CHAR(3), ODR_DATE DATE);
Query OK, 0 rows affected (0.07 sec)

mysql> INSERT INTO GARMENT VALUES('G101', 'EVENING GOWN',


850, 'F03', '2008-12-19');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO GARMENT VALUES('G102', 'SLACKS', 750,


'F02', '2020-10-20');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO GARMENT VALUES('G103', 'FROCK', 1000,


'F01', '2021-09-09');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO GARMENT VALUES('G104', 'TULIP SKIRT',


1550, 'F01', '2021-08-10');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO GARMENT VALUES('G105', 'BABY TOP',


1500, 'F02', '2020-03-31');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO GARMENT VALUES('G106', 'FORMAL PANT',


1250, 'F01', '2019-01-06');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM GARMENT;


+-------+--------------+-------+-------+------------+
| GCODE | TYPE | PRICE | FCODE | ODR_DATE |
+-------+--------------+-------+-------+------------+
| G101 | EVENING GOWN | 850 | F03 | 2008-12-19 |
| G102 | SLACKS | 750 | F02 | 2020-10-20 |
| G103 | FROCK | 1000 | F01 | 2021-09-09 |
| G104 | TULIP SKIRT | 1550 | F01 | 2021-08-10 |
| G105 | BABY TOP | 1500 | F02 | 2020-03-31 |
| G106 | FORMAL PANT | 1250 | F01 | 2019-01-06 |
+-------+--------------+-------+-------+------------+
(i) SELECT DISTINCT(COUNT(FCODE)) FROM GARMENT;
+----------------+
| (COUNT(FCODE)) |
+----------------+
| 6 |
+----------------+

mysql> SELECT COUNT(FCODE) FROM GARMENT;


+--------------+
| COUNT(FCODE) |
+--------------+
| 6 |
+--------------+
mysql> SELECT (COUNT(DISTINCT FCODE))FROM GARMENT;
+-------------------------+
| (COUNT(DISTINCT FCODE)) |
+-------------------------+
| 3 |
+-------------------------+

(ii) SELECT FCODE, COUNT(*), MIN(PRICE) FROM GARMENT GROUP BY


FCODE HAVING COUNT(*)>1;
+-------+----------+------------+
| FCODE | COUNT(*) | MIN(PRICE) |
+-------+----------+------------+
| F02 | 2 | 750 |
| F01 | 3 | 1000 |
+-------+----------+------------+
(iii) SELECT TYPE FROM GARMENT WHERE ODR_DATE >'2021-02-01' AND
PRICE <1500;
+-------+
| TYPE |
+-------+
| FROCK |
+-------+
(iv) SELECT * FROM GARMENT WHERE TYPE LIKE 'F%';
mysql> SELECT * FROM GARMENT WHERE TYPE LIKE 'F%';
+-------+-------------+-------+-------+------------+
| GCODE | TYPE | PRICE | FCODE | ODR_DATE |
+-------+-------------+-------+-------+------------+
| G103 | FROCK | 1000 | F01 | 2021-09-09 |
| G106 | FORMAL PANT | 1250 | F01 | 2019-01-06 |
+-------+-------------+-------+-------+------------+

15 Write the output of any three SQL queries (i) to (iv) based on the tables COMPT 4
COMPANY and CUSTOMER given below: 2023
(i) SELECT PRODUCTNAME, COUNT(*)FROM COMPANY GROUP BY
PRODUCTNAME HAVING COUNT(*)> 2;
(ii) SELECT NAME, PRICE, PRODUCTNAME FROM COMPANY C,CUSTOMER CT
WHERE C.CID = CU.CID AND C_NAME = 'SONY';
(iii) SELECT DISTINCT CITY FROM COMPANY;
(iv) SELECT * FROM COMPANY WHERE C_NAME LIKE '%ON%';
Ans.:
Creating Tables Company and Customer in Database
CBSE2023COMPT.

mysql> USE CBSE2023COMPT;


Database changed
mysql> CREATE TABLE COMPANY (CID INT PRIMARY KEY, C_NAME
VARCHAR(12), CITY VARCHAR(8), PRODUCTNAME VARCHAR(7));
Query OK, 0 rows affected (0.22 sec)

mysql> INSERT INTO COMPANY VALUES (111, 'SONY', 'DELHI',


'TV');
Query OK, 1 row affected (0.03 sec)

mysql> INSERT INTO COMPANY VALUES (222, 'NOKIA',


'MUMBAI', 'MOBILE');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO COMPANY VALUES (333, 'ONIDA', 'DELHI',


'TV');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO COMPANY VALUES (444, 'SONY', 'MUMBAI',


'MOBILE');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO COMPANY VALUES (555, 'BLACKBERRY',


'CHENNAI', 'MOBILE');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO COMPANY VALUES (666, 'DELL', 'DELHI',


'LAPTOP');
Query OK, 1 row affected (0.01 sec)
mysql> CREATE TABLE CUSTOMER (CUSTID CHAR(3) PRIMARY KEY,
CID INT, NAME VARCHAR(15), PRICE INT, QTY INT);
Query OK, 0 rows affected (0.12 sec)

mysql> INSERT INTO CUSTOMER VALUES ('C01', 222, 'ROHIT


SHARMA', 70000, 20);
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO CUSTOMER VALUES ('C02', 666, 'DEEPIKA


KUMARI', 50000, 10);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO CUSTOMER VALUES ('C03', 111, 'MOHAN


KUMAR', 30000, 5);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO CUSTOMER VALUES ('C04', 555, 'RADHA


MOHAN', 30000, 11);
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM COMPANY;


+-----+------------+---------+-------------+
| CID | C_NAME | CITY | PRODUCTNAME |
+-----+------------+---------+-------------+
| 111 | SONY | DELHI | TV |
| 222 | NOKIA | MUMBAI | MOBILE |
| 333 | ONIDA | DELHI | TV |
| 444 | SONY | MUMBAI | MOBILE |
| 555 | BLACKBERRY | CHENNAI | MOBILE |
| 666 | DELL | DELHI | LAPTOP |
+-----+------------+---------+-------------+
6 rows in set (0.00 sec)

mysql> SELECT * FROM CUSTOMER;


+--------+------+----------------+-------+------+
| CUSTID | CID | NAME | PRICE | QTY |
+--------+------+----------------+-------+------+
| C01 | 222 | ROHIT SHARMA | 70000 | 20 |
| C02 | 666 | DEEPIKA KUMARI | 50000 | 10 |
| C03 | 111 | MOHAN KUMAR | 30000 | 5 |
| C04 | 555 | RADHA MOHAN | 30000 | 11 |
+--------+------+----------------+-------+------+
4 rows in set (0.00 sec)
Outputs:
(i) mysql> SELECT PRODUCTNAME, COUNT(*)FROM COMPANY GROUP BY
PRODUCTNAME HAVING COUNT(*)> 2;
+-------------+----------+
| PRODUCTNAME | COUNT(*) |
+-------------+----------+
| MOBILE | 3 |
+-------------+----------+
(ii) mysql> SELECT NAME, PRICE, PRODUCTNAME FROM COMPANY
C,CUSTOMER CT WHERE C.CID = CU.CID AND C_NAME = 'SONY';
ERROR 1054 (42S22): Unknown column 'CU.CID' in 'where
clause'
mysql> SELECT NAME, PRICE, PRODUCTNAME FROM COMPANY
C,CUSTOMER CT WHERE C.CID = CT.CID AND C_NAME = 'SONY';
+-------------+-------+-------------+
| NAME | PRICE | PRODUCTNAME |
+-------------+-------+-------------+
| MOHAN KUMAR | 30000 | TV |
+-------------+-------+-------------+
(iii) mysql> SELECT DISTINCT CITY FROM COMPANY;
+---------+
| CITY |
+---------+
| DELHI |
| MUMBAI |
| CHENNAI |
+---------+
(iv) mysql> SELECT * FROM COMPANY WHERE C_NAME LIKE '%ON%';
+-----+--------+--------+-------------+
| CID | C_NAME | CITY | PRODUCTNAME |
+-----+--------+--------+-------------+
| 111 | SONY | DELHI | TV |
| 333 | ONIDA | DELHI | TV |
| 444 | SONY | MUMBAI | MOBILE |
+-----+--------+--------+-------------+
16 (a) (ii) COMPT 3
The table Bookshop in MySQL contains the following attributes: 2023
B_code Integer
B_name String
Qty Integer
Price Integer
Note the following to establish connectivity between Python and MySQL:
Username is shop
Password is Book
The table exists in a MySQL database named Bstore.
The code given below updates the records from the table
Bookshop in MySQL. 3
Statement 1 to form the cursor object.
Statement 2 to execute the query that updates the Qty to 200 of the
records whose B_code is 105 in the table.
Statement 3 to make the changes permanent in the
database.
import mysql.connector as mysql
def update_book():
mydb=mysql.connect(host="localhost",
user="shop",passwd="Book",database="Bstore")

mycursor=__________ # Statement 1
qry= "update Bookshop set Qty=200 where B_code=105"
___________________ # Statement 2
___________________ # Statement 3

Ans.:
Creating database Bstore and table Bookshop in MySQL.
mysql> USE Bstore;
Database changed
mysql> DESC bookshop;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| B_Code | int | YES | | NULL | |
| B_Name | varchar(10) | YES | | NULL | |
| Qty | int | YES | | NULL | |
| Price | int | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)

mysql> select * from bookshop;


+--------+--------+------+-------+
| B_Code | B_Name | Qty | Price |
+--------+--------+------+-------+
| 101 | C Sc | 10 | 100 |
| 103 | IP | 5 | 50 |
| 105 | AI | 200 | 75 |
+--------+--------+------+-------+

import mysql.connector as mysql


def update_book():
#mydb=mysql.connect(host="localhost",
user="shop",passwd="Book",database="Bstore")
mydb=mysql.connect(host="localhost",user="root",
passwd='yadav',database='Bstore')
mycursor=mydb.cursor() # Statement 1
qry= "update Bookshop set Qty=200 where B_code=105"
mycursor.execute(qry) # Statement 2
mydb.commit() # Statement 3
mycursor.execute("select * from bookshop")
Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()

update_book()

Output:

16 (b) The table Bookshop in MySQL contains the following attributes: COMPT
B_code Integer 2023
B_name String
Qty Integer
Price Integer
Note the following to establish connectivity between Python and MySQL :
Username is shop
Password is Book
The table exists in a MySQL database named Bstore.
The code given below reads the records from the table Bookshop
and displays all the records:
Statement 1 to form the cursor object.
Statement 2 to write the query to display all the records from the table.

Statement 3 to read the complete result of the query into the object named
B_Details, from the table Bookshop in the database.

import mysql.connector as mysql


def Display_book():
mydb=mysql.connect(host="localhost",user="shop",
passwd="Book",database="Bstore")
mycursor=___________ # Statement 1
mycursor.execute("_________") # Statement 2
B_Details=__________ # Statement 3
for i in B_Details:
print(i)
mysql> USE Bstore;
Database changed
mysql> DESC bookshop;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| B_Code | int | YES | | NULL | |
| B_Name | varchar(10) | YES | | NULL | |
| Qty | int | YES | | NULL | |
| Price | int | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)

mysql> select * from bookshop;


+--------+--------+------+-------+
| B_Code | B_Name | Qty | Price |
+--------+--------+------+-------+
| 101 | C Sc | 10 | 100 |
| 103 | IP | 5 | 50 |
| 105 | AI | 200 | 75 |
+--------+--------+------+-------+

Ans.:

import mysql.connector as mysql


def Display_book():
#mydb=mysql.connect(host="localhost",user="shop",
passwd="Book",database="Bstore")
mydb=mysql.connect(host="localhost",user="root",
passwd="yadav",database="Bstore")
mycursor=mydb.cursor() # Statement 1
mycursor.execute("select * from bookshop") # Statement 2
B_Details=mycursor.fetchall() # Statement 3
for i in B_Details:
print(i)

Display_book()

Output:
17 The ABC Company is considering to maintain their salespersons records using COMPT 4
SQL to store data. As a database administrator, Alia created the table 2023
Salesperson and also entered the data of 5 Salespersons.

Creating Table Salesperson and inserting records into it.


mysql> use cbse2023compt;
Database changed

mysql> CREATE TABLE Salesperson (S_ID CHAR(4), S_NAME


VARCHAR(8), AGE INT, S_AMOUNT INT, REGION VARCHAR(7));
Query OK, 0 rows affected (0.20 sec)

mysql> INSERT INTO SALESPERSON VALUES ('S001', 'SHYAM',


35, 20000, 'NORTH');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO SALESPERSON VALUES ('S002', 'RISHABH',


30, 25000, 'EAST');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO SALESPERSON VALUES ('S003', 'SUNIL',


29, 21000, 'NORTH');
Query OK, 1 row affected (0.03 sec)

mysql> INSERT INTO SALESPERSON VALUES ('S004', 'RAHIL',


39, 22000, 'WEST');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO SALESPERSON VALUES ('S005', 'AMIT',


40, 23000, 'EAST');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM SALESPERSON;


+------+---------+------+----------+--------+
| S_ID | S_NAME | AGE | S_AMOUNT | REGION |
+------+---------+------+----------+--------+
| S001 | SHYAM | 35 | 20000 | NORTH |
| S002 | RISHABH | 30 | 25000 | EAST |
| S003 | SUNIL | 29 | 21000 | NORTH |
| S004 | RAHIL | 39 | 22000 | WEST |
| S005 | AMIT | 40 | 23000 | EAST |
+------+---------+------+----------+--------+
Based on the data given above, answer the following questions:
(i) Identify the attribute that is best suited to be the Primary Key and 1
why?

A Primary key: S_ID As it is non-repeating value and not expected to repeat for
new rows too.

(½ Mark for identifying the correct attribute for Primary Key) (½ Mark for
appropriate explanation)
Note: S_NAME should also be considered as a Primary Key

(ii) The Company has asked Alia to add another attribute in the table. 1
What will be the new degree and cardinality of the above table?

A Degree = 6 and Cardinality = 5

(½ Mark for writing value of Degree correctly)


(½ Mark for writing value of Cardinality correctly)

(iii) Write the statements to: 2


(a) Insert details of one salesman with appropriate data.
A INSERT INTO SALESPERSON VALUES ("S006","JAYA",23,34000,'SOUTH');

(b) Change region of salesman ‘SHYAM’ to ‘SOUTH’ in the table Salesperson.


A UPDATE SALESPERSON SET REGION='SOUTH' WHERE S_NAME="SHYAM";

OR (Option for part iii only)


(iii) Write the statement to: 2
(a) Delete the record of salesman RISHABH, as he has left the company.
A DELETE FROM SALESPERSON WHERE S_NAME="RISHABH";

(b) Remove an attribute REGION from the table.


A ALTER TABLE SALESPERSON DROP COLUMN REGION;
OR
ALTER TABLE SALESPERSON DROP REGION;
18 Fill in the blank: 2023 1
______________ is number of tuples in a relation.
(a) Attribute (b) Degree (c) Domain (d) Cardinality

Ans.: (d) Cardinality


19 Fill in the blank: 2023
_________ clause is used with SELECT statement do display data in a sorted
form with respect to a specified column.
(a) WHERE (b) ORDER BY (c) HAVING (d) DISCTINCT

Ans.: (b) ORDER BY


20 fetchall() method fetches all rows in a result set and returns a: 2023
(a) Tuples of lists (b) List of tuples (c) List of strings (d) Tuples of strings
Ans.: (b) List of tuples
21 Explain concept of Alternate Key in a Relational Database Management System 2023
with an appropriate example.
Ans.:
Alternate Keys are all the Candidate Keys of a RDBMS table, which have not
been used as a Primary Key.
Example:

In this example, any one of the RegNo and AadhaarNo can be used as a Primary
Key. If RegNo is used as the Primary Key then AadhaarNo is the Alternate Key.

22 (a) Differentiate between CHAR and VARCHAR data types in SQL with 2023 2
appropriate example.

CHAR is of fixed length character(string) data type, which means, declaring


CHAR (10) implies to reserve spaces for 10 characters. If data does not have 10
characters (e.g., ‘CITY’ has four characters), MySQL fills the remaining 6
characters with spaces padded on the right.

VARCHAR is a variable-length character(string) data type. Declaring VARCHAR


(30) means a maximum of 30 characters can be stored but the actual allocated
bytes will depend on the length of the entered string. So ‘CITY’ in VARCHAR (30)
will occupy space needed to store 4 characters only and the remaining 26 will
be released.

OR
CHAR data type is used to store strings of fixed length, while the VARCHAR data
type is used to store strings of variable-length. Eg, to store ‘India’, VARCHAR(20)
occupies only 5 bytes whereas CHAR(20) occupies 20 bytes.

22 (b) Name any two DDL and any two DML commands. 2023

Ans.:
DDL: CREATE, ALTER, and DROP.
DML: SELECT, INSERT, UPDATE, and DELETE.

23 (a) Consider the following Tables LOAN and BORROWER: 2023


Table: LOAN
LOAN_NO B_NAME AMOUNT
L-170 DELHI 3000
L-230 KANPUR 4000

Table: BORROWER
CUST_NAME LOAN_NO
JOHN L-171
KRISH L-230
RAVYA L-170

How many rows and columns will be there in Natural Join of these two tables?

Ans.:
Creating Tables: LOAN and BORROWER in Database CBSE2023;
mysql> CREATE TABLE LOAN (LOAN_NO CHAR(5),B_NAME
VARCHAR(7), AMOUNT INT);
Query OK, 0 rows affected (0.20 sec)

mysql> INSERT INTO LOAN VALUES('L-170', 'DELHI',3000);


Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO LOAN VALUES('L-230','KANPUR',4000);


Query OK, 1 row affected (0.01 sec)

mysql> CREATE TABLE BORROWER(CUST_NAME VARCHAR(6),LOAN_NO


CHAR(5));
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO BORROWER VALUES('JOHN','L-171');


Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO BORROWER VALUES('KRISH','L-230');


Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO BORROWER VALUES('RAVYA','L-170');


Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM LOAN;


+---------+--------+--------+
| LOAN_NO | B_NAME | AMOUNT |
+---------+--------+--------+
| L-170 | DELHI | 3000 |
| L-230 | KANPUR | 4000 |
+---------+--------+--------+
2 rows in set (0.01 sec)

mysql> SELECT * FROM BORROWER;


+-----------+---------+
| CUST_NAME | LOAN_NO |
+-----------+---------+
| JOHN | L-171 |
| KRISH | L-230 |
| RAVYA | L-170 |
+-----------+---------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM LOAN NATURAL JOIN BORROWER;


+---------+--------+--------+-----------+
| LOAN_NO | B_NAME | AMOUNT | CUST_NAME |
+---------+--------+--------+-----------+
| L-230 | KANPUR | 4000 | KRISH |
| L-170 | DELHI | 3000 | RAVYA |
+---------+--------+--------+-----------+
2 rows in set (0.01 sec)

mysql> SELECT * FROM BORROWER NATURAL JOIN LOAN;


+---------+-----------+--------+--------+
| LOAN_NO | CUST_NAME | B_NAME | AMOUNT |
+---------+-----------+--------+--------+
| L-230 | KRISH | KANPUR | 4000 |
| L-170 | RAVYA | DELHI | 3000 |
+---------+-----------+--------+--------+
2 rows in set (0.00 sec)
Q:How many rows and columns will be there in Natural Join of these two
tables?
Ans.: There are 2 rows and 4 columns in Natural Join of two tables LOAN and
BORROWER.
23 (b) Write the output of queries (i) to (iv) based on the 2023 4
table WORKER given below:
Table: WORKER
W_ID F_NAME L_NAME CITY STATE
102 SAHIL KHAN KANPUR UTTAR PRADESH
104 SAMEER PARIKH ROOP NAGAR PUNJAB
105 MARY JONES DELHI DELHI
106 MAHIR SHARMA SONIPAT HARYANA
107 ATHARVA BHARDWAJ DELHI DELHI
108 VEDA SHARMA KANPUR UTTAR PRADESH

(i) SELECT F_NAME, CITY FROM WORKER ORDER BY STATE DESC;


(ii) SELECT DISTINCT(CITY) FROM WORKER;
SELECT DISTINCT CITY FROM WORKER;
(iii) SELECT F_NAME, STATE FROM WORKER WHERE L_NAME LIKE '_HA%';
(iv) SELECT CITY, COUNT(*) FROM WORKER GROUP BY CITY;
Ans.: Outputs:
(i) mysql> SELECT F_NAME, CITY FROM WORKER ORDER BY STATE
DESC;
+---------+------------+
| F_NAME | CITY |
+---------+------------+
| SAHIL | KANPUR |
| VEDA | KANPUR |
| SAMEER | ROOP NAGAR |
| MAHIR | SONIPAT |
| MARY | DELHI |
| ATHARVA | DELHI |
+---------+------------+
(ii) mysql> SELECT DISTINCT(CITY) FROM WORKER;
OR
mysql> SELECT DISTINCT CITY FROM WORKER;
+------------+
| CITY |
+------------+
| KANPUR |
| ROOP NAGAR |
| DELHI |
| SONIPAT |
+------------+
(iii) mysql> SELECT F_NAME, STATE FROM WORKER WHERE L_NAME LIKE
'_HA%';
+---------+---------------+
| F_NAME | STATE |
+---------+---------------+
| SAHIL | UTTAR PRADESH |
| MAHIR | HARYANA |
| ATHARVA | DELHI |
| VEDA | UTTAR PRADESH |
+---------+---------------+
(iv) mysql> SELECT CITY, COUNT(*) FROM WORKER GROUP BY CITY;
+------------+----------+
| CITY | COUNT(*) |
+------------+----------+
| KANPUR | 2 |
| ROOP NAGAR | 1 |
| DELHI | 2 |
| SONIPAT | 1 |
+------------+----------+
24 (a) Write the output of queries (i) to (iv) based on the 2023 2
relations COMPUTER and SALES given below:

Table: COMPUTER
PROD_ID PROD_NAME PRICE COMPANY TYPE
P001 MOUSE 200 LOGITECH INPUT
P002 LASER PRINTER 4000 CANON OUTPUT
P003 KEYBOARD 500 LOGITECH INPUT
P004 JOYSTICK 1000 IBALL INPUT
P005 SPEAKER 1200 CREATIVE OUTPUT
P006 DESKJET PRINTER 4300 CANON OUTPUT

Table: SALES
PROD_ID QTY_SOLD QUARTER
P002 4 1
P003 2 2
P001 3 2
P004 2 1

(i) SELECT MIN(PRICE), MAX(PRICE) FROM COMPUTER;


(ii) SELECT COMPANY, COUNT(*) FROM COMPUTER GROUP BY COMPANY
HAVING COUNT(COMPANY)>1;
(iii) SELECT PROD_NAME, QTY_SOLD FROM COMPUTER C, SALES S WHERE
C.PROD_ID=S.PROD_ID AND TYPE = 'INPUT';
(iv) SELECT PROD_NAME, COMPANY, QUARTER FROM COMPUTER C, SALES S
WHERE C.PROD_ID=S.PROD_ID;
Ans.: Outputs:
(i) mysql> SELECT MIN(PRICE), MAX(PRICE) FROM COMPUTER;
+------------+------------+
| MIN(PRICE) | MAX(PRICE) |
+------------+------------+
| 200 | 4300 |
+------------+------------+
(ii) mysql> SELECT COMPANY, COUNT(*) FROM COMPUTER GROUP BY
COMPANY HAVING COUNT(COMPANY)>1;
+----------+----------+
| COMPANY | COUNT(*) |
+----------+----------+
| LOGITECH | 2 |
| CANON | 2 |
+----------+----------+
(iii) mysql> SELECT PROD_NAME, QTY_SOLD FROM COMPUTER C, SALES
S WHERE C.PROD_ID=S.PROD_ID AND TYPE = 'INPUT';
+-----------+----------+
| PROD_NAME | QTY_SOLD |
+-----------+----------+
| KEYBOARD | 2 |
| MOUSE | 3 |
| JOYSTICK | 2 |
+-----------+----------+
(iv) mysql> SELECT PROD_NAME, COMPANY, QUARTER FROM COMPUTER
C, SALES S WHERE C.PROD_ID=S.PROD_ID;
+---------------+----------+---------+
| PROD_NAME | COMPANY | QUARTER |
+---------------+----------+---------+
| LASER PRINTER | CANON | 1 |
| KEYBOARD | LOGITECH | 2 |
| MOUSE | LOGITECH | 2 |
| JOYSTICK | IBALL | 1 |
+---------------+----------+---------+
24 (b) Write the command to view all databases.
Ans.: SHOW DATABASES;
25 (a) The code given below deletes the record from the table employee which 2023 3
contains the following record structure:
E_code - String
E_name - String
Sal – Integer
City - String
Note the following to establish connectivity between Python and MySQL :
· Username is root
· Password is root
· The table exists in a MySQL database named emp.
· The details (E_code,E_name,Sal,City) are the attributes of the
table.
Write the following statements to complete the code :
Statement 1 – to import the desired library.
Statement 2 – to execute the command that deletes the record with
E_code as 'E101'.
Statement 3 – to delete the record permanently from the database.

import __________ as mysql # Statement 1


def delete() :
mydb=mysql.connect(host="localhost",user="root",
passwd="root",database="emp")
mycursor=mydb.cursor()
_________________ # Statement 2
_________________ # Statement 3
print ("Record deleted")

mycursor.execute("select * from employee")


Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()
delete()

Creating database EMP and creating Table Employee and


inserting 3 records in Table Employee
mysql> CREATE DATABASE EMP;
mysql> USE EMP;
mysql> SHOW TABLES;

mysql> CREATE TABLE EMPLOYEE (E_code CHAR(4), E_name


VARCHAR(10), Sal INT, City VARCHAR(10));

mysql> INSERT INTO EMPLOYEE VALUES('E101','ABC',11111,


'DUBAI');

mysql> INSERT INTO EMPLOYEE VALUES('E102','PQR',11123,


'SHARJAH');

mysql> INSERT INTO EMPLOYEE VALUES('E103','XYZ',11789,


'AJMAN');

mysql> SELECT * FROM EMPLOYEE;


+--------+--------+-------+---------+
| E_code | E_name | Sal | City |
+--------+--------+-------+---------+
| E101 | ABC | 11111 | DUBAI |
| E102 | PQR | 11123 | SHARJAH |
| E103 | XYZ | 11789 | AJMAN |
+--------+--------+-------+---------+

Ans.:
import mysql.connector as mysql # Statement 1 import
__________ as mysql
def delete():
#mydb=mysql.connect(host="localhost",user="root",
passwd="root",database="emp")
mydb=mysql.connect(host="localhost",user="root",
passwd='yadav',database='emp')
mycursor=mydb.cursor()
#cur.execute(query)
mycursor.execute("DELETE FROM employee WHERE
E_code='E101'") # Statement 2
mydb.commit() # Statement 3
print ("Record deleted")
mycursor.execute("select * from employee")
Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()
delete()

Output:

Record of employee having E_code ‘E101’ is deleted.


25 (b) The code given below reads the following records from the table employee 2023 3
and displays only those records who have employees coming from city
‘Delhi’:
E_code – String
E_name - String
Sal - Integer
City - String
Note the following to establish connectivity between Python and MySQL :
• Username is root
• Password is root
• The table exists in a MySQL database named emp.
• The details (E_code,E_name,Sal,City) are the attributes
of the table.
Write the following statements to complete the code :
Statement 1 – to import the desired library.
Statement 2 – to execute the query that fetches records of the employees
coming from city ‘Delhi’.
Statement 3 – to read the complete data of the query (rows whose city is
Delhi) into the object named details, from the table employee in
the database.
import _____________ as mysql # Statement 1
def display():
mydb=mysql.connect(host="localhost",user="root",
passwd="root",database="emp")
mycursor=mydb.cursor()
____________________________ # Statement 2
details = ___________________ # Statement 3
for i in details:
print (i)
display()
The Table Employee in Database EMP has the following
details:

mysql> USE EMP;

mysql> SELECT * FROM EMPLOYEE;


+--------+--------+-------+---------+
| E_code | E_name | Sal | City |
+--------+--------+-------+---------+
| E102 | PQR | 11123 | SHARJAH |
| E103 | XYZ | 11789 | AJMAN |
| E101 | ABC | 11111 | DELHI |

Ans.:
import mysql.connector as mysql # Statement 1
def display():
#mydb=mysql.connect(host="localhost",user="root",
passwd="root",database="emp")
mydb=mysql.connect(host="localhost",user="root",
passwd='yadav',database='emp')
mycursor=mydb.cursor()
mycursor.execute("SELECT * FROM employee WHERE
City='Delhi'") # Statement 2
details = mycursor.fetchall() # Statement 3
for i in details:
print (i)
display()

26 The school has asked their estate manager Mr. Rahul to 2023 4
maintain the data of all the labs in a table LAB. Rahul
has created a table and entered data of 5 labs.

LABNO LAB_NAME INCHARGE CAPACITY FLOOR


L001 CHEMISTRY DAISY 20 I
L002 BIOLOGY VENKY 20 II
L003 MATH PREETI 15 I
L004 LANGUAGE DAISY 36 III
L004 COMPUTER MARY KOM 37 I

Based on the data given above, answer the following


questions:

(i) Identify the columns which can be considered as Candidate keys. 2023 1
Ans.: Candidate keys: LABNO and LAB_NAME
(1 Mark for correctly writing both names of Candidate keys) OR (½ Mark for
specifying any one candidate key correctly)
(ii) Write the degree and cardinality of the table. 2023 1
Ans.: Degree = 5 Cardinality = 5
(iii) Write the statements to: 2023 2
(a) Insert a new row with appropriate data.
(b) Increase the capacity of all the labs by 10 students which are on ‘I’ Floor.
Ans.:
(a) INSERT INTO LAB VALUES('L006', 'PHYSICS',
'RAVI', 25,'II');
(b) UPDATE LAB SET CAPACITY=CAPACITY+10 WHERE
FLOOR='I';

mysql> SELECT * FROM LAB;


+-------+-----------+----------+----------+-------+
| LABNO | LAB_NAME | INCHARGE | CAPACITY | FLOOR |
+-------+-----------+----------+----------+-------+
| L001 | CHEMISTRY | DAISY | 20 | I |
| L002 | BIOLOGY | VENKY | 20 | II |
| L003 | MATH | PREETI | 15 | I |
| L004 | LANGUAGE | DAISY | 36 | III |
| L005 | COMPUTER | MARY KOM | 37 | II |
| L006 | PHYSICS | RAVI | 25 | II |
+-------+-----------+----------+----------+-------+
mysql> UPDATE LAB SET CAPACITY=CAPACITY+10 WHERE
FLOOR='I';
mysql> SELECT * FROM LAB;
+-------+-----------+----------+----------+-------+
| LABNO | LAB_NAME | INCHARGE | CAPACITY | FLOOR |
+-------+-----------+----------+----------+-------+
| L001 | CHEMISTRY | DAISY | 30 | I |
| L002 | BIOLOGY | VENKY | 20 | II |
| L003 | MATH | PREETI | 25 | I |
| L004 | LANGUAGE | DAISY | 36 | III |
| L005 | COMPUTER | MARY KOM | 37 | II |
| L006 | PHYSICS | RAVI | 25 | II |
+-------+-----------+----------+----------+-------+
OR
(Option for part (iii) only)

(iii) Write the statements to: 2023 2


(a) Add the constraint PRIMARY KEY to a column LABNO in the table.
(b) Delete the table LAB.
(a) ALTER TABLE LAB ADD PRIMARY KEY (LABNO);

mysql> DESC LAB;


+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| LABNO | char(4) | NO | PRI | NULL | |
| LAB_NAME | varchar(10) | YES | | NULL | |
| INCHARGE | varchar(9) | YES | | NULL | |
| CAPACITY | int | YES | | NULL | |
| FLOOR | varchar(3) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+

(b) DROP TABLE LAB;

27 Fill in the blank: SQP 1


______ command is used to remove primary key from a table in SQL. 2023
(a) update (b)remove (c) alter (d)drop
Ans: (c) alter
28 Which of the following commands will delete the table from MYSQL database? SQP 1
(a) DELETE TABLE (b) DROP TABLE (c) REMOVE TABLE (d) ALTER TABLE 2023
Ans: (b) DROP TABLE
29 Fill in the blank: SQP 1
_________ is a non-key attribute, whose values are derived from the primary key 2023
of some other table.
(a) Primary Key (b) Foreign Key (c) Candidate Key (d) Alternate Key
Ans: (b) Foreign Key
30 Fill in the blank: SQP 1
The SELECT statement when combined with __________ clause, returns records 2023
without repetition.
(a) DESCRIBE (b) UNIQUE (c) DISTINCT (d) NULL
Ans: (c) DISTINCT
31 Which function is used to display the total number of records from a table in a SQP 1
database? 2023
(a) sum(*) (b) total(*) (c) count(*) (d) return(*)
Ans: (c) count(*)
32 To establish a connection between Python and SQL database, connect() is SQP 1
used. Which of the following arguments may not necessarily be given while 2023
calling connect() ?
(a) host (b) database (c) user (d) password
Ans: (b) – database
33 Explain the use of ‘Foreign Key’ in a Relational Database Management System. SQP 2
Give example to support your answer. 2023
Ans.:
A foreign key is a non-key attribute, whose values are derived from the primary
key of some other table. A foreign key is used to set or represent a relationship
between two relations (or tables) in a database. Its value is derived from the
primary key attribute of another relation.

For example: In the tables TRAINER and COURSE given below, TID is primary key
in TRAINER table but foreign key in COURSE table.

Table: TRAINER

Table: COURSE

34 (a) Differentiate between COUNT() and COUNT(*) functions in SQL with SQP 2
appropriate example. 2023
Ans.: COUNT(*) returns the count of all rows in the table, whereas COUNT ()
is used with Column_Name passed as argument and counts the number of
non-NULL values in a column that is given as argument.

(b) Categorize the following commands as DDL or DML: SQP 2


INSERT, UPDATE, ALTER, DROP 2023
Ans.:
DDL- ALTER, DROP
DML – INSERT, UPDATE
35 (a) Consider the following tables – Bank_Account and Branch: SQP 1
2023
What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;

Ans.:

36 (b) Write the output of the queries (i) to (iv) based on the table, TECH_COURSE SQP 2
given below: 2023

(i) SELECT DISTINCT TID FROM TECH_COURSE;


Ans.:

(ii) SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE GROUP BY TID


HAVING COUNT(TID)>1;
Ans.:
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000 ORDER BY
CNAME;
Ans.:

(iv) SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 15000


AND 17000;
Ans.:
AVG(FEES)
15500.00
37 (a) Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher SQP 2
and Placement given below: 2023
Table: Teacher

(i) SELECT Department, avg(salary) FROM Teacher GROUP BY Department;


Ans.:

(ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM Teacher;


Ans.:

(iii) SELECT Name, Salary, T.Department, Place FROM Teacher T, Placement P


WHERE T.Department = P.Department AND Salary>20000;

Ans.:

(iv) SELECT Name, Place FROM Teacher T, Placement P WHERE Gender='F' and
T.Department=P.Department;

Ans.:

(b) Write the command to view all tables in a database. SQP 1


2023
Ans.:
SHOW TABLES;
38 (a) The code given below inserts the following record in the 3
table Student:
RollNo – integer
Name – string
Class – integer
Mark – 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.
• The details (RollNo, Name, Class and Mark) are to be
accepted from the user.
Write the following missing statements to complete the
code:
Statement 1 – to establish the mySQL connection
Statement 2 – to create the cursor object
Statement 3 – to execute the command that inserts the record in the table
Student.
Statement 4 - to add the record permanently in the
database

import mysql.connector as SQL


con=________________________________ # Statement 1
cur=________________________________ # Statement 2
RollNo=int(input('Enter the roll number: '))
Name=input('Enter name: ')
Class=int(input('Enter Class: '))
Mark=int(input("Enter Marks :: "))
#query="insert into student values
({},'{}',{},{})".format(RollNo,Name,Class,Mark)
# OR
query="insert into student values (%s, '%s', %s,
%s)"%(RollNo,Name,Class,Mark)
__________________ # Statement 3
________________________________ # Statement 4
print("Data Added successfully")
cur.execute("select * from student")
Records=cur.fetchall()
count=cur.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
con.close()
Ans.:
import mysql.connector as SQL
con=SQL.connect(host="localhost",user="root",

passwd='yadav',database='school') # Statement 1
cur=con.cursor() # Statement 2
RollNo=int(input('Enter the roll number: '))
Name=input('Enter name: ')
Class=int(input('Enter Class: '))
Mark=int(input("Enter Marks: "))
#query="insert into student values
({},'{}',{},{})".format(RollNo,Name,Class,Mark)
# OR
query="insert into student values (%s, '%s', %s,
%s)"%(RollNo,Name,Class,Mark)
cur.execute(query) # Statement 3
con.commit() # Statement 4
print("Data Added successfully")
cur.execute("select * from student")
Records=cur.fetchall()
count=cur.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
con.close()

38 (b) The code given below reads the following record from the table
named student and displays only those records who have marks
greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – 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.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students
whose marks are greater than 75.
Statement 3- to read the complete result of the query (records whose marks
are greater than 75) into the object named data, from the table student in
the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost", user="root", password="tiger",
database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
con1.close()
sql_data()
Ans.:
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root", passwd='yadav', database=
'school')
#con1=mysql.connect(host="localhost",user="root",password="tiger",
database="school")
mycursor=con1.cursor() # Statement 1
print("Students with marks greater than 75 are : ")
mycursor.execute('Select * from student where marks> 75 ' ) # Statement 2
data=mycursor.fetchall()
count=mycursor.rowcount # Statement 3
print("Total number of rows = : ", count)
for i in data:
print(i)
print()
con1.close()
sql_data()

mysql> select * from student;


+--------+---------+-------+-------+
| RollNo | St_Name | Class | marks |
+--------+---------+-------+-------+
| 1 | Manish | 12 | 50 |
| 2 | Abdul | 11 | 90 |
| 3 | Akash | 11 | 98 |
| 4 | Ajoy | 12 | 50 |
| 5 | Ram | 11 | 100 |
+--------+---------+-------+-------+
Output:
39 Navdeep creates a table RESULT with a set of records to maintain the marks SQP 2
secured by students in Sem 1, Sem2, Sem3 and their division. After creation of 2023
the table, he has entered data of 7 students in the table.

Table: RESULT

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key. 1
Ans.:
ROLL_NO

(ii) If two columns are added and 2 rows are deleted from the table result, what will 1
be the new degree and cardinality of the above table?
Ans.:
New Degree: 8
New Cardinality: 5
(iii) Write the statements to: 2
(a) Insert the following record into the table – Roll No- 108, NameAadit, Sem1-
470, Sem2-444, Sem3-475, Div – I.
(b) Increase the SEM2 marks of the students by 3% whose name begins with ‘N’
Ans.:
(a) INSERT INTO RESULT VALUES (108, ‘Aadit’, 470, 444, 475, ‘I’);
(b) UPDATE RESULT SET SEM2=SEM2+ (SEM2*0.03) WHERE SNAME LIKE “N%”;

OR (Option for Part iii only)


(iii) Write the statements to: 2
a. Delete the record of students securing IV division.
b. Add a column REMARKS in the table with datatype as varchar with 50
characters
Ans.:
a. DELETE FROM RESULT WHERE DIV=’IV’;
b. ALTER TABLE RESULT ADD (REMARKS VARCHAR(50));
OR
ALTER TABLE RESULT ADD COLUMN (REMARKS VARCHAR(50));

It works without () after ADD:


ALTER TABLE RESULT ADD REMARKS VARCHAR(50);
OR
ALTER TABLE RESULT ADD COLUMN REMARKS VARCHAR(50);
40 Differentiate between Degree and Cardinality in the context of Relational Data COMPT 2
Model. 2022
Ans.:
Degree : Number of columns in a table is called its Degree.
Cardinality : Number of rows in a table is called its Cardinality.

41 Consider the following table EMPLOYEE in a Database COMPANY: COMPT 2


2022
Table: EMPLOYEE

Assume that the required library for establishing the connection between
Python and MySQL is already imported in the given Python code.
Also assume that DB is the name of the database connection for the given
table EMPLOYEE stored in the database COMPANY.
Predict the output of the following Python code:

import mysql.connector as mysql


DB=mysql.connect(host="localhost",user="root", passwd='yadav',
database= 'COMPANY')
CUR = DB.cursor()
CUR.execute("USE COMPANY")
CUR.execute("SELECT * FROM EMPLOYEE WHERE DEPT = 'AC' ")
for i in range(2) :
R=CUR.fetchone()
print(R[0], R[1], sep ="#")

Ans.: 2
H1001#Avneet 1
A1003#Amina 1

42 Write the output of the SQL queries (a) to (d) based on the table TRAVEL given 2
below:

Table: TRAVEL

mysql> select * from travel;


+------+--------+-----------+------------+------+
| T_ID | START | END | T_DATE | FARE |
+------+--------+-----------+------------+------+
| 101 | DELHI | CHENNAI | 2021-12-25 | 4500 |
| 102 | DELHI | BENGALURU | 2021-11-20 | 4000 |
| 103 | MUMBAI | CHENNAI | 2020-12-10 | 5500 |
| 104 | DELHI | MUMBAI | 2019-12-20 | 4500 |
| 105 | MUMBAI | BENGALURU | 2022-01-15 | 5000 |
+------+--------+-----------+------------+------+

(a) SELECT START, END FROM TRAVEL WHERE FARE <=4000; ½

Ans.:
+-------+-----------+
| START | END |
+-------+-----------+
| DELHI | BENGALURU |
+-------+-----------+
(b) SELECT T_ID, FARE FROM TRAVEL WHERE T_DATE LIKE '2021-12-%' ; ½
Ans.:
+------+------+
| T_ID | FARE |
+------+------+
| 101 | 4500 |
+------+------+

(c) SELECT T_ID, T_DATE FROM TRAVEL WHERE END = 'CHENNAI' ORDER BY FARE ½
;

Ans.:
+------+------------+
| T_ID | T_DATE |
+------+------------+
| 101 | 2021-12-25 |
| 103 | 2020-12-10 |
+------+------------+
(d) SELECT START, MIN(FARE)FROM TRAVEL GROUP BY START ; ½

Ans.:
+--------+-----------+
| START | MIN(FARE) |
+--------+-----------+
| DELHI | 4000 |
| MUMBAI | 5000 |
+--------+-----------+
43 Write the output of the SQL queries (a) and (b) based on the following two tables 2022 2
FLIGHT and PASSENGER belonging to the same database: COMPT

Table: FLIGHT

Table: PASSENGER
mysql> use cbse2022compt;
Database changed

mysql> SELECT * FROM FLIGHT;


+------+--------+-----------+------+
| FNO | DEPART | ARRIVE | FARE |
+------+--------+-----------+------+
| F101 | DELHI | CHENNAI | 4500 |
| F102 | DELHI | BENGALURU | 4000 |
| F103 | MUMBAI | CHENNAI | 5500 |
| F104 | DELHI | MUMBAI | 4500 |
| F105 | MUMBAI | BENGALURU | 4500 |
+------+--------+-----------+------+

mysql> SELECT * FROM PASSENGER;


+------+---------+------------+------+
| PNO | NAME | FLIGHTDATE | FNO |
+------+---------+------------+------+
| P1 | PRAKASH | 2021-12-25 | F101 |
| P2 | NOOR | 2021-11-20 | F103 |
| P3 | HARMEET | 2020-12-10 | NULL |
| P4 | ANNIE | 2019-12-20 | F105 |
+------+---------+------------+------+

(A) SELECT NAME, DEPART FROM FLIGHT NATURAL JOIN PASSENGER ; 1


Ans.:
+---------+--------+
| NAME | DEPART |
+---------+--------+
| PRAKASH | DELHI |
| NOOR | MUMBAI |
| ANNIE | MUMBAI |
+---------+--------+

(b) SELECT NAME, FARE FROM PASSENGER P, FLIGHT F WHERE F.FNO = P.FNO 1
AND F.DEPART = 'MUMBAI' ;
Ans.:
+-------+------+
| NAME | FARE |
+-------+------+
| NOOR | 5500 |
| ANNIE | 4500 |
+-------+------+

44 Explain Primary Key in the context of Relational Database Model. Support your 2022 2
answer with suitable example. COMPT
Ans.:
An attribute or a group of attributes that identifies a tuple uniquely is known as a
Primary Key of the table.

Example:
Table: BANK

Primary Key: ACNO

OR

Consider the following table BATSMEN: 2022 2


COMPT
Table: BATSMEN
(a) Identify and write the name of the Candidate Keys in the given table BATSMEN.
Ans.:
PNO, NAME
(b) How many tuples are there in the given table BATSMEN?
Ans.:
5
45 (a) A SQL table BOOKS contains the following column names: 2022 1
BOOKNO,BOOKNAME, QUANTITY, PRICE, AUTHOR COMPT
Write the SQL statement to add a new column REVIEW to store the reviews of
the book.

Ans.:
ALTER TABLE BOOKS ADD REVIEW VARCHAR(20) ;
OR
ALTER TABLE BOOKS ADD COLUMN REVIEW VARCHAR(20) ;

(b) Write the names of any two commands of DDL and any two commands of DML 2022 2
in SQL. COMPT
Ans.:
DDL Commands : CREATE, DROP, ALTER (any two)
DML Commands : INSERT, DELETE, UPDATE etc. (any two)

46 Rashmi has forgotten the names of the databases, tables and the structure of 2022 2
the tables that she had created in Relational Database Management System COMPT
(RDBMS) on her computer.
(a) Write the SQL statement to display the names of all the databases present in
RDBMS application on her computer.
Ans.:
SHOW DATABASES ;
(b) Write the statement which she should execute to open the database named
"STOCK".
Ans.:
USE STOCK;
(c) Write the statement which she should execute to display the structure of the
table "ITEMS" existing in the above opened database "STOCK".

Ans.:
DESCRIBE ITEMS;
OR
DESC ITEMS;
47 Write SQL queries for (a) to (d) based on the tables CUSTOMER and TRANSACT 2022 4
given below: COMPT
Table : CUSTOMER
+------+--------+--------+--------------------+------------+
| CNO | NAME | GENDER | ADDRESS | PHONE |
+------+--------+--------+--------------------+------------+
| 1001 | Suresh | Male | A-123, West Street | 9310010010 |
| 1002 | Anita | Female | C-24, Court Lane | 9988117700 |
| 1003 | Harjas | Male | T-1, Woods Avenue | 8920021001 |
+------+--------+--------+--------------------+------------+

Table : TRANSACT
+------+------+--------+--------+------------+
| TNO | CNO | Amount | TTYPE | TDATE |
+------+------+--------+--------+------------+
| T1 | 1002 | 2000 | DEBIT | 2021-09-25 |
| T2 | 1003 | 1500 | CREDIT | 2022-01-28 |
| T3 | 1002 | 3500 | CREDIT | 2021-12-31 |
| T4 | 1001 | 1000 | DEBIT | 2022-01-10 |
+------+------+--------+--------+------------+

(a) Write the SQL statements to delete the records from table TRANSACT whose
amount is less than 1000.
Ans.:
DELETE FROM TRANSACT WHERE AMOUNT<1000;
(b) Write a query to display the total AMOUNT of all DEBITs and all CREDITs.
Ans.:
SELECT TTYPE, SUM(AMOUNT)FROM TRANSACT GROUP BY TTYPE;

(c) Write a query to display the NAME and corresponding AMOUNT of all
CUSTOMERs who made a transaction type (TTYPE) of CREDIT.
Ans.:
SELECT NAME, AMOUNT FROM CUSTOMER, TRANSACT WHERE
CUSTOMER.CNO=TRANSACT.CNO AND TTYPE='CREDIT';
OR
SELECT NAME, AMOUNT FROM CUSTOMER C, TRANSACT T WHERE
C.CNO=T.CNO AND TTYPE='CREDIT';
OR
SELECT NAME, AMOUNT FROM CUSTOMER NATURAL JOIN TRANSACT
WHERE TTYPE='CREDIT';
(d) Write the SQL statement to change the Phone number of customer whose CNO
is 1002 to 9988117700 in the table CUSTOMER.
Ans.:
UPDATE CUSTOMER SET PHONE=9988117700 WHERE CNO=1002;

You might also like