Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
39 views65 pages

Python Practical Record - Grade 12

Uploaded by

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

Python Practical Record - Grade 12

Uploaded by

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

Python Practical Record – Grade 12

1. Write a program to create a random number generator that


generates numbers between 1 and 6. (Simulates a dice)

Program:

import random

def gen():

print("The random number generated is:",random.randint(1,6))

gen()

Output:

2. Write a program to create a function that takes a number n and then


returns a randomly generated number having exactly n digits.

Program:

def rand(n):

import random

start = 10**(n-1)

stop = 10**n

print("The random number generated


is:",random.randrange(start,stop))

n = int(input("Enter a number:"))

rand(n)

rand(n)

Output:
3. Write a program to create a function that takes two numbers and
returns the number that has minimum one's digit.

Program:

def comp(n,n1):

a = n%10

b = n1%10

if a<b:

print("The minimum one's digit is:",a)

else:

print("The minimum one's digit is:",b)

n = int(input("Enter a number:"))

n1 = int(input("Enter another number:"))

comp(n,n1)

Output:

4. Write a program that generates a series using a function which takes


first and last values of the series and then generates four terms that are
equidistant.

Program:

def func(x, y):

d = (y-x)/3
print("The series is:",x,',', x+d,',', x+2*d,',', y)

x = int(input("Enter lower limit:"))

y = int(input("Enter upper limit:"))

func(x,y)

Output:

5. Write a program to read a program line by line and display each


word separated by a #.
Program:

f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/Emirates - rec


5.txt",'r')
a = ''
r = f.readlines()
for i in r:
b=i.split()
for j in b:
a+=j
a+='#'
print(a)

Output:

6. Write a program to read a text file and display the number of


vowels/consonants/upper case/lowercase characters in the file.
Program:

f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/test - rec


6.txt",'r')

ch = ''
v=0

c=0

l=0

u=0

r = f.read()

for i in r:

if i in 'aeiouAEIOU':

v+=1

else:

c+=1

for i in r:

if i.isupper() == True:

u+=1

else:

l+=1

print('Vowels',v)

print('Consonants',c)

Output:
7. Write a program to remove all the lines that contain the character
letter 'a' in a file and write it to another file.

Program:

f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/text file - rec


7.txt','r')

f1 = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/text file 2 - rec


7.txt','w')

for i in f:

if 'a' not in i:

f1.write(i)

f.close()

f1.close()

Output:

8. Create a binary file with name and role number search for a given
role number and search for a given role number and display the name
and if not found display an appropriate message.
Program (i):
import pickle
def record():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/student.dat",'wb')
n = int(input("How many records?"))
d = {}
for i in range(n):
r = int(input("Enter roll number:"))
n = input("Enter name:")
d[r]=n
pickle.dump(d,f)
f.close()
record()
Program(ii):
import pickle
def search():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/student.dat",'rb')
n = int(input("Enter roll number:"))
c=0
try:
while True:
data = pickle.load(f)
for i in data:
if i == n:
print(i,data[i])
c+=1
except EOFError:
if c == 0:
print("Record not found")
else:
pass
f.close()
search()
Output:

9. Write a program to create a binary file with roll number, name and
marks. Input a roll number and update the marks.
Program:
import pickle
def write():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat','wb')
n = int(input("How many records?"))
rec = []
for i in range(n):
r = int(input("Enter roll number:"))
n = input("Enter name:")
m = float(input("Enter marks:"))
data = [r,n,m]
rec.append(data)
pickle.dump(rec,f)
f.close()
def update():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat','rb+')
f.seek(0)
found = 0
roll = int(input("Enter roll number to update:"))
t = pickle.load(f)
for i in t:
if i[0]==roll:
i[2]=float(input("Enter marks:"))
found = 1
f.seek(0)
pickle.dump(t,f)
if found == 0:
print("Not found")
f.close()
def read():
f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat",'rb+')
rec = pickle.load(f)
for i in rec:
print(i)
f.close()
while True:
print('Menu','1.Write','2.Update','3.Read','4.Exit',sep='\n')
o = int(input("Enter number:"))
if o ==1:
write()
if o==2:
update()
elif o==3:
read()
elif o==4:
break
else:
print("Invalid option")
print("Thank you")
Output:
10.Create a csv file using userID and password, read and search the
password for given userID.
Program:
import csv
def write():
f = open("C:/Users/user/Desktop/Bhavika 12A/Record/csv file - rec
10.csv","w",newline='')
s = csv.writer(f)
s.writerow(['Username','Password'])
n = int(input("Enter number of records:"))
for i in range(n):
u = input("Enter username:")
p = input("Enter password:")
l = [u,p]
s.writerow(l)
f.close()
def read():
e = input("Enter username:")
f1 = open("C:/Users/user/Desktop/Bhavika 12A/Record/csv file - rec
10.csv","r")
r = csv.reader(f1)
for rec in r:
if rec[0]==e:
print("Password is:",rec[1])
f1.close()
write()
read()
Output:

11.Write a function that reads a csv file ad creates another csv file with
the same content but with a different delimiter.
Program:
def create()
import csv
f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/file -
rec11.csv",'r',newline='')
r = csv.reader(f)
f1 = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/2nd file rec
11.csv",'w',newline='')
w = csv.writer(f1,delimiter = '|')
for i in r:
w.writerow(i)
f.close()
f1.close()
create()
Ouput:

12. Program to create a CSV file and store empno, name, salary and
search any empno and display name, salary and if not found print
appropriate message.
Program:
import csv
def record():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/record - rec
12.csv','w',newline='')
w = csv.writer(f)
w.writerow(['EmployeeNumber','Name','Salary'])
n = int(input("Enter number of records:"))
for i in range(n):
empno = input("Enter employee number:")
n = input("Enter name:")
s = float(input("Enter salary:"))
l = list([empno,n,s])
w.writerow(l)
f.close()
record()
def search():
import csv
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/record - rec
12.csv','r',newline='')
e = input("Enter employee number to search:")
wr = csv.reader(f)
next(wr)
for i in wr:
if i[0]==e:
print(i[1])
print(i[2])
break
search()
Output:
13. Write functions:
i. To create a text file "text.txt" with few lines of text.
ii. To count the number of lines with 'B' in the file test.txt.
iii. To count the number of words starting with letter 'E' or 'O'.
Program:
def write():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'w')
t = "Bear and Goldilocks\nGoldilocks and the three bears\nElephant
and the ant\nLion and mouse"
f.write(t)
f.close()
write()
def B():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'r')
r = f.readlines()
b=0
for i in range(len(r)):
s = r[i].split()
if s[0][0]=='B':
b+=1
print("Number of lines starting with B:",b)
f.close()
B()
def EorG():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'r')
r = f.readlines()
e=0
for i in range(len(r)):
s = r[i].split()
for j in range(len(s)):
if s[j][0]=='E' or s[j][0]=='G':
e+=1
print("Number of words starting with E or G:",e)
f.close()
EorG()
Output:

14. Write a menu driven program to perform all the basic operations in
a binary file "TELEPHONE.DAT" which contains telephone number,
customer name and area.
i. Inserting records
ii. Reading all records and displaying
iii. Updating record based on given telephone number
iv. Searching record based on given telephone number
v. Deleting a record based on given customer name

Program:
import pickle
def choice():
print("Hello! Welcome to - Telephone menu -")
print("Choose:")
print("1.Inserting records")
print("2.Reading all records and displaying")
print("3.Updating record based on given telephone number")
print("4.Searching record based on given telephone number")
print("5.Deleting a record based on given customer name")
c = int(input("Enter number to perform task:"))
if c==1:
one()
elif c==2:
two()
elif c==3:
three()
elif c==4:
four()
elif c==5:
five()
else:
print("INVALID NUMBER ENTERED!")
def one():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'wb')
n = int(input("Enter number of records:"))
rec = []
print()
for i in range(n):
n = input("Enter name of customer:")
t = int(input("Enter telephone number:"))
a = input("Enter area of customer:")
data = [n,t,a]
rec.append(data)
pickle.dump(rec,f)
f.close()
def two():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb+')
rec = pickle.load(f)
print()
for i in rec:
print(i)
print()
f.close()

def three():
f = open(r'C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT','rb+')
f.seek(0)
found = 0
n = int(input("Enter telephone number to update:"))
t = pickle.load(f)
for i in t:
if i[1]==n:
i[1]=int(input("Enter new telephone number:"))
found = 1
f.seek(0)
pickle.dump(t,f)
if found == 0:
print("Not found")
f.close()
print("NEW RECORD.....")
print()
d1 = two()
print()
def four():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb')
t = int(input("Enter telephone number:"))
c=0
try:
while True:
data = pickle.load(f)
for i in data:
if i[1] == t:
print("Record found....",i[0],i[1],i[2])
print()
c+=1
except EOFError:
if c == 0:
print("Record not found")
else:
pass
f.close()
def five():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb+')
n = input("Enter customer name:")
f.seek(0)
try:
l=[]
while True:
data = pickle.load(f)
if data[0]!=n:
l.append(data)
except EOFError:
f.seek(0)
for i in l:
pickle.dump(i,f)
print("Record deleted")
print("UPDATED RECORD....")
print()
d2 = two()
f.close()

def five():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb')
rec = pickle.load(f)
f.close()
n = input("Enter customer name to delete:")
l = []
for r in rec:
if r[0] != n:
l.append(r)

f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT", 'wb')
pickle.dump(l, f)
f.close()

print("Record deleted")
print("UPDATED RECORD....")
print()
two()
def more():
while 'y':
i = input("Do you want to enter more?.....y/n....:")
if i == 'y' or i=='Y':
choice()
elif i == 'n':
print("THANK YOU! EXITING....")
break
choice()
more()
Output:
15. Write a python program to implement a stack using a list data
structures write functions:
a) to add an element
b) to delete an element
c) to display the stack
Program:
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[a])
stack=[]
top=None
while True:
print("Stack operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display stack")
print("5.Exit")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter item"))
Push(stack,item)
elif ch==2:
item=Pop(stack)
if item=="Underflow":
print("Underflow! Stack is empty")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(stack)
if item=="Underflow":
print("Underflow! Stack is empty!")
else:
print("Topmost item is",item)
elif ch==4:
Display(stack)
elif ch==5:
break
else:
print("Invalid choice!")
Output:
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:1
Enter item:8
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:2
Popped item is 8
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:3
Stack Empty
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:4
Underflow! Stack is EMPTY
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:5
16. Write a python program to implement a stack:
Each element of a stack TICKET(a list) is a dictionary with keys
'TICKETNO', and 'PNAME'. The values for 'TICKETNO' and 'PNAME' are
of type integers and string respectively.
Write functions:
- PUSH(TICKET) to push an element into the stack. The details of the
ticket to be pushed are to be input from the user.
- POP(TICKET) to pop an element from the stack. The popped element
should be returned by the function. If the stack is empty, function
should return None.

17. Program to connect with database and store record of employee


and display records.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(empno int,name
varchar(20),dept varchar(20),salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
18. Program to connect with database and search employee number in
table employee and display record, if empno not found appropriate
message.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(empno int,name
varchar(20),dept varchar(20),salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
19. Program to connect with database and update the employee record
of entered empno.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(Empno int,Name
varchar(20),Dept varchar(20),Salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlupdate():
ans = "y"
while ans.lower()=='y':
eno = int(input("Enter empno to update:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
d = input("Enter new department:")
s = int(input("Enter new salary:"))
else:
break
q = "update employee set Dept='{}', Salary={} where
empno={}".format(d,s,eno)
ur.execute(q)
con.commit()
print("Record Updates!")
ans = input("Do you want to update more? (y/n):")
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('4.Update Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice == 4:
sqlupdate()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
20. Program to connect with database and to delete the record of
entered employee number.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(Empno int,Name
varchar(20),Dept varchar(20),Salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlupdate():
ans = "y"
while ans.lower()=='y':
eno = int(input("Enter empno to update:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
d = input("Enter new department:")
s = int(input("Enter new salary:"))
else:
break
q = "update employee set Dept='{}', Salary={} where
empno={}".format(d,s,eno)
ur.execute(q)
con.commit()
print("Record Updates!")
ans = input("Do you want to update more? (y/n):")
def sqldelete():
ans='y'
while ans.lower()=='y':
eno = int(input("Enter empno to delete:"))
q = 'select * from employee where empno={}'.format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry! Not found")
else:

print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
q = 'delete from employee where empno={}'.format(eno)
ur.execute(q)
con.commit()
print("Record Deleted!")
else:
break
ans = input("Do you want to delete more? (y/n):")
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('4.Update Record')
print('5.Delete Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice == 4:
sqlupdate()
continue
elif choice == 5:
sqldelete()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue

Output:

SQL RECORD - BHAVIKA


1. Write a SQL command to create the following table FLIGHTS and FARE table of the
following structure.

TABLE: FLIGHTS

COLUMN NAME DATA TYPE SIZE CONSTRAINT


FL NO CHAR 10 PRIMARY KEY
DEPARTURE VARCHAR 20 NOT NULL
ARRIVAL VARCHAR 20 NOT NULL
NO FLIGHTS INTEGER
NO OF STOPS INTEGER

Output:

mysql> create table Flights(FL_NO char(10) primary key, DEPARTURE varchar(20) NOT
NULL, ARRIVAL varchar(20), NO_FLIGHTS INT NOT NULL,NO_OF_STOPS INT);
Query OK, 0 rows affected (0.31 sec)
mysql> desc flights;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| FL_NO | char(10) | NO | PRI | NULL | |
| DEPARTURE | varchar(20) | NO | | NULL | |
| ARRIVAL | varchar(20) | YES | | NULL | |
| NO_FLIGHTS | int | NO | | NULL | |
| NO_OF_STOPS | int | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)

TABLE: FARE

Column name Date type Size Constraint


FL_NO CHAR 10 PRIMARY KEY
AIRLINES VARCHAR 20 NOT NULL
FARE DECIMAL 10,2 NOT NULL
TAX DECIMAL 10,2 NOT NULL

Output:

mysql> create table FARE(FL_NO CHAR(10) primary key, AIRLINES varchar(20) not null,
FARE DECIMAL(10,2) NOT NULL, TAX DECIMAL(10,2) NOT NULL);
Query OK, 0 rows affected (0.66 sec)

mysql> desc fare;


+----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+-------+
| FL_NO | char(10) | NO | PRI | NULL | |
| AIRLINES | varchar(20) | NO | | NULL | |
| FARE | decimal(10,2) | NO | | NULL | |
| TAX | decimal(10,2) | NO | | NULL | |
+----------+---------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

TABLE : FLIGHT
FL_NO DEPARTURE ARRIVAL NO FLIGHTS NO STOPS
IC301 MUMBAI DELHI 8 0
IC799 BALNGALORE DELHI 2 1
MC101 INDORE MUMBAI 3 0
IC302 DELHI MUMBAI 8 0
AM812 KANPUR BANGLORE 3 1
IC899 MUMBAI KOCHI 1 4
AM501 DELHI TRIVANDRUM 1 5
MU499 MUMBAI MADRAS 3 3
IC701 DELHI AHMEDABAD 4 0

Output:
mysql> insert into Flight values("IC301","MUMBAI","DELHI",8,0),
(“IC799”,”BANGALORE”,”DELHI”,2,1),("MC101","INDORE","MUMBAI",3,0),
("IC302","DELHI","MUMBAI",8,0),("AM812","KANPUR","BANGALORE",3,1),
("IC899","MUMBAI","KOCHI",1,4),("AM501","DELHI","TRIVANDRUM",1,5),
("MU499","MUMBAI","MADRAS",3,3),("IC701","DELHI","AHMEDABAD",4,0);
Query OK, 7 rows affected (0.08 sec)
Records: 7 Duplicates: 0 Warnings: 0

mysql> SELECT * from flight;


+-------+-----------+------------+------------+-------------+
| FL_NO | DEPARTURE | ARRIVAL | NO_FLIGHTS | NO_OF_STOPS |
+-------+-----------+------------+------------+-------------+
| AM501 | DELHI | TRIVANDRUM | 1| 5|
| AM812 | KANPUR | BANGALORE | 3| 1|
| IC301 | MUMBAI | DELHI | 8| 0|
| IC302 | DELHI | MUMBAI | 8| 0|
| IC701 | DELHI | AHMEDABAD | 4| 0|
| IC799 | BANGALORE | DELHI | 2| 1|
| IC899 | MUMBAI | KOCHI | 1| 4|
| MC101 | INDORE | MUMBAI | 3| 0|
| MU499 | MUMBAI | MADRAS | 3| 3|
+-------+-----------+------------+------------+-------------+
9 rows in set (0.03 sec)

TABLE : FARE

FL_NO AIRLINES FARE TAX


%
IC701 INDIAN 6500 10
AIRLINES
MU499 SAHARA 9400 5
AM501 JET AIRWAYS 13450 8
IC899 INDIAN 8100 4
AIRLINES
IC302 INDIAN 4300 9
AIRLINES
IC799 INDIAN 1050 10
AIRLINES
MC101 DECCAN 3500 4
AIRLINES

Output:
mysql> create table FARE1(FL_NO varchar(20) primary key,AIRLINES varchar(20),FARE int ,
TAX int);
Query OK, 0 rows affected (0.52 sec)

mysql> insert into FARE1 values("IC701", "INDIAN AIRLINES", 6500, 10),


("MU499","SAHARA",9400,5),("AM501","JET AIRWAYS",13450,8),("IC899","INDIAN
AIRLINES",8100,4),("IC302","INDIAN ARLINES",4300,9),("IC799","INDIAN
AIRLINES",1050,10),("MC101","DECCAN ARILINES",3500,4);
Query OK, 7 rows affected (0.06 sec)
Records: 7 Duplicates: 0 Warnings: 0
mysql> select * from FARE1;
+-------+-----------------+-------+------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+-------+------+
| AM501 | JET AIRWAYS | 13450 | 8 |
| IC302 | INDIAN AIRLINES | 4300 | 9 |
| IC701 | INDIAN AIRLINES | 6500 | 10 |
| IC799 | INDIAN AIRLINES | 1050 | 10 |
| IC899 | INDIAN AIRLINES | 8100 | 4 |
| MC101 | DECCAN ARILINES | 3500 | 4 |
| MU499 | SAHARA | 9400 | 5 |
+-------+-----------------+-------+------+
7 rows in set (0.02 sec)

2. Write SQL commands for the following questions based on the above tables:
i) Display Flight_No, No of flights arriving to Delhi .

Output:
mysql> select FL_NO, NO_FLIGHTS from flight where ARRIVAL = "Delhi";
+-------+------------+
| FL_NO | NO_FLIGHTS |
+-------+------------+
| IC301 | 8|
| IC799 | 2|
+-------+------------+
2 rows in set (0.00 sec)

ii) Display all the airlines that have maximum number of flights.

mysql> select AIRLINES, NO_FLIGHTS from Fare1, Flight where Flight.FL_NO =


Fare1.FL_NO and NO_FLIGHTS = (select max(NO_FLIGHTS) from FLIGHT);
+----------------+------------+
| AIRLINES | NO_FLIGHTS |
+----------------+------------+
| INDIAN AIRLINES | 8|
+----------------+------------+

(iii) Display total fare of all the airlines.

mysql> select sum(FARE) from fare1;


+-----------+
| sum(FARE) |
+-----------+
| 46300 |
+-----------+
1 row in set (0.02 sec)

(iv) To display departure and arrival points of flights no IC302 and MU499.

mysql> select DEPARTURE, ARRIVAL from FLIGHT where FL_NO = "IC302" or FL_NO =
'MU499';
+-----------+---------+
| DEPARTURE | ARRIVAL |
+-----------+---------+
| DELHI | MUMBAI |
| MUMBAI | MADRAS |
+-----------+---------+
2 rows in set (0.00 sec)

(v) Display number of distinct flight.

mysql> select count(distinct(AIRLINES)) from fare1;


+---------------------------+
| count(distinct(AIRLINES)) |
+---------------------------+
| 4|
+---------------------------+
1 row in set (0.00 sec)

(vi) Display the minimum and maximum fare of each airline.

mysql> select FL_NO, AIRLINES, max(FARE), min(FARE) from fare1 group by AIRLINES;
+-------+-----------------+-----------+-----------+
| FL_NO | AIRLINES | max(FARE) | min(FARE) |
+-------+-----------------+-----------+-----------+
| AM501 | JET AIRWAYS | 13450 | 13450 |
| IC302 | INDIAN AIRLINES | 8100 | 1050 |
| MC101 | DECCAN ARILINES | 3500 | 3500 |
| MU499 | SAHARA | 9400 | 9400 |
+-------+-----------------+-----------+-----------+
4 rows in set (0.01 sec)

(vii) Increase the fare of Sahara by 200.

mysql> update fare1 set fare = fare+200 where AIRLINES = 'SAHARA';


Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from fare1;


+-------+-----------------+-------+------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+-------+------+
| AM501 | JET AIRWAYS | 13450 | 8 |
| IC302 | INDIAN AIRLINES | 4300 | 9 |
| IC701 | INDIAN AIRLINES | 6500 | 10 |
| IC799 | INDIAN AIRLINES | 1050 | 10 |
| IC899 | INDIAN AIRLINES | 8100 | 4 |
| MC101 | DECCAN ARILINES | 3500 | 4 |
| MU499 | SAHARA | 9600 | 5 |
+-------+-----------------+-------+------+
7 rows in set (0.02 sec)

(viii) Create a report which contains FL_NO, AIRLINES, TOTAL FARE of all airlines. Total
fare is calculated as fare+(fare*tax%*0.01).

mysql> select FL_NO, AIRLINES, FARE+(FARE*TAX*0.01) from fare1;


+-------+-----------------+----------------------+
| FL_NO | AIRLINES | FARE+(FARE*TAX*0.01) |
+-------+-----------------+----------------------+
| AM501 | JET AIRWAYS | 14526.00 |
| IC302 | INDIAN AIRLINES | 4687.00 |
| IC701 | INDIAN AIRLINES | 7150.00 |
| IC799 | INDIAN AIRLINES | 1155.00 |
| IC899 | INDIAN AIRLINES | 8424.00 |
| MC101 | DECCAN ARILINES | 3640.00 |
| MU499 | SAHARA | 10080.00 |
+-------+-----------------+----------------------+
7 rows in set (0.00 sec)

(ix) Display the details of airlines whose name start with ‘IC’.

mysql> select * from fare1 where FL_NO like 'IC%';


+-------+-----------------+------+------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+------+------+
| IC302 | INDIAN AIRLINES | 4300 | 9 |
| IC701 | INDIAN AIRLINES | 6500 | 10 |
| IC799 | INDIAN AIRLINES | 1050 | 10 |
| IC899 | INDIAN AIRLINES | 8100 | 4 |
+-------+-----------------+------+------+
4 rows in set (0.01 sec)

(x) Create a view which contains details of airlines which are arriving in Mumbai.

mysql> create view vl as select * from flight where ARRIVAL = 'MUMBAI';


Query OK, 0 rows affected (0.28 sec)

mysql> select * from vl;


+-------+-----------+---------+------------+-------------+
| FL_NO | DEPARTURE | ARRIVAL | NO_FLIGHTS | NO_OF_STOPS |
+-------+-----------+---------+------------+-------------+
| IC302 | DELHI | MUMBAI | 8| 0|
| MC101 | INDORE | MUMBAI | 3| 0|
+-------+-----------+---------+------------+-------------+
2 rows in set (0.04 sec)

(xi) Change the name of the column airlines to flight name.

mysql> alter table fare1 change AIRLINES FLIGHT_NAME varchar(20);


Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql>
mysql> select * from fare1;
+-------+-----------------+-------+------+
| FL_NO | FLIGHT_NAME | FARE | TAX |
+-------+-----------------+-------+------+
| AM501 | JET AIRWAYS | 13450 | 8 |
| IC302 | INDIAN AIRLINES | 4300 | 9 |
| IC701 | INDIAN AIRLINES | 6500 | 10 |
| IC799 | INDIAN AIRLINES | 1050 | 10 |
| IC899 | INDIAN AIRLINES | 8100 | 4 |
| MC101 | DECCAN ARILINES | 3500 | 4 |
| MU499 | SAHARA | 9600 | 5 |
+-------+-----------------+-------+------+
7 rows in set (0.02 sec)

(OR)
Alter table fare rename column airlines to flight_name;

(xii) Delete the column tax.

mysql> alter table fare1 drop column TAX;


Query OK, 0 rows affected (0.96 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> select * from fare1;


+-------+-----------------+-------+
| FL_NO | FLIGHT_NAME | FARE |
+-------+-----------------+-------+
| AM501 | JET AIRWAYS | 13450 |
| IC302 | INDIAN AIRLINES | 4300 |
| IC701 | INDIAN AIRLINES | 6500 |
| IC799 | INDIAN AIRLINES | 1050 |
| IC899 | INDIAN AIRLINES | 8100 |
| MC101 | DECCAN ARILINES | 3500 |
| MU499 | SAHARA | 9600 |
+-------+-----------------+-------+
7 rows in set (0.00 sec)

3. Create the tables SCHOOL and ADMIN of following structure.

TABLE : SCHOOL
Column name Data type Size Constraints
Code Integer Primary key
Teacher_name Varchar 20 Not null
Subject Char 20 Not null
DOJ Cate Not null
Periods Integer
Experience Integer

Output:

mysql> create table SCHOOL(Code int primary key, Teacher_name varchar(20) not null, Subject
char(20) not null, DOJ date not null, Periods int, Experience int);
Query OK, 0 rows affected (0.24 sec)

mysql> desc school;


+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| Code | int | NO | PRI | NULL | |
| Teacher_name | varchar(20) | NO | | NULL | |
| Subject | char(20) | NO | | NULL | |
| DOJ | date | NO | | NULL | |
| Periods | int | YES | | NULL | |
| Experience | int | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
6 rows in set (0.07 sec)

Table: ADMIN

Column Name Date type Size Constraints


Code Integer Primary key
Gender Varchar 8 Not null
Designation Char 20 Not null

Output:

mysql> create table ADMIN(code int primary key, gender varchar(20) not null, designation
char(20) not null);
Query OK, 0 rows affected (0.25 sec)

mysql> desc ADMIN;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| code | int | NO | PRI | NULL | |
| gender | varchar(20) | NO | | NULL | |
| designation | char(20) | NO | | NULL | |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.07 sec)

4. Insert following values into the table.

TABLE: SCHOOL

Code Teacher_nam Subject DOJ Period Experienc


e s e
1001 Ravi English 2001/12/03 24 10
Shankar
1009 Priya Raj Physics 1998/09/12 26 12
1203 Lasa Anand English 2000/04/09 27 5
1045 Yasraj Maths 2000/08/24 24 15
1123 Gagan Physics 1999/07/16 28 3
1167 Umesh Chemistr 1998/05/11 22 5
y

Output:
mysql> insert into school values(1001, "Ravi Shankar", "English", "2001/12/03", 24, 10),(1009,
"Priya Raj", "Physics", "1998/09/12", 26, 12), (1203, "Lasa Anand", "English", "2000/08/24",
24,15), (1045, "Yasraj", "Math", "2000/08/24", 24, 15), (1123,"Gagan","Physics", "1999/07/16",
28, 3), (1167, "Umesh","Chemistry","1998/05/11",22,5);
Query OK, 6 rows affected (0.08 sec)

mysql> select * from SCHOOL;


+------+--------------+-----------+------------+---------+------------+
| Code | Teacher_name | Subject | DOJ | Periods | Experience |
+------+--------------+-----------+------------+---------+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 | 10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 | 12 |
| 1045 | Yasraj | Math | 2000-08-24 | 24 | 15 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 | 3|
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 | 5|
| 1203 | Lasa Anand | English | 2000-08-24 | 24 | 15 |
+------+--------------+-----------+------------+---------+------------+
6 rows in set (0.00 sec)

TABLE: ADMIN
Code Gender Designation
1001 Male Vice principal
1203 Female Coordinator
1009 Female Coordinator
1045 Male HOD
1123 Male Senior teacher
1167 Male Senior teacher

Ouput:

mysql> insert into admin values(1001, "Male" , "Vice Principal"), (1203, "Female",
"Coordinator"), (1009, "Female","Coordinator"), (1045, "Male", "HOD"), (1123, "Male
", "Senior Teacher"), (1167, "Male", 'Senior Teacher');
Query OK, 6 rows affected (0.08 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from admin;


+------+--------+----------------+
| Code | Gender | Designation |
+------+--------+----------------+
| 1001 | Male | Vice Principal |
| 1009 | Female | Coordinator |
| 1045 | Male | HOD |
| 1123 | Male | Senior Teacher |
| 1167 | Male | Senior Teacher |
| 1203 | Female | Coordinator |
+------+--------+----------------+
6 rows in set (0.00 sec)

5. (i) Display teacher name, periods of all teachers whose periods are less than 25 ans name
starts with either R or U
mysql> select Teacher_name, Periods from school where Periods<=25 and (Teacher_name like "R
%" or Teacher_name like "U%");
+--------------+---------+
| Teacher_name | Periods |
+--------------+---------+
| Ravi Shankar | 24 |
| Umesh | 22 |
+--------------+---------+
2 rows in set (0.00 sec)

(ii) Display the contents of school table in descending order of teacher name

mysql> select * from school order by Teacher_name desc;


+------+--------------+-----------+------------+---------+------------+
| Code | Teacher_name | Subject | DOJ | Periods | Experience |
+------+--------------+-----------+------------+---------+------------+
| 1045 | Yasraj | Math | 2000-08-24 | 24 | 15 |
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 | 5|
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 | 10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 | 12 |
| 1203 | Lasa Anand | English | 2000-08-24 | 24 | 15 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 | 3|
+------+--------------+-----------+------------+---------+------------+
6 rows in set (0.01 sec)
(iii) Display all from table school, where period is between 10 and 20.

mysql> select * from school where periods between 10 and 20;


Empty set (0.02 sec)

(iv) Display teachername, code and designation from tables school and admin for female
teacher

mysql> select school.Code,Teacher_name, Designation from school, admin where gender =


'Female' and school.code = admin.code;
+------+--------------+-------------+
| Code | Teacher_name | Designation |
+------+--------------+-------------+
| 1009 | Priya Raj | Coordinator |
| 1203 | Lasa Anand | Coordinator |
+------+--------------+-------------+
2 rows in set (0.00 sec)

(v) Display the teacher name who has minimum periods

mysql> select teacher_name from school where periods = (select min(periods) from school);
+--------------+
| teacher_name |
+--------------+
| Umesh |
+--------------+
1 row in set (0.04 sec)

(vi) Increase 2 year’s experience for all female teachers

mysql> update school, admin set Experience = Experience+2 where gender = "Female" and
admin.code = school.code;
Query OK, 2 rows affected (0.06 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from school;
+------+--------------+-----------+------------+---------+------------+
| Code | Teacher_name | Subject | DOJ | Periods | Experience |
+------+--------------+-----------+------------+---------+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 | 10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 | 14 |
| 1045 | Yasraj | Math | 2000-08-24 | 24 | 15 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 | 3|
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 | 5|
| 1203 | Lasa Anand | English | 2000-08-24 | 24 | 17 |
+------+--------------+-----------+------------+---------+------------+
6 rows in set (0.00 sec)

(vii) Insert a row in admin table.

mysql> insert into admin value(1011, "Female", "Secretary");


Query OK, 1 row affected (0.04 sec)

mysql> select * from admin;


+------+--------+----------------+
| Code | Gender | Designation |
+------+--------+----------------+
| 1001 | Male | Vice Principal |
| 1009 | Female | Coordinator |
| 1011 | Female | Secretary |
| 1045 | Male | HOD |
| 1123 | Male | Senior Teacher |
| 1167 | Male | Senior Teacher |
| 1203 | Female | Coordinator |
+------+--------+----------------+
7 rows in set (0.00 sec)

(viii) Create a view of table school

mysql> create view dl as select* from school;


Query OK, 0 rows affected (0.10 sec)

(ix) Display the highest experience among all male teachers

mysql> select max(Experience) from school, admin where gender = "Male";


+-----------------+
| max(Experience) |
+-----------------+
| 17 |
+-----------------+
1 row in set (0.09 sec)

(x) Display code, teacher_name, salary to be paid where salary to be paid = period*507.50

mysql> select code, teacher_name, periods*507.5 from school;


+------+--------------+---------------+
| code | teacher_name | periods*507.5 |
+------+--------------+---------------+
| 1001 | Ravi Shankar | 12180.0 |
| 1009 | Priya Raj | 13195.0 |
| 1045 | Yasraj | 12180.0 |
| 1123 | Gagan | 14210.0 |
| 1167 | Umesh | 11165.0 |
| 1203 | Lasa Anand | 12180.0 |
+------+--------------+---------------+
6 rows in set (0.00 sec)

(xi) Display code.teachername and subject of all teachers who have joined the school after
01/01/1999

mysql> select Code,Teacher_name, Subject from school where DOJ>"1999-01-01";


+------+--------------+---------+
| Code | Teacher_name | Subject |
+------+--------------+---------+
| 1001 | Ravi Shankar | English |
| 1045 | Yasraj | Math |
| 1123 | Gagan | Physics |
| 1203 | Lasa Anand | English |
+------+--------------+---------+
4 rows in set (0.02 sec)

(xii) Display the highest experience in each subject


mysql> select subject, max(experience) from school group by subject;
+-----------+-----------------+
| subject | max(experience) |
+-----------+-----------------+
| English | 17 |
| Physics | 14 |
| Math | 15 |
| Chemistry | 5|
+-----------+-----------------+
4 rows in set (0.00 sec)

(xiii) Display teacher_name, designation of male teachers

mysql> select Teacher_name, Designation from school, admin where school.code = admin.code
and gender = "Male";
+--------------+----------------+
| Teacher_name | Designation |
+--------------+----------------+
| Ravi Shankar | Vice Principal |
| Yasraj | HOD |
| Gagan | Senior Teacher |
| Umesh | Senior Teacher |
+--------------+----------------+
4 rows in set (0.00 sec)

(xiv) Display the number of teachers in each designation

mysql> select designation ,count(Teacher_name) from school,admin where school.code =


admin.code group by designation;
+----------------+---------------------+
| designation | count(Teacher_name) |
+----------------+---------------------+
| Vice Principal | 1|
| Coordinator | 2|
| HOD | 1|
| Senior Teacher | 2|
+----------------+---------------------+
4 rows in set (0.00 sec)
(xv) Display the number of distinct subjects

mysql> select count(distinct subject) from school;


+-------------------------+
| count(distinct subject) |
+-------------------------+
| 4|
+-------------------------+
1 row in set (0.00 sec)

(xv) Delete all the records of subject physics

mysql> delete from school where Subject = 'Physics';


Query OK, 2 rows affected (0.11 sec)

mysql> select * from school;


+------+--------------+-----------+------------+---------+------------+
| Code | Teacher_name | Subject | DOJ | Periods | Experience |
+------+--------------+-----------+------------+---------+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 | 10 |
| 1045 | Yasraj | Math | 2000-08-24 | 24 | 15 |
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 | 5|
| 1203 | Lasa Anand | English | 2000-08-24 | 24 | 17 |
+------+--------------+-----------+------------+---------+------------+
4 rows in set (0.00 sec)

6. Write SQL command to create a table CLUB of the following structure:

TABLE CLUB:
COLUMN NAME DATA TYPE SIZE CONSTRAINTS
COACH ID INTEGER 4 PRIMARY KEY
COACH NAME VARCHAR 20 NOT NULL
AGE INTEGER 2 >=18
SPORTS VARCHAR 20
DATE OF APP DATE
PAY DECIMAL 8,3
GENDER CHAR 2

Output:

mysql> create table CLUB(Coach_ID integer(4) primary key, Coach_name varchar(20) not null,
Age integer(2) check(Age>=18), Sports varchar(20), Date_of_app date, Pay float(8,3), Gender
char(2));
Query OK, 0 rows affected, 3 warnings (0.45 sec)
mysql> desc CLUB;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| Coach_name | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| Date_of_app | date | YES | | NULL | |
| Pay | float(8,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
7 rows in set (0.05 sec)

7. Insert the following values into table

Coach_ID Coach_name Age Sports Date_of_app Pay Gender


1 Kukreja 35 Karate 1996/03/27 1000 M
2 Ravina 34 Karate 1998/01/20 1200 F
3 Karan 34 Squash 1998/02/19 2000 M
4 Tarun 33 Basketball 1998/01/01 1500 M
5 Zubin 36 Swimming 1998/01/12 750 M
6 Ketaki 36 Swimming 1998/02/24 800 F
7 Amkita 39 Squash 1998/02/20 2200 F
8 Zareen 37 Karate 1998/02/22 1100 F
9 Kush 41 Swimming 1998/01/13 900 M
10 Sailya 37 Basketball 1998/02/19 3700 M

Output:
mysql> insert into CLUB values(1,"Kukreja",35,"Karate","1996/03/27",1000,"M"),
(2,"Ravina",34,"Karate","1998/01/20",1200,"F"),(3, "Karan", 34,"Squash",
"1998/02/19",2000,"M"),(4, "Tarun", 33, "Basketball", "1998/01/01", 1500, "M"), (5, "Zubin", 36,
"Swimming", "1998/01/12", 750, "M"), (6, "Ketaki", 3
6, "Swimming", "1998/02/24", 800, "F"), (7, "Amkita", 39, "Squash", "1998/02/20", 2200, "F"),
(8, "Zareen", 37, "Karate", "1998/02/22", 1100, "F"), (9, "Kush", 41, "Swimming", "1998/01/13",
900, "M"), (10, "Sailya", 37, "Basketball", "1998/02/19", 3700, "M");
Query OK, 10 rows affected (0.05 sec)
Records: 10 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM CLUB;

+----------+------------+------+------------+-------------+----------+--------+
| Coach_ID | Coach_name | Age | Sports | Date_of_app | Pay | Gender |
+----------+------------+------+------------+-------------+----------+--------+
| 1 | Kukreja | 35 | Karate | 1996-03-27 | 1000.000 | M |
| 2 | Ravina | 34 | Karate | 1998-01-20 | 1200.000 | F |
| 3 | Karan | 34 | Squash | 1998-02-19 | 2000.000 | M |
| 4 | Tarun | 33 | Basketball | 1998-01-01 | 1500.000 | M |
| 5 | Zubin | 36 | Swimming | 1998-01-12 | 750.000 | M |
| 6 | Ketaki | 36 | Swimming | 1998-02-24 | 800.000 | F |
| 7 | Amkita | 39 | Squash | 1998-02-20 | 2200.000 | F |
| 8 | Zareen | 37 | Karate | 1998-02-22 | 1100.000 | F |
| 9 | Kush | 41 | Swimming | 1998-01-13 | 900.000 | M |
| 10 | Sailya | 37 | Basketball | 1998-02-19 | 3700.000 | M |
+----------+------------+------+------------+-------------+----------+--------+
10 rows in set (0.00 sec)

8. Write SQL commands for the following:


(i) Modify the column pay’s size to 10,3

mysql> alter table CLUB modify column pay decimal(10,3);


Query OK, 10 rows affected (1.22 sec)
Records: 10 Duplicates: 0 Warnings: 0

mysql> desc club;


+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| Coach_name | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| Date_of_app | date | YES | | NULL | |
| pay | decimal(10,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
+-------------+---------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

(ii) Add new column address with 20 characters

mysql> alter table club add(Address varchar(20));


Query OK, 0 rows affected (0.52 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc club;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| Coach_name | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| Date_of_app | date | YES | | NULL | |
| Salary | decimal(10,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
| Address | varchar(20) | YES | | NULL | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.01 sec)

(iii) Change the name of column pay as salary.

mysql> alter table club rename column salary to Salary;


Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc club;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| Coach_name | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| Date_of_app | date | YES | | NULL | |
| Salary | decimal(10,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
| Address | varchar(20) | YES | | NULL | |
+-------------+---------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

(iv) To show all information about the swimming coaches in the club

mysql> select * from club where Sports = 'Swimming';


+----------+------------+------+----------+-------------+---------+--------+---------+
| Coach_ID | Coach_name | Age | Sports | Date_of_app | Salary | Gender | Address |
+----------+------------+------+----------+-------------+---------+--------+---------+
| 5 | Zubin | 36 | Swimming | 1998-01-12 | 750.000 | M | NULL |
| 6 | Ketaki | 36 | Swimming | 1998-02-24 | 800.000 | F | NULL |
| 9 | Kush | 41 | Swimming | 1998-01-13 | 900.000 | M | NULL |
+----------+------------+------+----------+-------------+---------+--------+---------+
3 rows in set (0.00 sec)

(v) To list the name of all coaches with their date of appointment in descending order.

mysql> select Coach_name from club order by Date_of_app desc;


+------------+
| Coach_name |
+------------+
| Ketaki |
| Zareen |
| Amkita |
| Karan |
| Sailya |
| Ravina |
| Kush |
| Zubin |
| Tarun |
| Kukreja |
+------------+
10 rows in set (0.02 sec)

(vi) To display a report showing Coach_name, Pay, Age and Bonus(15% of Pay) for all
coaches.

mysql> select Coach_name, Salary, Age, Salary*0.15 as Bonus from CLUB;


+------------+----------+------+-----------+
| Coach_name | Salary | Age | Bonus |
+------------+----------+------+-----------+
| Kukreja | 1000.000 | 35 | 150.00000 |
| Ravina | 1200.000 | 34 | 180.00000 |
| Karan | 2000.000 | 34 | 300.00000 |
| Tarun | 1500.000 | 33 | 225.00000 |
| Zubin | 750.000 | 36 | 112.50000 |
| Ketaki | 800.000 | 36 | 120.00000 |
| Amkita | 2200.000 | 39 | 330.00000 |
| Zareen | 1100.000 | 37 | 165.00000 |
| Kush | 900.000 | 41 | 135.00000 |
| Sailya | 3700.000 | 37 | 555.00000 |
+------------+----------+------+-----------+
10 rows in set (0.00 sec)
(vii)Display the number of distinct sports

mysql> select count(distinct sports) from club;


+------------------------+
| count(distinct sports) |
+------------------------+
| 4|
+------------------------+
1 row in set (0.00 sec)

(viii) Display all female coaches belonging to various sports except Karate.

mysql> select Coach_name from club where Gender = "F" and Sports!="Karate";
+------------+
| Coach_name |
+------------+
| Ketaki |
| Amkita |
+------------+
2 rows in set (0.00 sec)

(ix) Display name of all coaches whose name ends with ‘N’.

mysql> select Coach_name from Club where Coach_name like "%N";


+------------+
| Coach_name |
+------------+
| Karan |
| Tarun |
| Zubin |
| Zareen |
+------------+
4 rows in set (0.00 sec)

(x) Display the minimum and maximum age of female coaches

mysql> select min(Age), max(Age) from club where gender = "F";


+----------+----------+
| min(Age) | max(Age) |
+----------+----------+
| 34 | 39 |
+----------+----------+
1 row in set (0.01 sec)

(xi) Display the average salary of Karate coaches.

mysql> select round(avg(salary)) from club where Sports = "Karate";


+--------------------+
| round(avg(salary)) |
+--------------------+
| 1100 |
+--------------------+
1 row in set (0.02 sec)

9. Create the table Mobile Master and Mobile Stock of the following structure:

M_ID M_company M_name M_price M_Mf_Date


MB001 Samsung Galaxy 4500 2013/ 02/12
MB003 Nokia N1100 2250 2011/04/15
MB004 Micromax Unite3 4500 2016/10/17
MB005 Sony XperiaM 7500 2017/11/20
MB006 Oppo SelfieEx 8500 2010/08/21

Output:

mysql> create table MobileMaster(M_ID varchar(10) Primary key, M_company varchar(10),


M_name varchar(10), M_price float(8,3), M_Mf_Date Date);
Query OK, 0 rows affected, 1 warning (0.30 sec)
mysql> desc MobileMaster;
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| M_ID | varchar(10) | NO | PRI | NULL | |
| M_company | varchar(10) | YES | | NULL | |
| M_name | varchar(10) | YES | | NULL | |
| M_price | float(8,3) | YES | | NULL | |
| M_Mf_Date | date | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.03 sec)
mysql> insert into MobileMaster values("MB001","Samsung","Galaxy",4500,"2013/02/12"),
("MB003","Nokia", "N100", 2250, "2011/04/15"),("MB004", "Micromax", "Unite3", 4500,
"2016/10/17"),( "MB005","Sony", "XperiaM", 7500, "2017/11/20"), ("MB006", "Oppo",
"SelfieEx", 8500, "2010/08/21");
Query OK, 5 rows affected (0.05 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from MobileMaster;
+-------+-----------+----------+----------+------------+
| M_ID | M_company | M_name | M_price | M_Mf_Date |
+-------+-----------+----------+----------+------------+
| MB001 | Samsung | Galaxy | 4500.000 | 2013-02-12 |
| MB003 | Nokia | N100 | 2250.000 | 2011-04-15 |
| MB004 | Micromax | Unite3 | 4500.000 | 2016-10-17 |
| MB005 | Sony | XperiaM | 7500.000 | 2017-11-20 |
| MB006 | Oppo | SelfieEx | 8500.000 | 2010-08-21 |
+-------+-----------+----------+----------+------------+
5 rows in set (0.00 sec)

S_ID M_ID M_Qty M_Supplier


S001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile Store
S004 MB006 150 A-one Mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Center

Output:

mysql> create table mobilestock(S_ID varchar(10) Primary key, M_ID varchar(10), M_Qty
float(8,3), M_Supplier varchar(20));
Query OK, 0 rows affected, 1 warning (0.43 sec)
mysql> desc mobilestock;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| S_ID | varchar(10) | NO | PRI | NULL | |
| M_ID | varchar(10) | YES | | NULL | |
| M_Qty | float(8,3) | YES | | NULL | |
| M_Supplier | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> insert into Mobilestock values("S001","MB004",450,"New vision"),("S002","MB003",


250, "Praveen Gallery"),("S003", "MB001", 300, "Classic Mobile Store"),( "S004","MB006",
150, "A-one Mobiles"), ("S005", "MB003", 150, "The Mobile"),(“S006”, “MB006”, 50, “Mobile
Center”);
Query OK, 5 rows affected (0.05 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> select * from mobilestock;


+------+-------+---------+----------------------+
| S_ID | M_ID | M_Qty | M_Supplier |
+------+-------+---------+----------------------+
| S001 | MB004 | 450.000 | New Vision |
| S002 | MB003 | 250.000 | Praveen Gallery |
| S003 | MB001 | 300.000 | Classic Mobile Store |
| S004 | MB006 | 150.000 | A-one Mobiles |
| S005 | MB003 | 150.000 | The Mobile |
| S006 | MB006 | 50.000 | Mobile Center |
+------+-------+---------+----------------------+
6 rows in set (0.00 sec)

9. Write SQL commands for the following questions based on the above tables
(i)Display the Mobile Company, Mobile name and price in descending order of their
manufacturig date.

mysql> select M_company, M_name, M_price from mobilemaster order by M_Mf_Date desc;
+-----------+----------+----------+
| M_company | M_name | M_price |
+-----------+----------+----------+
| Sony | XperiaM | 7500.000 |
| Micromax | Unite3 | 4500.000 |
| Samsung | Galaxy | 4500.000 |
| Nokia | N100 | 2250.000 |
| Oppo | SelfieEx | 8500.000 |
+-----------+----------+----------+
5 rows in set (0.00 sec)

(ii) List the details of mobile whose name starts with “S”

mysql> select * from mobilemaster where M_name like "S%";


+-------+-----------+----------+----------+------------+
| M_ID | M_company | M_name | M_price | M_Mf_Date |
+-------+-----------+----------+----------+------------+
| MB006 | Oppo | SelfieEx | 8500.000 | 2010-08-21 |
+-------+-----------+----------+----------+------------+
1 row in set (0.02 sec)

(iii) Display the mobile supplier and quantity of all mobiles except “MB003”

mysql> select M_Supplier, M_Qty from mobilestock where M_ID != "MB003";


+----------------------+---------+
| M_Supplier | M_Qty |
+----------------------+---------+
| New Vision | 450.000 |
| Classic Mobile Store | 300.000 |
| A-one Mobiles | 150.000 |
| Mobile Center | 50.000 |
+----------------------+---------+
4 rows in set (0.00 sec)

(iv) To display the name of the mobile company price between 3000 and 5000.

mysql> select M_company from MOBILEMASTER WHERE M_price > 3000 and
M_price<5000;
+-----------+
| M_company |
+-----------+
| Samsung |
| Micromax |
+-----------+
2 rows in set (0.00 sec)

10. Create the tables TRAINER and COURSE of the following structure:

TABLE: TRAINER
TID TNAME CITY HIREDATE SALARY
101 Sunaina Mumbai 1998-10-15 90000
102 Anamika Delhi 1994-12-24 80000
103 Deepti Chandigarh 2001-12-21 82000
104 Meenakshi Delhi 2002-12-25 78000
105 Richa Mumbai 1996-01-12 95000
106 Maniprabha Chennai 2001-12-12 69000

Output:

mysql> create table TRAINER(TID integer(3) primary key, TNAME varchar(10), CITY
varchar(10), HIREDATE date, Salary float(8,3));
Query OK, 0 rows affected, 2 warnings (0.36 sec)

mysql> desc TRAINER;

+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| TID | int | NO | PRI | NULL | |
| TNAME | varchar(10) | YES | | NULL | |
| CITY | varchar(10) | YES | | NULL | |
| HIREDATE | date | YES | | NULL | |
| SALARY | float(8,3) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> insert into trainer values(101,"Sunaina", "Mumbai", "1998-10-15", 90000), (102,


"Anamika", "Delhi", "1994/12/24", 80000), (103, "Deepti", "Chandigarh", "2001/12/21", 82000),
(104, "Meenakshi", "Delhi", "2002/12/25", 78000), (105, "Richa", "Mumbai", "1996/01/12",
95000), (106, "Maniprabha", "C
hennai", "2001/12/12", 69000);
Query OK, 6 rows affected (0.06 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from trainer;


+-----+------------+------------+------------+-----------+
| TID | TNAME | CITY | HIREDATE | SALARY |
+-----+------------+------------+------------+-----------+
| 101 | Sunaina | Mumbai | 1998-10-15 | 90000.000 |
| 102 | Anamika | Delhi | 1994-12-24 | 80000.000 |
| 103 | Deepti | Chandigarh | 2001-12-21 | 82000.000 |
| 104 | Meenakshi | Delhi | 2002-12-25 | 78000.000 |
| 105 | Richa | Mumbai | 1996-01-12 | 95000.000 |
| 106 | Maniprabha | Chennai | 2001-12-12 | 69000.000 |
+-----+------------+------------+------------+-----------+
6 rows in set (0.00 sec)

TABLE COURSE

CID CNAME FEES STARTDATE TID


C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 102
C203 DCA 10000 2018-10-01 103
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 105
C206 O LEVEL 18000 2018-07-25 106

Output:
mysql> create table COURSE(CID varchar(10) Primary key, CNAME varchar(20), FEES int,
STARTDATE date, TID int);
Query OK, 0 rows affected (0.81 sec)

mysql> desc course;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| CID | varchar(10) | NO | PRI | NULL | |
| CNAME | varchar(20) | YES | | NULL | |
| FEES | int | YES | | NULL | |
| STARTDATE | date | YES | | NULL | |
| TID | int | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.04 sec)

mysql> insert into course values("C201", "AGDCA", 120000, "2018/07/02", 101), ("C202",
"ADCA", 15000, "2018/07/15", 102), ("C203", "DCA", 10000, "2018/10/01", 103), ("C204",
"DDTP", 9000, "2018/09/15", 104), ("C205", "DHN", 20000, "2018/08/01", 105), ("C206", "O
LEVEL", 18000, "2018/07/25", 106);
Query OK, 6 rows affected (0.10 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from course;

+------+---------+-------+------------+------+
| CID | CNAME | FEES | STARTDATE | TID |
+------+---------+-------+------------+------+
| C201 | AGDCA | 12000 | 2018-07-02 | 101 |
| C202 | ADCA | 15000 | 2018-07-15 | 102 |
| C203 | DCA | 10000 | 2018-10-01 | 103 |
| C204 | DDTP | 9000 | 2018-09-15 | 104 |
| C205 | DHN | 20000 | 2018-08-01 | 105 |
| C206 | O LEVEL | 18000 | 2018-07-25 | 106 |
+------+---------+-------+------------+------+
6 rows in set (0.00 sec)

11. Write SQL commands for the following questions based on the above tables
(i) Display the trainer name, city and salary in descending order of their hire.

mysql> select TNAME, CITY, SALARY from TRAINER order by HIREDATE desc;
+------------+------------+-----------+
| TNAME | CITY | SALARY |
+------------+------------+-----------+
| Meenakshi | Delhi | 78000.000 |
| Deepti | Chandigarh | 82000.000 |
| Maniprabha | Chennai | 69000.000 |
| Sunaina | Mumbai | 90000.000 |
| Richa | Mumbai | 95000.000 |
| Anamika | Delhi | 80000.000 |
+------------+------------+-----------+
6 rows in set (0.00 sec)

(ii) To display the TNAME and CITY of trainer who joined the institute in the month of
December 2001.
mysql> select TNAME, CITY from trainer where hiredate between "2001/12/01" and
"2001/12/31";
+------------+------------+
| TNAME | CITY |
+------------+------------+
| Deepti | Chandigarh |
| Maniprabha | Chennai |
+------------+------------+
2 rows in set (0.00 sec)

(iii) To display TNAME, HIREDATE , CNAME , STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.

mysql> select TNAME, HIREDATE, CNAME,STARTDATE from trainer, course where


trainer.TID = course.TID and FEES<=10000;
+-----------+------------+-------+------------+
| TNAME | HIREDATE | CNAME | STARTDATE |
+-----------+------------+-------+------------+
| Deepti | 2001-12-21 | DCA | 2018-10-01 |
| Meenakshi | 2002-12-25 | DDTP | 2018-09-15 |
+-----------+------------+-------+------------+
2 rows in set (0.00 sec)

(IV) To display the number of trainers from each city.

mysql> select city, count(*) from trainer group by city;


+------------+----------+
| city | count(*) |
+------------+----------+
| Mumbai | 2|
| Delhi | 2|
| Chandigarh | 1|
| Chennai | 1|
+------------+----------+
4 rows in set (0.00 sec)

You might also like