SQL Concepts for Relational Databases
SQL Concepts for Relational Databases
1
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
2
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
11 Mr. Atharva is given a task to create a database, Admin. He has to create a table, 2
users in the database with the following columns:
User_id – int
User_name – varchar(20)
Password – varchar(10)
Help him by writing SQL queries for both tasks.
3
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Answers
2. Differentiate between DROP and DELETE query in SQL with a suitable example.
• DELETE: Deletes records (rows) from a table but keeps the structure.
DELETE FROM student WHERE id=101;
3. What constraint should be applied on a table column so that duplicate values are not
allowed in that column, but NULL is allowed.
Answer: UNIQUE
4. What constraint should be applied on a table column so that NULL is not allowed in
that column, but duplicate values are allowed.
Answer: NOT NULL
5. Write an SQL command to remove the Primary Key constraint from a table, named
MOBILE. M_ID is the primary key of the table.
ALTER TABLE MOBILE DROP PRIMARY KEY;
6. Write an SQL command to make the column M_ID the Primary Key of an already
existing table, named MOBILE.
ALTER TABLE MOBILE ADD PRIMARY KEY (M_ID);
Insert record:
INSERT INTO Employee (EmpId, Ename, Department, Salary)
VALUES (999, 'Shweta', 'Production', 26900);
4
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Insert record:
INSERT INTO Sports (Game_id, P_Age, G_name, Category)
VALUES ('G42', 'Above 18', 'Chess', 'Senior');
Create table:
CREATE TABLE users (
User_id INT,
User_name VARCHAR(20),
Password VARCHAR(10)
);
5
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
I. To display the total quantity sold for each product whose total quantity sold
exceeds 12.
SELECT *
FROM SALES
ORDER BY product DESC;
III. To display the distinct Product names from the SALES table.
IV. To display the records of customers whose names end with the letter 'e'.
SELECT *
FROM SALES
WHERE customer_name LIKE '%e';
6
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Table: Hotels
7
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Table: Bookings
B_ID H_ID Customer_Name Check_In Check_Out
1 1 Jiya 2024-12-01 2024-12-05
2 2 Priya 2024-12-03 2024-12-07
3 3 Alicia 2024-12-01 2024-12-06
4 4 Bhavik 2024-12-02 2024-12-03
5 5 Charu 2024-12-01 2024-12-02
6 6 Esha 2024-12-04 2024-12-08
7 6 Dia 2024-12-02 2024-12-06
8 4 Sonia 2024-12-04 2024-12-08
B. To display the customer’s name along with their booked hotel’s name.
II. To display the booking details for customers who have booked hotels in
'Mumbai', 'Chennai', or 'Kolkata'.
SELECT B.*
FROM Bookings B
JOIN Hotels H ON B.H_ID = H.H_ID
WHERE [Link] IN ('Mumbai', 'Chennai', 'Kolkata');
Expected Output:
B_ID H_ID Customer_Name Check_In Check_Out
2 2 Priya 2024-12-03 2024-12-07
5 5 Charu 2024-12-01 2024-12-02
6 6 Esha 2024-12-04 2024-12-08
7 6 Dia 2024-12-02 2024-12-06
8
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
III. To delete all bookings where the check-in date is before 2024-12-03.
DELETE FROM Bookings
WHERE Check_In < '2024-12-03';
(This will delete bookings of Jiya, Alicia, Bhavik, Charu, and Dia.)
A) Queries
I.
II.
9
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
FROM Orders
ORDER BY Total_Price DESC;
III.
IV.
OR
B) Write the output
I. Select c_name, sum(quantity) as total_quantity from orders group by
c_name;
II. Select * from orders where product like '%phone%';
III. Select o_id, c_name, product, quantity, price from orders where price
between 1500 and 12000;
IV. Select max(price) from orders;
B) Outputs
I.
C_Name total_quantity
Jitendra 1
Mustafa 2
Dhwani 1
II.
O_Id C_Name Product Quantity Price
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
III.
O_Id C_Name Product Quantity Price
1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
IV.
12000
5 Saman has been entrusted with the management of Law University Database. He
needs to access some information from FACULTY and COURSES tables for a
survey analysis. Help him extract the following information by writing the desired
SQL queries as mentioned below.
10
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Table: FACULTY
F_ID FName LName Hire_Date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
Table: COURSES
I. To display complete details (from both the tables) of those Faculties whose
salary is less than 12000.
II. To display the details of courses whose fees is in the range of 20000 to
50000 (both values included).
III. To increase the fees of all courses by 500 which have "Computer" in their
Course names.
VI. (A)To display names (FName and LName) of faculty taking System
Design.
OR
(B) To display the Cartesian Product of these two tables.
I. To display complete details (from both the tables) of those Faculties whose
salary is less than 12000.
II. To display the details of courses whose fees is in the range of 20000 to
50000 (both values included).
SELECT *
FROM COURSES
WHERE Fees BETWEEN 20000 AND 50000;
III. To increase the fees of all courses by 500 which have "Computer" in their
Course names.
UPDATE COURSES
SET Fees = Fees + 500
11
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
OR
SELECT *
FROM FACULTY, COURSES;
I. To display the names and wages of those workers whose wages are between
800 and 1500.
SELECT *
FROM WORKER
WHERE SITEID IS NULL;
12
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
III. To display WNAME, WAGE and HOURS of all those workers whose
TYPE is 'Skilled'.
IV. To change the WAGE to 1200 of the workers where the TYPE is
"Semiskilled".
UPDATE WORKER
SET WAGE = 1200
WHERE TYPE = 'Semiskilled';
I.
WNAME WAGE*HOURS
Ahmed J 300000
Anju S 156000
II.
COUNT(DISTINCT TYPE)
3
III.
MAX(WAGE) MIN(WAGE) TYPE
1500 780 Unskilled
13
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
IV.
WNAME SITEID
Jacob B 101
Ahmed J 103
Table : Articles
Code A_Code Article DOC Price
PL001 A0001 Painting 2018-10-19 20000
SC028 A0004 Sculpture 2021-01-15 16000
QL005 A0003 Quilling 2024-04-24 3000
Table : Artists
A_Code Name Phone Email DOB
A0001 Roy 595923 r@[Link] 1986-10-12
A0002 Ghosh 1122334 ghosh@[Link] 1972-02-05
A0003 Gargi 121212 Gargi@[Link] 1996-03-22
A0004 Mustafa 3333333 M@[Link] 2000-01-01
Note: The tables contain many more records than shown here.
DOC is Date of Creation of an Article.
As an employee of CAG, you are required to write the SQL queries for the
following:
I. To display all the records from the Articles table in
descending order of price.
II. To display the details of Articles which were created in the year
2020.
III. To display the structure of Artists table.
IV. (a)To display the name of all artists whose Article is Painting
through qui Join.
OR
(b) To display the name of all Artists whose Article is 'Painting'
through Natural Join.
14
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
I. To display all the records from the Articles table in descending order of
price.
II. To display the details of Articles which were created in the year 2020.
DESC Artists;
IV. (a) To display the name of all artists whose Article is Painting through
equi join.
OR
IV. (b) To display the name of all Artists whose Article is 'Painting' through
Natural Join.
9 Consider the table CLUB given below and write the output of the SQL queries that 3
follow.
Table : CLUB
CID CNAME AGE GENDER SPORTS PAY DOAPP
5246 AMRITA 35 FEMALE CHESS 900 2006-03-27
4687 SHYAM 37 MALE CRICKET 1300 2004-04-15
1245 MEENA 23 FEMALE VOLLEYBALL 1000 2007-06-18
1622 AMRIT 28 MALE KARATE 1000 2007-09-05
1256 AMINA 36 FEMALE CHESS 1100 2003-08-15
1720 MANJU 33 FEMALE KARATE 1250 2004-04-10
2321 VIRAT 35 MALE CRICKET 1050 2005-04-30
15
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Answer:
I. Output:
4
II. Output:
CNAME SPORTS
AMINA CHESS
III. Output:
CNAME AGE PAY
AMRIT 28 1000
VIRAT 35 1050
Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of personals whose allowance is known.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all
personals. The column heading ‘Total Salary’ should also be displayed.
(iii) Delete the record of personals who have salary greater than 25000
Answer:
(i) UPDATE Personal SET Salary = Salary + (Salary * 0.05)
WHERE Allowance IS NOT NULL;
(ii) SELECT Name, (Salary + Allowance) AS "Total Salary" FROM Personal;
(iii) DELETE FROM Personal WHERE Salary > 25000;
Table: BRAND
16
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
Answer:
(i) Display product name and brand name from the tables PRODUCT and BRAND
SELECT PName, BName FROM PRODUCT
INNER JOIN BRAND ON [Link] = [Link];
(ii) Display the structure of the table PRODUCT
DESCRIBE PRODUCT;
(iii) Display the average rating of Medimix and Dove brands
SELECT BName, AVG(Rating) AS Avg_Rating
FROM PRODUCT
INNER JOIN BRAND
ON [Link] = [Link]
WHERE BName IN ('Medimix', 'Dove')
GROUP BY BName;
(iv) Display the name, price, and rating of products in descending order of rating
SELECT PName, UPrice, Rating
FROM PRODUCT
ORDER BY Rating DESC;
17
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
12 Consider the table ORDERS given below and write the output of the SQL 3
queries that follow :
II. Output:
ITEM QTY
RICE 25
WHEAT 28
III. Output:
ORDNO ORDATE
1004 2023-12-25
1007 2024-04-30
18
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
13 3
Answer:
(i) Add the constraint, primary key to column P_id in the existing table Projects.
ALTER TABLE Projects ADD PRIMARY KEY (P_id);
(ii) To change the language to Python of the project whose id is P002.
UPDATE Projects SET Language = 'Python' WHERE P_id = 'P002';
(iii) To delete the table Projects from MySQL database along with its data.
DROP TABLE Projects;
14 4
19
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Answer:
(i) Display the student name and their stop name from the tables Admin and
Transport.
SELECT Admin.S_name, Transport.Stop_name
FROM Admin
INNER JOIN Transport
ON Admin.S_id = Transport.S_id;
(iii) Display all details of the students whose name starts with 'V'.
SELECT *
FROM Admin
WHERE S_name LIKE 'V%';
(iv) Display student id and address in alphabetical order of student name, from the
table Admin.
SELECT S_id, Address
FROM Admin
ORDER BY S_name ASC;
20
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
15 5
Answer:
Example:
If table A has 2 rows and table B has 3 rows, then A × B will have 6 rows.
import [Link]
# Establish connection
mydb = [Link](
host="localhost",
user="admin",
password="Shopping",
database="Keeper"
)
# Update query
update_query = "UPDATE shop SET Qty = 20 WHERE Item_code = 111"
try:
[Link](update_query)
[Link]() # Save changes
21
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
# Close connection
[Link]()
[Link]()
Explanation:
16
5
Answer:
(ii) Python code to display all the details of passengers from the table flight:
import [Link]
22
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
# Establish connection
con = [Link](
host="localhost",
user="root",
password="airplane",
database="Travel"
)
cur = [Link]()
# Execute query
[Link]("SELECT * FROM flight")
# Close connection
[Link]()
This code connects Python with the MySQL database Travel, retrieves all records
from the table flight, and prints them.
17 Consider the table Stationery given below and write the output of the 3
SQL queries that follow.
Table : Stationery
23
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
(b) Output:
ITEMNO ITEM
402 Gel Pen Premium
406 Gel Pen Classic
(c) Output:
ITEM AMOUNT
Gel Pen Premium 3000
Based on the given table, write SQL queries for the following:
Answer:
17 4
Consider the tables GAMES and PLAYERS given below
Table: GAMES
24
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Table: PLAYERS
PCode Name GCode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
Write SQL queries for the following:
(i) Display the game type and average number of games played in each
type.
(ii) Display prize money, name of the game, and name of the players from
the tables Games and Players.
(iii) Display the types of games without repetition.
(iv) Display the name of the game and prize money of those games whose
prize money is known.
Answer:
(i) Display the game type and average number of games played in each type.
SELECT Type, AVG(Number) AS AvgPlayers
FROM Games GROUP BY Type;
(ii) Display prize money, name of the game, and name of the players from the
tables Games and Players.
(We need to join both tables using GCode)
SELECT [Link], [Link], [Link]
FROM Games G
INNER JOIN Players P
ON [Link] = [Link];
(iv) Display the name of the game and prize money of those games whose prize
money is known.
SELECT GameName, PrizeMoney
FROM Games
WHERE PrizeMoney IS NOT NULL;
25
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Write a Python program to change the Quantity of the product to 91 whose Item_code is
208 in the product_inventory table.
def update_quantity():
try:
# Establish connection
mydb = [Link](
host="localhost",
user="admin_user",
password="warehouse2024",
database="WarehouseDB"
)
# Execute query
[Link](update_query, values)
# Commit changes
[Link]()
finally:
if mydb.is_connected():
[Link]()
[Link]()
26
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Explanation:
• [Link]() establishes the connection using given
credentials.
• UPDATE query changes the Quantity to 91 where Item_code = 208.
• commit() saves the changes to the database.
• try-except-finally ensures error handling and proper closing of the
connection.
Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)
Assume the following for Python-Database connectivity: Host: localhost, User: root,
Password: Pencil
import [Link]
def AddAndDisplay():
try:
# Establish connection
mydb = [Link](
host="localhost",
user="root",
password="Pencil",
database="ITEMDB"
)
mycursor = [Link]()
27
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
finally:
if mydb.is_connected():
[Link]()
[Link]()
Explanation:
Here’s the Python function Delete_Theatre() that will take Th_ID from the user and
delete the record from the THEATRE table in CINEMA database:
import [Link]
def Delete_Theatre():
try:
# Establish connection
28
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
mydb = [Link](
host="localhost",
user="root",
password="Ex2025",
database="CINEMA"
)
mycursor = [Link]()
# Input Theatre ID
th_id = input("Enter Theatre ID (Th_ID) to delete: ")
# Delete query
delete_query = "DELETE FROM THEATRE WHERE Th_ID = %s"
[Link](delete_query, (th_id,))
[Link]()
finally:
if mydb.is_connected():
[Link]()
[Link]()
Explanation
29
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
· Host – localhost
Help Sangeeta to write the program in Python for the above
mentioned task.
Example:
If we have a table STUDENTS(StudentID, Name, DeptID) and another table
DEPARTMENTS(DeptID, DeptName), then DeptID in STUDENTS can be declared as a
foreign key referencing DeptID in DEPARTMENTS.
import [Link]
def delete_candidate():
try:
# Establish connection
mydb = [Link](
host="localhost",
user="root",
password="job",
database="Agency"
)
mycursor = [Link]()
# Candidate to delete
cname = "Raman"
# Delete query
query = "DELETE FROM Placement WHERE CName = %s"
[Link](query, (cname,))
[Link]()
finally:
if mydb.is_connected():
[Link]()
[Link]()
30
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
delete_candidate()
Explanation of Code:
One-line answer:
CHAR is fixed-length, while VARCHAR is variable-length.
import [Link]
# Establish connection
conn = [Link](
host="localhost",
user="admin",
31
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
password="root",
database="Bank"
)
Explanation:
1 5
(i) Define the term Domain with respect to RDBMS. Give one example to support
your answer.
(ii) 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
• DOB (Date of birth) – Date
• Fee – float
32
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
• 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.
Definition:
A domain is the set of permissible values that a column (attribute) in a table can
hold in a relational database. It defines the type, range, and format of data that can
be stored in a column.
Example:
• Column Fee in table Student may have a domain of FLOAT with values
greater than 0.
• Column DOB may have a domain of DATE.
One-line answer:
A domain restricts the type of values that can be stored in a column. For example,
rno can only accept integer values.
import [Link]
# Establish connection
conn = [Link](
host="localhost",
user="root",
password="tiger",
database="SCHOOL"
)
33
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
Explanation:
5
(i) Give one difference between alternate key and candidate key.
(ii) 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
One-line answer:
An alternate key is a candidate key that is not selected as the primary key.
import [Link]
# Establish connection
conn = [Link](
host="localhost",
user="root",
34
Class XII Subject: Computer Science Topic: Relational Database and SQL Marks:20
password="tiger",
database="SCHOOL"
)
Explanation:
35