Practical File
Practical File
DWARKA
COMPUTER SCIENCE
PRACTICAL FILE
SESSION:2025-26
SUBMITTED BY:
ROLL_NO:42
CERTIFICATE
Q2 Creating a Function to explain the use of Global and Local variables in function
Q10 Creating a python program to copy particular lines of a text file into another text file
Q11 Creating a python program to create and search records in binary file
Q12 Creating a python program to create and update/modify records in binary file
Q13 Creating a python program to create and search employee’s record in csv file
OUTPUT:
MENU
[Link]
[Link]
[Link]
enter number: 1
enter first number110
enter second number25
135.0
MENU
[Link]
[Link]
[Link]
enter number: 2
enter first number 15
enter second number10
5.0
Q2: Create a python function to explain the use of global and local variables in function:
CODE:
x=10
def f():
y=5
global x
print('inside function')
print(f'global variable x:{x}')
print(f'global variable y:{y}')
x=x+15
f()
print(f'modified variable inside function x:{x}')
OUTPUT:
inside function:
global variable x:10
global variable y:5
modified variable inside function x:25
CODE:
l=[]
def f1():
global l
try:
element=input('enter element to add in the list')
[Link](element)
print(f'element:{element} added in list')
except:
print('element not added!')
def f2():
global l
try:
element=input('enter element to remove')
while True:
[Link](element)
if element not in l:
break
print(f'all occurences of element:{element} is removed')
except:
print('element not removed!')
def f3():
global l
print(l)
def f4():
global l
try:
element=input('enter element u want to find')
if element in l:
print(f'{element} is present in list')
except:
print(f'{element} not in list!')
def f5():
global l
print(f'length of list is {len(l)}')
while True:
print('\n\tMENU')
print('\n\[Link]')
print('\n\[Link] an element to the list')
print('\n\[Link] an element to the list')
print('\n\[Link] the list')
print('\n\[Link] for an element in list')
print('\n\[Link] the length of the list')
a=int(input('enter num'))
if a not in (1,2,3,4,5):
print('\n\t***THE END***')
break
if a==1:
f1()
if a==2:
f2()
if a==3:
f3()
if a==4:
f4()
if a==5:
f5()
OUTPUT:
MENU
[Link]
enter num1
enter element to add in the list hello
element: hello added in list
MENU
[Link]
CODE:
t = ()
def add_tuple():
global t
element = input("Enter element to add to the tuple: ")
t += (element,)
print(f"Element '{element}' added.")
def remove_tuple():
global t
element = input("Enter element to remove: ")
if element in t:
t = tuple(x for x in t if x != element)
print(f"All occurrences of '{element}' have been removed.")
else:
print(f"'{element}' not found in the tuple.")
def display_tuple():
print("Current tuple:", t)
def search_tuple():
element = input("Enter element to search for: ")
for i in range(len(t)):
if t[i] == element:
print(f"'{element}' found at index {i}")
return
print(f"'{element}' not found.")
def length_tuple():
print(f"Length of tuple is: {len(t)}")
while True:
print("\n========= MENU =========")
print("0. Exit")
print("1. Add an element")
print("2. Remove an element")
print("3. Display the tuple")
print("4. Search for an element")
print("5. Get tuple length")
try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == 0:
print("*** THE END ***")
break
elif choice == 1:
add_tuple()
elif choice == 2:
remove_tuple()
elif choice == 3:
display_tuple()
elif choice == 4:
search_tuple()
elif choice == 5:
length_tuple()
else:
print("Invalid choice. Try again.")
OUTPUT:
CODE:
d = {}
def add_key_value():
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value
print(f"'{key}': '{value}' added to dictionary.")
def remove_key():
key = input("Enter key to remove: ")
if key in d:
del d[key]
print(f"Key '{key}' removed.")
else:
print(f"Key '{key}' not found.")
def display_dictionary():
print("Current dictionary:")
for key, value in [Link]():
print(f"{key}: {value}")
def search_key():
key = input("Enter key to search: ")
if key in d:
print(f"Found '{key}' with value '{d[key]}'")
else:
print(f"Key '{key}' not found.")
def dictionary_size():
print(f"Dictionary has {len(d)} entries.")
while True:
print("\n========= MENU =========")
print("0. Exit")
print("1. Add a key-value pair")
print("2. Remove a key")
print("3. Display dictionary")
print("4. Search for a key")
print("5. Dictionary size")
try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Enter a valid number.")
continue
if choice == 0:
print("*** THE END ***")
break
elif choice == 1:
add_key_value()
elif choice == 2:
remove_key()
elif choice == 3:
display_dictionary()
elif choice == 4:
search_key()
elif choice == 5:
dictionary_size()
else:
print("Invalid choice.")
OUTPUT:
CODE:
def arithmetic_operators(a, b):
print("\nArithmetic Operators:")
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b if b != 0 else 'undefined'}")
print(f"{a} % {b} = {a % b if b != 0 else 'undefined'}")
print(f"{a} ** {b} = {a ** b}")
print(f"{a} // {b} = {a // b if b != 0 else 'undefined'}")
def assignment_operators():
print("\nAssignment Operators:")
x = 5
print(f"x = {x}")
x += 3; print(f"x += 3 -> {x}")
x -= 2; print(f"x -= 2 -> {x}")
x *= 4; print(f"x *= 4 -> {x}")
x /= 2; print(f"x /= 2 -> {x}")
x %= 3; print(f"x %= 3 -> {x}")
while True:
print("\n========= OPERATOR MENU =========")
print("0. Exit")
print("1. Arithmetic Operators")
print("2. Comparison Operators")
print("3. Logical Operators")
print("4. Assignment Operators")
print("5. Bitwise Operators")
try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Please enter a number.")
continue
if choice == 0:
print("*** THE END ***")
break
if choice == 1:
arithmetic_operators(a, b)
elif choice == 2:
comparison_operators(a, b)
elif choice == 3:
logical_operators(a, b)
elif choice == 4:
assignment_operators()
elif choice == 5:
bitwise_operators(a, b)
else:
print("Invalid choice.")
OUTPUT:
========= OPERATOR MENU =========
0. Exit
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
Enter your choice: 1
Enter first number: 40
Enter second number: 27
Arithmetic Operators:
40 + 27 = 67
40 - 27 = 13
40 * 27 = 1080
40 / 27 = 1.4814814814814814
40 % 27 = 13
40 ** 27 = 18014398509481984000000000000000000000000000
40 // 27 = 1
Comparison Operators:
40 == 27 -> False
40 != 27 -> True
40 > 27 -> True
40 < 27 -> False
40 >= 27 -> True
40 <= 27 -> False
Q7: Create a python program to generate random numbers:
CODE:
import random
def generate_random_number():
while True:
try:
lower = int(input("Enter the lower bound: "))
upper = int(input("Enter the upper bound: "))
if lower > upper:
print("Lower bound must be less than or equal to
upper bound.")
else:
number = [Link](lower, upper)
print(f" Your random number between {lower} and
{upper} is: {number}")
break
except ValueError:
print("Please enter valid whole numbers.")
generate_random_number()
OUTPUT:
Enter the lower bound: 1
CODE:
print('function to read a text_file line by line:\n\t')
def read_file_linewise():
try:
f = open('[Link]', 'r')
while True:
s=[Link]()
print(s,end='')
if len(s)==0:
break
[Link]()
except:
print('error!')
read_file_linewise()
FILE:
OUTPUT:
function to read a text_file line by line:
Hello!
My name is Upraj
Q9: Create a python program to read a text file word by word:
CODE:
print('function to read a text_file word by word:\n\t')
def read_file_wordwise():
try:
f = open('[Link]', 'r')
s=[Link]()
l=[Link]()
for i in l:
print(i)
[Link]()
except:
print('error!')
read_file_wordwise()
FILE:
OUTPUT:
function to read a text_file word by word:
Hello!
My
name
is
Upraj.
Q10: Creating a python program to copy particular lines of a text file into another text file:
CODE:
try:
src = open(source_file, 'r')
tgt = open(target_file, 'w')
matched = False
for line in src:
for rollno in rollnos:
if rollno in line:
[Link](line)
matched = True
break
if matched:
print(f"Lines with roll numbers {rollnos} copied to
'{target_file}'.")
else:
print("No matching lines found for the given roll
numbers.")
[Link]()
[Link]()
except:
print("Error")
rollno_list = []
print("Enter roll numbers one by one. Type 'done' to finish:")
while True:
roll = input("Enter roll number: ")
if [Link]() == 'done':
break
rollno_list.append([Link]())
source_path = "[Link]"
target_path = "matched_rollno.txt"
OUTPUT:
CODE:
import pickle
def add_record(filename):
try:
f = open(filename, 'ab')
roll = input("Enter Roll Number: ")
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
record = {'roll': roll, 'name': name, 'marks': marks}
[Link](record, f)
[Link]()
print("Record added successfully.\n")
except:
print("Error")
def search_record(filename):
try:
f = open(filename, 'rb')
roll_to_search = input("Enter Roll Number to search: ")
found = False
while True:
try:
record = [Link](f)
if record['roll'] == roll_to_search:
print("Record Found:")
print(f"Roll No: {record['roll']}, Name:
{record['name']}, Marks: {record['marks']}\n")
found = True
break
except EOFError:
break
[Link]()
if not found:
print("Record not found.\n")
except:
print("Error")
def menu():
filename = "student_records.dat"
while True:
print("===== Student Record Menu =====")
print("1. Add Record")
print("2. Search Record")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
add_record(filename)
else:
print("Invalid choice. Please try again.\n")
menu()
OUTPUT:
===== Student Record Menu =====
1. Add Record
2. Search Record
3. Exit
Enter your choice (1-3): 1
Enter Roll Number: 1
Enter Name: Upraj
Enter Marks: 94
Record added successfully.
def modify_record(filename):
try:
records = []
found = False
for i in range(len(records)):
if records[i]['roll'] == roll_to_modify:
print("Current Record:")
print(f"Roll No: {records[i]['roll']}, Name:
{records[i]['name']}, Percentage: {records[i]['percentage']}")
records[i]['name'] = input("Enter New Name: ")
records[i]['percentage'] = float(input("Enter New
Percentage: "))
found = True
break
if found:
with open(filename, 'wb') as f:
for rec in records:
[Link](rec, f)
print("Record modified successfully.\n")
else:
print("Record not found.\n")
except:
print("Error:")
def menu():
filename = "student_records.dat"
while True:
print("===== Student Record Menu =====")
print("1. Add Record")
print("2. Modify Record")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
add_record(filename)
elif choice == '2':
modify_record(filename)
elif choice == '3':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.\n")
menu()
OUTPUT:
CODE:
import csv
def add_employee(filename):
try:
f = open(filename, 'a', newline='')
writer = [Link](f)
emp_id = input("Enter Employee ID: ")
name = input("Enter Name: ")
department = input("Enter Department: ")
salary = float(input("Enter Salary: "))
[Link]([emp_id, name, department, salary])
[Link]()
print("Employee record added successfully.\n")
except :
print("Error")
def search_employee(filename):
try:
emp_id_to_search = input("Enter Employee ID to search: ")
found = False
f = open(filename, 'r')
reader = [Link](f)
for row in reader:
if row and row[0] == emp_id_to_search:
print("Employee Found:")
print(f"ID: {row[0]}, Name: {row[1]}, Department:
{row[2]}, Salary: {row[3]}\n")
found = True
break
[Link]()
if not found:
print("Employee not found.\n")
except :
print("Error")
def menu():
filename = "employee_records.csv"
while True:
print("===== Employee Record Menu =====")
print("1. Add Employee")
print("2. Search Employee")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
add_employee(filename)
else:
print("Invalid choice. Please try again.\n")
menu()
OUTPUT:
===== Employee Record Menu =====
1. Add Employee
2. Search Employee
3. Exit
1. Add Employee
2. Search Employee
3. Exit
Enter your choice (1-3): 2
Enter Employee ID to search: 1
Employee Found:
ID: 1, Name: Upraj, Department: 10, Salary: 10000.0
1. Add Employee
2. Search Employee
3. Exit
CODE:
stack = []
top = -1
def push():
global top
item = input("Enter item to push: ")
[Link](item)
top += 1
print(f"'{item}' pushed. Top is now at index {top}.")
def pop():
global top
if top == -1:
print("Stack Underflow")
else:
item = [Link]()
print(f"'{item}' popped. Top was at index {top}.")
top -= 1
def peek():
if top == -1:
print("Stack is empty. No top element.")
else:
print(f"Top element is: {stack[top]}")
def display():
if top == -1:
print("Stack is empty.")
else:
print("Stack contents from bottom to top:")
for i in range(top + 1):
print(f"Index {i}: {stack[i]}")
def menu():
while True:
print("\n--- Stack Operations Menu ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to
5.")
menu()
OUTPUT:
--- Stack Operations Menu ---
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 1
Enter item to push: 3
'3' pushed. Top is now at index 2.
CODE:
stack = {}
top = -1
def push():
global top
item = input("Enter item to push: ")
top += 1
stack[top] = item
print(f"'{item}' pushed at position {top}.")
def pop():
global top
if top == -1:
print("Stack Underflow! Cannot pop from empty stack.")
else:
item = [Link](top)
print(f"'{item}' popped from position {top}.")
top -= 1
def peek():
if top == -1:
print("Stack is empty. No top element.")
else:
print(f"Top element is: {stack[top]}")
def display():
if top == -1:
print("Stack is empty.")
else:
print("Stack contents from bottom to top:")
for i in range(top + 1):
print(f"Position {i}: {stack[i]}")
def menu():
while True:
print("\n--- Stack Operations Menu (Dictionary) ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to
5.")
menu()
OUTPUT:
CODE:
import pymysql as x
def create_table():
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q='create table stu(rollno int primary key,name
varchar(20),maths int,eng int,cs int);'
[Link](q)
[Link]()
[Link]()
[Link]()
print('table stu created')
except:
print('table stu already created')
def insert_record(b, c, g, e, f):
try:
d = [Link](host='localhost', user='root', passwd='usb',
db='xii')
cur = [Link]()
query = "INSERT INTO stu (rollno, name, maths, eng, cs)
VALUES (%s, %s, %s, %s, %s)"
[Link](query, (b, c, g, e, f))
[Link]()
[Link]()
[Link]()
print("Record added successfully!")
except :
print(f"Error ")
def display_table():
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q='select*from stu;'
[Link](q)
r=[Link]()
for i in r:
print(i)
[Link]
[Link]
except:
print('error')
def delete_record(h,i):
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q = f'delete from stu WHERE {h} = %s'
[Link](q, (i,))
[Link]()
[Link]()
[Link]()
print(f'row deleted where {h} is {i}')
except:
print('ERROR')
def update_record(j,k,l,m):
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q = f'update stu set {j}=%s where {l}=%s'
[Link](q, (k, m))
[Link]()
[Link]()
[Link]()
except:
print('ERROR')
def search_Record(n,o):
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q=f'select*from stu where {n}=%s;'
[Link](q, (o,))
r=[Link]()
for i in r:
print(i)
[Link]
[Link]
except:
print('error')
def sort_table(y,z):
try:
z=[Link]()
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q=f'select*from stu ORDER BY {y} {z};'
[Link](q)
r=[Link]()
for i in r:
print(i)
[Link]()
[Link]()
except:
print('error')
while True:
print('\n\tMENU')
print('\n\[Link]')
print('\n\[Link] table')
print('\n\[Link] record')
print('\n\[Link] table')
print('\n\[Link] row')
print('\n\[Link] row')
print('\n\[Link] row')
print('\n\[Link] table\n\t')
a=int(input('enter num'))
if a not in (1,2,3,4,5,6,7):
print('\n\t***THE END***')
break
if a==1:
create_table()
if a==2:
b = int(input('Enter unique roll no: '))
c = input('Enter name: ')
g = int(input('Marks in Maths: '))
e = int(input('Marks in English: '))
f = int(input('Marks in CS: '))
insert_record(b,c,g,e,f)
if a==3:
print('\n\t***TABLE***\n')
display_table()
if a==4:
h=input('column from which u want to pass parameter')
i=input('value of which u want to delete')
i=eval(i)
delete_record(h,i)
if a==5:
j=input('name of column where u want to change the value')
k=input('value u want to change it into')
l=input('column after where clause which acts as a reference
point')
m=input('value of this column')
if [Link]():
k=eval(k)
if [Link]():
m=eval(m)
update_record(j,k,l,m)
print('value changed successfully!')
if a==6:
n=input('column name from where u want to search records')
o=input('its value')
search_Record(n,o)
print(f'record(s) where {n} is {o}')
if a==7:
y=input('enter column by which u want to sort')
z=input('ascending or descending (ASC/DESC)')
z=[Link]()
if z in ('ASC','DESC'):
sort_table(y,z)
print(f'sorted by column-{y}')
else:
print(f'{z} should be ASC or DESC')
OUTPUT:
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num2
Enter unique roll no: 4
Enter name: Atharv
Marks in Maths: 99
Marks in English: 82
Marks in CS: 33
Record added successfully!
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num:3
***TABLE***
enter num:4
column from which u want to pass parameter:rollno
value of which u want to delete:5
row deleted where rollno is 5
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num:5
name of column where u want to change the value:rollno
value u want to change it into:5
column after where clause which acts as a reference point:rollno
value of this column:4
value changed successfully!
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num:3
***TABLE***
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num6
column name from where u want to search records:rollno
its value:1
(1, 'Upraj', 99, 99, 99)
record(s) where rollno is 1
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num7
enter column by which u want to sort:rollno
ascending or descending (ASC/DESC):desc
(5, 'Atharv', 99, 82, 33)
(3, 'Ujjwal', 88, 66, 84)
(2, 'Tanmay', 67, 89, 99)
(1, 'Upraj', 99, 99, 99)
sorted by column-rollno
Q17:SQL commands exercise-1:
TABLE:
+-------+-----------+-----------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-----------+-----------+------+------------+---------+------+--------+
| 8369 | smith | clerk | 8902 | 1990-12-18 | 792 | NULL | 20 |
| 8499 | anya | salesman | 8698 | 1991-02-20 | 1600 | 300 | 30 |
| 8521 | seth | salesman | 8698 | 1991-02-22 | 1250 | 500 | 30 |
| 8566 | mahadevan | manager | 8839 | 1991-04-02 | 2955.15 | NULL | 20 |
| 8654 | momin | salesman | 8698 | 1991-09-28 | 1250 | 1400 | 30 |
| 8698 | bina | manager | 8839 | 1991-05-01 | 2821.5 | NULL | 30 |
| 8839 | amir | president | NULL | 1991-11-18 | 4950 | NULL | 10 |
| 8844 | kuldeep | salesman | 8698 | 1991-09-08 | 1500 | 0 | 10 |
| 8882 | shiavansh | manager | 8839 | 1991-06-09 | 2425.5 | NULL | 10 |
| 8886 | anoop | clerk | 8888 | 1993-01-12 | 1089 | NULL | 20 |
| 8888 | scott | analyst | 8566 | 1992-12-09 | 2970 | NULL | 20 |
| 8900 | jatin | clerk | 8698 | 1991-12-03 | 940.5 | NULL | 30 |
| 8902 | fakir | analyst | 8566 | 1991-12-03 | 2970 | NULL | 20 |
| 8934 | mita | clerk | 8882 | 1992-01-23 | 1287 | NULL | 10 |
+-------+-----------+-----------+------+------------+---------+------+--------+
14 rows in set (0.03 sec)
Q1:Write a query to display the name of employee who is having ‘L’ in their name:
Solution:
mysql> SELECT ename FROM emp WHERE ename like '%l%';
+---------+
| ename |
+---------+
| kuldeep |
+---------+
1 row in set (0.01 sec)
Q2:List the details of all employees whose annual salary is between 25000->40000:
Solution:
mysql> SELECT*FROM emp WHERE sal*12 BETWEEN 25000 AND 40000;
+-------+-----------+---------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-----------+---------+------+------------+---------+------+--------+
| 8566 | mahadevan | manager | 8839 | 1991-04-02 | 2955.15 | NULL | 20 |
| 8698 | bina | manager | 8839 | 1991-05-01 | 2821.5 | NULL | 30 |
| 8882 | shiavansh | manager | 8839 | 1991-06-09 | 2425.5 | NULL | 10 |
| 8888 | scott | analyst | 8566 | 1992-12-09 | 2970 | NULL | 20 |
| 8902 | fakir | analyst | 8566 | 1991-12-03 | 2970 | NULL | 20 |
+-------+-----------+---------+------+------------+---------+------+--------+
5 rows in set (0.00 sec)
Q3:Write a query to display employee name. salary and department number who are not getting
commission from the above table:
Solution:
mysql> SELECT ename,sal,deptno FROM emp WHERE comm is null or comm=0;
+-----------+---------+--------+
| ename | sal | deptno |
+-----------+---------+--------+
| smith | 792 | 20 |
| mahadevan | 2955.15 | 20 |
| bina | 2821.5 | 30 |
| amir | 4950 | 10 |
| kuldeep | 1500 | 10 |
| shiavansh | 2425.5 | 10 |
| anoop | 1089 | 20 |
| scott | 2970 | 20 |
| jatin | 940.5 | 30 |
| fakir | 2970 | 20 |
| mita | 1287 | 10 |
+-----------+---------+--------+
11 rows in set (0.00 sec)
Q4:List the details of employees who earn more commission than their salary:
Solution:
mysql> select*from emp where comm>sal;
+-------+-------+----------+------+------------+------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-------+----------+------+------------+------+------+--------+
| 8654 | momin | salesman | 8698 | 1991-09-28 | 1250 | 1400 | 30 |
+-------+-------+----------+------+------------+------+------+--------+
1 row in set (0.00 sec)
Q5:Write a query to display the name of employee whose name contains ‘A’ as third alphabet:
Solution:
mysql> select ename from emp where ename like '_a%';
+-----------+
| ename |
+-----------+
| mahadevan |
| jatin |
| fakir |
+-----------+
3 rows in set (0.00 sec)
Q18:SQL command exercise-2:
TABLE:
+-----+---------+------+------------+------------+---------+
| VID | Name | Age | Dose1 | Dose2 | City |
+-----+---------+------+------------+------------+---------+
| 101 | Jenny | 27 | 2021-12-25 | 2022-01-31 | Delhi |
| 102 | Harjot | 55 | 2021-07-14 | 2021-10-14 | Mumbai |
| 103 | Srikant | 43 | 2021-04-18 | 2022-07-20 | Delhi |
| 104 | Gazala | 75 | 2021-07-31 | NULL | Kolkata |
| 105 | Shiksha | 32 | 2022-01-01 | NULL | Mumbai |
+-----+---------+------+------------+------------+---------+
5 rows in set (0.00 sec)
Q1:Display name and age from table whose 2nd dose has been given and age more than 40:
Solution:
mysql> select name,age from vaccination where dose2 is not NULL and
age>40;
+---------+------+
| name | age |
+---------+------+
| Harjot | 55 |
| Srikant | 43 |
+---------+------+
2 rows in set (0.00 sec)
Solution:
mysql> select DISTINCT city from vaccination;
+---------+
| city |
+---------+
| Delhi |
| Mumbai |
| Kolkata |
+---------+
3 rows in set (0.00 sec)
Q3:display when the last 1st dose was given and when the first 2nd dose was given:
Solution:
mysql> select max(dose1),min(dose2) from vaccination;
+------------+------------+
| max(dose1) | min(dose2) |
+------------+------------+
| 2022-01-01 | 2021-10-14 |
+------------+------------+
1 row in set (0.01 sec)
TABLE:
+---------+---------------+-----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+---------------+-----------+-------------+----------------+--------------+
| 1 | Hindi_movie | musical | 2018-04-23 | 124500 | 130000 |
| 2 | Tamil_movie | action | 2016-05-17 | 112000 | 118000 |
| 3 | English_movie | horror | 2017-08-06 | 245000 | 360000 |
| 4 | Bengali_movie | adventure | 2017-01-04 | 72000 | 100000 |
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+---------------+-----------+-------------+----------------+--------------+
5 rows in set (0.00 sec)
Q1:Find the net profit of each movie showing its ID,name and net profit:
Solution:
mysql> select movieID,moviename,buisnesscost-productioncost as 'Net_profit'
from movie;
+---------+---------------+------------+
| movieID | moviename | Net_profit |
+---------+---------------+------------+
| 1 | Hindi_movie | 5500 |
| 2 | Tamil_movie | 6000 |
| 3 | English_movie | 115000 |
| 4 | Bengali_movie | 28000 |
| 5 | Telugu_movie | NULL |
+---------+---------------+------------+
5 rows in set (0.01 sec)
Q2:List details of all movies which have not been released yet:
Solution:
mysql> select*From movie where releasedate is null;
+---------+--------------+----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+--------------+----------+-------------+----------------+--------------+
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+--------------+----------+-------------+----------------+--------------+
1 row in set (0.01 sec)
Q3:List movieID,name and cost of all movies with product cost greater than 10000 and less than
100000:
Solution:
mysql> select movieID,moviename,productioncost from movie where productioncost
BETWEEN 10000 AND 100000;
+---------+---------------+----------------+
| movieID | moviename | productioncost |
+---------+---------------+----------------+
| 4 | Bengali_movie | 72000 |
| 5 | Telugu_movie | 100000 |
+---------+---------------+----------------+
2 rows in set (0.00 sec)
Q4:List details of all movies which fall in the category of action and horror:
Solution:
mysql> select*from movie where category in ('horror','action');
+---------+---------------+----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+---------------+----------+-------------+----------------+--------------+
| 2 | Tamil_movie | action | 2016-05-17 | 112000 | 118000 |
| 3 | English_movie | horror | 2017-08-06 | 245000 | 360000 |
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+---------------+----------+-------------+----------------+--------------+
3 rows in set (0.00 sec)
Q20:SQL command exercise-4
TABLE:
+-----------+-------+---------+------------+--------+-------------+--------+
| studentNo | class | name | game | grade1 | SUPW | grade2 |
+-----------+-------+---------+------------+--------+-------------+--------+
| 10 | 7 | sameer | cricket | B | photography | A |
| 11 | 8 | sujit | tennis | A | gardening | C |
| 12 | 7 | kamal | swimming | B | photography | B |
| 13 | 7 | veena | tennis | C | cooking | A |
| 14 | 9 | archana | basketball | A | literature | A |
+-----------+-------+---------+------------+--------+-------------+--------+
5 rows in set (0.00 sec)
Q1:Display the names of the students who are getting a grade ‘C’ in either game or SUPW:
Solution:
mysql> select name from student where grade1='C' or grade2='C';
+-------+
| name |
+-------+
| sujit |
| veena |
+-------+
2 rows in set (0.00 sec)
Solution:
mysql> Select Distinct game from student;
+------------+
| game |
+------------+
| cricket |
| tennis |
| swimming |
| basketball |
+------------+
4 rows in set (0.00 sec)
Q3:Display name and SUPW taken by students whose name starts with ‘A’:
Solution:
mysql> select name,supw from student where name like 'a%';
+---------+------------+
| name | supw |
+---------+------------+
| archana | literature |
+---------+------------+
1 row in set (0.00 sec)
TABLE:
+-----+----------+------+------------+------------+--------+------+
| ID | name | age | department | dateOfjoin | salary | sex |
+-----+----------+------+------------+------------+--------+------+
| 101 | jugal | 34 | computer | 1997-01-10 | 12000 | M |
| 102 | sharmila | 31 | history | 1998-03-24 | 20000 | F |
| 103 | sandeep | 32 | maths | 1996-12-12 | 30000 | M |
| 104 | sangeeta | 35 | history | 1999-07-01 | 40000 | F |
| 105 | rakesh | 42 | maths | 1997-09-05 | 35000 | M |
+-----+----------+------+------------+------------+--------+------+
5 rows in set (0.00 sec)
Solution:
mysql> select*from teacher where department='history';
+-----+----------+------+------------+------------+--------+------+
| ID | name | age | department | dateOfjoin | salary | sex |
+-----+----------+------+------------+------------+--------+------+
| 102 | sharmila | 31 | history | 1998-03-24 | 20000 | F |
| 104 | sangeeta | 35 | history | 1999-07-01 | 40000 | F |
+-----+----------+------+------------+------------+--------+------+
2 rows in set (0.00 sec)
Solution:
mysql> select name from teacher where sex='F' and salary>30000;
+----------+
| name |
+----------+
| sangeeta |
+----------+
1 row in set (0.00 sec)
Q3:List names of all teacher with their date of joining in ascending order:
Solution:
mysql> select name from teacher order by dateofjoin;
+----------+
| name |
+----------+
| sandeep |
| jugal |
| rakesh |
| sharmila |
| sangeeta |
+----------+
5 rows in set (0.01 sec)
BIBLIOGRAPHY
This project draws upon the foundational concepts and examples presented in
Computer Science with Python for Class XII by Sumita Arora, published by
Dhanpat Rai & Co. in 2025.