Database Management Q and A
Database Management Q and A
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');
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:
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> 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)
Table: Projects
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)
(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)
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
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)
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
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:
Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd='yadav',database='travel')
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’);
Table: Sport
Ans.:
Creating Database CBSE2023Compt and creating tables
Student and Sport and inserting records:
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.
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)
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.
Ans.:
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.
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?
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.
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.
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)
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
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:
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.
(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';
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.
Ans.:
36 (b) Write the output of the queries (i) to (iv) based on the table, TECH_COURSE SQP 2
given below: 2023
Ans.:
(iv) SELECT Name, Place FROM Teacher T, Placement P WHERE Gender='F' and
T.Department=P.Department;
Ans.:
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.
Table: RESULT
(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%”;
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:
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
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
(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
OR
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;