0% found this document useful (0 votes)
7 views

sc

Uploaded by

vaibhaviverma79
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

sc

Uploaded by

vaibhaviverma79
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

PYTHON

PROGRAMS
1.Write a program to create a random number generator
that generates a number between 1 and 6 (simulates a
dice):

Concept used:
import, random module, function, return

Source Code:

import random
def func():
a=random.randint(1,6)
return a
print('Number is: ',func())

OUTPUT:
Number is: 4

1
2.Write a program to create a function that takes a
number n and then returns a randomly generated number
having exactly n digits.

Concepts used:
import, random module, function, print()

Source Code:

import random
def func1(n):
start=10**(n-1)
stop=10**n
a=random.randrange(start,stop)
print("Random number generated is:",a)
func1(int(input("Enter number of digits: ")))

OUTPUT:
Enter number of digits: 4
Random number generated is: 4709

2
3.Write a program to create a function that takes two
numbers and returns the number that has minimum ones
digit.

Concepts used:
function, if and else, print()

Source Code:

def func(a,b):
a1=a%10
b1=b%10
if a1<b1:
return a
else:
return b

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


b=int(input("Enter second number: "))

print('The number with minimum ones digit is:',func(a,b))

OUTPUT:
Enter first number: 12
Enter second number: 34
The number with minimum ones digit is: 12

3
4.Write a program that generates a series using a
function which takes first and last values of the
series and then generates 4 terms that are equidistant.

Concepts used:
function, return, print()

Source Code:

def func(a,b):
s=(b-a)
i=(s/3)
w,x,y,z=a,a+i,a+(2*i),(a+3*i)
return w,x,y,z

a1=int(input("Enter first number: "))


b1=int(input("Enter last number: "))
print('The series is:', func(a1,b1))

OUTPUT:
Enter first number: 1
Enter last number: 7
The series is: (1, 3.0, 5.0, 7.0)

4
5. Write a program to read a text file line by line and
display each word separated by a hash(#).

Concepts used:
open(), readlines(), for loop, print(), close()

Source Code:
f=open("prac1.txt",'r')
l=''
re=f.readlines()
for i in re:
a=i.split()
for j in a:
l+=j
l+='#'
print(l[:-1])
f.close()

OUTPUT:
computer#science#is#really#fun

5
6.Write a program to read a text file and display the
number of vowels/consonants/uppercase/lowercase
characters in the file.

Concepts used:
open(), readlines(), for loop, if and else, print(),
close()

Source Code:
f=open("prac2.txt",'r')

vow='aeiouAEIOU'

v=0
c=0
up=0
low=0

re=f.readlines()
for i in re:
b=i.split()
for j in b:
for z in j:
if z in vow:
v+=1
else:
c+=1
if z.isupper():
up+=1
else:
low+=1

print('vowels:',v)
print('consonants:',c)
print('uppercase:',up)
print('loweercase:',low)

f.close()

6
#Sample Data

OUTPUT:
vowels: 25
consonants: 35
uppercase: 0
lowercase: 60

7
7.Write a program to remove all the lines that contain
the character (‘a’) in a file and write it to another
file.

Concepts used:
open(), readlines(), for loop, if and else, print(),
close()

Source Code:
f=open('prac7.txt','r')
f1=open('prac7a.txt','w')
a=f.readlines()
for i in a:
if 'a' not in i:
f1.write(i)

f1=open('prac7a.txt','r')
print(f1.read())
f.close()
f1.close()

#Sample data OUTPUT:

8
8.Create a binary file with name and roll number.
Search for a given roll number and display the name and
if not found, display appropriate message

Concepts used:
import, pickle module, dump(), load(), open(), for
loop, try and except, while loop, if and else, print(),
break

Source Code:
import pickle
f=open('prac8.dat','wb')

n=int(input("No. of records: ")) #Creating records

for i in range (n):


rno=int(input("Roll No.: "))
name=input("Name: ")
pickle.dump([rno,name],f)

f=open('prac8.dat','rb')
r_inp=int(input("Enter roll no. to search: "))
try:
while True:
data=pickle.load(f)
if data[0]==r_inp:
print(data)
break

except EOFError:
print("No such record found")

OUTPUT:
No. of records: 3
Roll No.: 1
Name: Riya
Roll No.: 2
Name: Rahul

9
Roll No.: 3
Name: Thomas
Enter roll no. to search: 3
[3, 'Thomas']
9) Write a program to create a binary file with roll
number, name and marks. Input a roll no. and update the
marks.

Concepts used:
import, pickle module, dump(), load(), seek(), open(),
for loop, try and except, while loop, if and else,
print(), break

Source Code:
import pickle
f=open('prac9.dat','wb')

rec=[]
while True:
rno=int(input("Roll No.: "))
name=input("Name: ")
mar=int(input("Marks: "))
data=[rno,name,mar]
rec.append(data)

a=input("Do you want to continue y/n: ")


if a=='n':
break
pickle.dump(rec,f)

f=open('prac9.dat','rb+')
f.seek(0)
found=0

r_inp=int(input("Enter roll no. to update: "))


t=pickle.load(f)
for i in t:
if i[0]==r_inp:
i[2]=input("Enter new marks: ")
found=1

10
f.seek(0)
pickle.dump(t,f)

if found==0:
print("Not found")

f.seek(0)
try:
while True:
data=pickle.load(f)
print(data)
break

except EOFError:
print("No such record found")
f.close()

OUTPUT:
Roll No.: 1
Name: Aarav
Marks: 25
Do you want to continue y/n: y
Roll No.: 2
Name: Ria
Marks: 89
Do you want to continue y/n: y
Roll No.: 3
Name: Thomas
Marks: 99
Do you want to continue y/n: n
Enter roll no. to update: 3
Enter new marks: 100
[[1, 'Aarav', 25], [2, 'Ria', 89], [3, 'Thomas', '100']]

11
10.Create a CSV file by entering user ID and password,
read and search the password for given user ID.

Concepts used:
import, csv module, open(), for loop, if and else,
print()

Source Code:
import csv

f=open('prac10a.csv','w',newline='')
wo=csv.writer(f)

n=int(input("How many records: "))

for i in range(n):
uid=int(input("Enter UserID: "))
pw=input("Enter password: ")
wo.writerow([uid,pw])

f.close()
f1=open('prac10a.csv','r')
r1_uid=input("Enter UserID to search: ")
ro=csv.reader(f1)
for i in ro:
if i[0]==r1_uid:
print("Password: ",i[-1])
f1.close()

OUTPUT:
How many records: 2
Enter UserID: 123
Enter password: uxw*32
Enter UserID: 980
Enter password: pl$%sWR
Enter UserID to search: 123
Password: uxw*32

12
11.Write a function that reads a CSVfile and creates
another CSV file with same content but with a different
delimiter.

Concepts used:
import, csv module, reader(), writer(), open(), for
loop, print()

Source Code:
import csv
f=open('prac11a.csv','w',newline='')
wo=csv.writer(f)
n=int(input("How many records: "))
for i in range(n):
a=input("Enter Value 1: ")
b=input("Enter Value 2: ")
wo.writerow([a,b])
f.close()
f=open('prac11a.csv','r',newline='')
f1=open('prac11b.csv','w',newline='')

ro=csv.reader(f)
w1=csv.writer(f1,delimiter='|')

for i in ro:
print(i)
w1.writerow(i)
f1.close()

f1=open('prac11b.csv','r',newline='')
r1=csv.reader(f1)
for j in r1:
print(j)

OUTPUT:
How many records: 2

13
Enter Value 1: a
Enter Value 2: b
Enter Value 1: c
Enter Value 2: d
['a', 'b']
['c', 'd']
['a|b']
['c|d']

14
12.Program to create CSV file and store empno., name,
salary and search any empno and display name, salary,
and if not found, appropriate message

Concepts used:
import, csv module, reader(), writer(), open(), for
loop, while loop, print()

Source Code:
import csv
f=open('prac12.csv','w',newline='')
wo=csv.writer(f)

length=int(input("How many records: "))

for i in range(length):
empno=input("Enter empno: ")
name=input("Enter name: ")
sal=input("Enter salary: ")
wo.writerow([empno,name,sal])
f.close()

f=open('prac12.csv','r',newline='')
emp=input("Search empno: ")
ro=csv.reader(f)
c=0
for i in ro:
if i[0]==emp:
print("Name: ",i[1])
print("Salary: ",i[2])
break
c+=1
if c==length:
print("No such record found")

OUTPUT:
How many records: 3
Enter empno: 1
Enter name: Rahul

15
Enter salary: 10000
Enter empno: 2
Enter name: Ria
Enter salary: 15000
Enter empno: 3
Enter name: Thomas
Enter salary: 50000
Search empno: 3
Name: Thomas
Salary: 50000

16
13.Write functions:
 To create a text file 'test.txt' with few lines of
text
 To count the number of lines starting with 'b' in
the file 'test.txt'
 To count the number of words starting with the
letter 'e' or 'g'

Concepts used:
open(), for loop, append(), writelines(), seek(),
readlines(), if and else, print()

Source Code:
f=open("test.txt",'w+')

n=int(input("How many lines: "))


l=[]
for i in range(1,n+1):
str=''
st=input("Enter line: ")
str+=st
str+='\n'
l.append(str)
f.writelines(l)
f.seek(0)

lines=f.readlines()
b=0
for i in lines:
words=i.split()
if i[0][0]=='B' or i[0][0]=='b':
b+=1
print("No. of lines starting with b: ",b)

f.seek(0)
lines=f.readlines()
eg=0
l='eEgG'

17
for i in lines:
words=i.split()
for word in words:
if word[0] in l:
eg+=1
print("No. of words starting with E or G : ",eg)

OUTPUT:
How many lines: 3
Enter line: Bottles on the ground
Enter line: Computer Science is good
Enter line: Software engineering
No. of lines starting with b: 1
No. of words starting with E or G : 3

18
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

Concepts used:
import, pickle module, open(), dump(), load(), if else
and elif, while loop, try and except, close()

Source Code:
import pickle as p
f = open(r"TELEPHONE.dat", 'wb')

l = []

while True:
tn = int(input("Enter telephone number: "))
n = input("Enter customer name: ")
a = input("Enter area: ")
l = [tn, n, a]
p.dump(l, f)
a = input("Enter more? :")
if a == 'n':

19
break
f.close()

#menu
import pickle as p

def ins():
g = open(r"TELEPHONE.dat", 'ab')
while True:
li = eval(input("Enter a list to be inserted: "))
p.dump(li,g)
a = input("Enter more?: ")
if a == 'n':
break
g.close()

def dis():
g = open(r"TELEPHONE.dat", 'rb')
while True:
try:
r = p.load(g)
print(r)
except:
g.close()

def uptele():
g = open(r"TELEPHONE.dat", 'rb+')

20
n = int(input("Enter phone number to search record: "))
l = []
while True:
try:
r = p.load(g)
if r[0] == n:
name = input("Enter new name: ")
r[1] = name
area = input("Enter new area: ")
r[2] = area
l.append(r)
except:
g.close()
f = open(r"TELEPHONE.dat", 'wb')
for i in l:
p.dump(i,f)
f.close()

def searchno():
g = open(r"TELEPHONE.dat", 'rb')
n = int(input("Enter phone number to search: "))
while True:
try:
r = p.load(g)
if r[0] == n:
print(r)
break
except:

21
g.close()

def delname():
g = open(r"TELEPHONE.dat", 'rb+')
name = input("Enter name to search: ")
l = []
while True:
try:
r = p.load(g)
if r[1] != name:
l.append(r)
except:
g.close()
break
f = open(r"TELEPHONE.dat", 'wb')
for i in l:
p.dump(i, f)
f.close()

o = int(input('''What do you want to do with file?


1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
'''))

22
if o == 1:
ins()
elif o == 2:
dis()
elif o == 3:
uptele()
elif o == 4:
searchno()
elif o == 5:
delname()
else:
print('Invalid option')

OUTPUT:
Enter telephone number: 23432
Enter customer name: Abhay
Enter area: A1
Enter more? :y
Enter telephone number: 34543
Enter customer name: Siddharth
Enter area: A2
Enter more? :y
Enter telephone number: 45654
Enter customer name: Shubhankar
Enter area: A3
Enter more? :y
Enter telephone number: 56765

23
Enter customer name: Anas
Enter area: A4
Enter more? :n

#option-1

What do you want to do with file?


1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
1
Enter a list to be inserted: [78987, 'Shabarinath', 'A5']
Enter more?: n

#option-2

What do you want to do with file?


1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
2
[23432, 'Abhay', 'A1']

24
[34543, 'Siddharth', 'A2']
[45654, 'Shubhankar', 'A3']
[56765, 'Anas', 'A4']
[78987, 'Shabarinath', 'A5']

#option-3
What do you want to do with file?
1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
3
Enter phone number to search record: 23432
Enter new name: Abhay H
Enter new area: A1
#option-4
What do you want to do with file?
1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
4
Enter phone number to search: 34543
[34543, 'Siddharth', 'A2']

25
#option-5

15.Write a menu driven program to implement stack


using a list data structure:
Let it have the following functions:
 To add an element
 To delete an elment
 To display stack

Concept used:
function, if else and elif, append(), pop(), peek(),
while loop, return, print()

Source Code:

def empty(st):
if len(st)==0:
return True
else:
return False

def push(st,item):
st.append(item)
top=st[-1]
st

def delete(st):
if empty(st):
return "Underflow"
else:
return st.pop()
top=st[-1]

def display(st):
if empty(st):
print("Stack Empty")

26
else:
print(st[-1],'<--Top')
for i in range(-2,-len(st)-1,-1):
print(st[i])
def peek(st):
if empty(st):
return "Stack Empty"
else:
return st[-1]

st=[]

while True:
print("----------------------------------")
print("Options:")
print("1: Add to stack")
print("2: Delete element")
print("3: Display stack")
print("4: Peek")
print("5: EXIT MENU")

ch=input("Enter choice: ")

if ch=='1':
item=int(input("Enter element: "))
push(st,item)

elif ch=='2':
ret=delete(st)
if ret=="Underflow":
print(ret)
else:
print("Popped item: ", ret)

elif ch=='3':
display(st)

elif ch=='4':
a=peek(st)
if a=="Stack Empty":
print(a)

27
else:
print("Topmost item: ",a)
elif ch=='5':
print("End of Program")
break
else:
print("Incorrect Choice. Try Again")

OUTPUT:
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 1
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 2
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 3
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack

28
4: Peek
5: EXIT MENU
Enter choice: 3
3 <--Top
2
1
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 2
Popped item: 3
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 4
Topmost item: 2
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 5
End of Program

29
16.Write a 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 integer 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, the function should return None.

Concepts used:
function, if else and elif, append(), pop(), peek(),
while loop, return, print()

Source Code:

def empty(TICKET):
if len(TICKET)==0:
return True
else:
return False

def PUSH(TICKET):
d={}
tno=int(input("Enter Ticket number: "))
pname=input("Enter passenger name: ")
d['TICKETNO']=tno
d['PNAME']=pname
TICKET.append(d)

def POP(TICKET):
if empty(TICKET):
return 'None'

30
else:
elem=TICKET.pop()
print("Popped item is: ",elem)

def display(TICKET):
if empty(TICKET):
return 'None'
else:
print(TICKET[-1],'<--Top')
for i in range(-2,-len(TICKET)-1,-1):
print(TICKET[i])
TICKET=[]
while True:
print("----------------------------------")
print("Options:")
print("1: Push detail")
print("2: Delete detail")
print("3: Display details: ")
print("4: EXIT MENU")

ch=input("Enter choice: ")


if ch=='1':
a=PUSH(TICKET)

elif ch=='2':
a=POP(TICKET)
if a=='None':
print(None)
elif ch=='3':
a=display(TICKET)
if a=='None':
print(None)
elif ch=='4':
print("End of program")
break

OUTPUT:
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 3
None
----------------------------------

31
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 122321
Enter passenger name: Riya
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 377839
Enter passenger name: Rahul
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 398430
Enter passenger name: Thomas
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 3
{'TICKETNO': 398430, 'PNAME': 'Thomas'} <--Top
{'TICKETNO': 377839, 'PNAME': 'Rahul'}
{'TICKETNO': 122321, 'PNAME': 'Riya'}
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 2
Popped item is: {'TICKETNO': 398430, 'PNAME': 'Thomas'}
----------------------------------
Options:

32
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 4
End of program

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

Concepts used:
import, mysql.connector module, connect(),
execute(), function, commit(), if else and elif

Source Code:

import mysql.connector as mycon


con=mycon.connect(host='localhost',user='root',password='my
sql')
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 name: '))
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','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])

34
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')
OUTPUT:
1.Add record
2.Display record
0.Exit
Enter choice: 1
enter employee number: 101
Enter name: John Doe
Enter Department: IT
Enter salary: 75000
##DATA SAVED##
1.Add record
2.Display record
0.Exit
Enter choice: 1
enter employee number: 102
Enter name: Jane Smith
Enter Department: HR
Enter salary: 60000
##DATA SAVED##
1.Add record
2.Display record
0.Exit
Enter choice: 2
empno name department salary
101 John Doe IT 75000
102 Jane Smith HR 60000

1.Add record
2.Display record

35
0.Exit
Enter choice: 0
#BYE#
18.Program to connect with database and search
employee number un table employee and display
record, if empno not found display appropriate
message.

Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif

Source Code:

import mysql.connector as mycon


con=mycon.connect(host='localhost',user='root',password='my
sql')
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 name: '))
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()

36
print('%10s'%'empno','%10s'%'name','%10s'%'department','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])

def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary
desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\t\tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')

37
OUTPUT:
1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 1
enter employee number: 201
Enter name: Alice Johnson
Enter Department: Marketing
Enter salary: 55000
##DATA SAVED##

1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 1
enter employee number: 202
Enter name: Bob Williams
Enter Department: Sales
Enter salary: 60000
##DATA SAVED##

1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 3
Employee searching from
###########################################

Enter empno to search: 202


EMPNO NAME DEPARTMENT
SALARY
202 Bob Williams Sales
60000
Search more? y/n: n

1.Add record
2.Display record
3.Search record

38
0.Exit
Enter choice: 3
Employee searching from
###########################################

Enter empno to search: 203


Sorry! Employee not found
Search more? y/n: n

1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 0
#BYE#

39
19.Program to connect with database and update the
employee record of entered emp.no

Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif, break
Source Code:

import mysql.connector as mycon


con=mycon.connect(host='localhost',user='root',password='my
sql')
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 name: '))
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)

40
result=ur.fetchall()

print('%10s'%'empno','%10s'%'name','%10s'%'department','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])

def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary
desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\t\tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")

def sqlupdate():
ans='y'
while ans.lower()=='y':
eno=int(input('Enter empno to update: '))
query='select * from employee2 where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\tSALARY')
for r in result:

41
print('\t\t',r[0],'\t\t',r[1],'\t\
t',r[2],'\t\t',r[3])
ans=intput('Do you want to continue? y/n: ')
if ans.lower()=='y':
d=input('Enter new department: ')
s=int(input('Enter new salary: '))
else:
break
query='update employee set dept="{}",salary={}
where empno={}'.format(d,s,eno)
ur.execute(query)
con.commit()
print("RECORD UPDATED")
ans=input("Do you want to update more records? y/n:
")

choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n4.Update record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==4:
sqlupdate()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')

OUTPUT:
1.Add record
2.Display record
3.Search record
4.Update record

42
0.Exit
Enter choice: 1
enter employee number: 301
Enter name: Kevin Parker
Enter Department: IT
Enter salary: 72000
##DATA SAVED##

1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 2
empno name department salary
301 Kevin Parker IT 72000

1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 4
Enter empno to update: 301
EMPNO NAME DEPARTMENT SALARY
301 Kevin Parker IT 72000
Do you want to continue? y/n: y
Enter new department: Marketing

43
Enter new salary: 78000
RECORD UPDATED

1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 2
empno name department salary
301 Kevin Parker Marketing 78000

1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 0
#BYE#

44
20.Program to connect with database and delete the
employee record of entered emp.no

Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif, break

Source Code:

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 no: '))
n = input('Enter name: ')
d = input('Enter Department: ')

45
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','\
t\t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\t',r[3])

def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:

46
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\t\
tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")

def sqlupdate():
ans='y'
while ans.lower()=='y':
eno=int(input('Enter empno to update: '))
query='select * from employee where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\
tSALARY')
for r in result:
print('\t\t',r[0],'\t\t',r[1],'\t\t',r[2],'\t\
t',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

47
query='update employee set dept="{}",salary={}
where empno={}'.format(d,s,eno)
ur.execute(query)
con.commit()
print("RECORD UPDATED")
ans=input("Do you want to update more records?
y/n: ")

def sqldelete():
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to delete: "))
query='select * from employee where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\
tSALARY')
for r in result:
print('\t\t',r[0],'\t\t',r[1],'\t\t',r[2],'\t\
t',r[3])
ans=input('Do you want to continue? y/n: ')
if ans.lower()=='y':
query='delete from employee where
empno={}'.format(eno)
ur.execute(query)
print('RECORD DELETED')

48
break

choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n4.Update record\n5.Delete record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==4:
sqlupdate()
elif choice==5:
sqldelete()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')

OUTPUT:
1.Add record
2.Display record
3.Search record
4.Update record

49
5.Delete record
0.Exit
Enter choice: 1
enter employee no: 101
Enter name: John Doe
Enter Department: HR
Enter salary: 50000
##DATA SAVED##

1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit
Enter choice: 5
Enter empno to delete: 101
EMPNO NAME DEPARTMENT SALARY
101 John Doe HR 50000
Do you want to continue? y/n: y
RECORD DELETED

1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit

50
Enter choice: 2
empno name department salary

1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit
Enter choice: 0
#BYE#

51
MySQL

52
SQL program 1

Write SQL command to create the following tables


FLIGHTS and FARE tables of 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 NOT NULL

NO_OF_STOPS INTEGER

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)
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.25 sec)

mysql> select * from flights;


Empty set (0.08 sec)

mysql> desc flights;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| FL_NO | char(10) | NO | PRI | NULL | |

53
| 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.04 sec)

TABLE:FARE
Column Name Data 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

Insert the following values into the table FLIGHTS


FL NO DEPARTURE ARRIVAL NO_FLIGHT NO_STOPS
S
“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
,

54
mysql> insert into flights
values('IC301','MUMBAI','DELHI',8,0);
Query OK, 1 row affected (0.07 sec)
mysql> insert into flights
values('IC799','BANGALORE','DELHI',2,1);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('MC101','INDORE','MUMBAI',3,0);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('IC302','DELHI','MUMBAI',8,0);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('AM812','KANPUR','BANGALORE',3,1);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('IC899','MUMBAI','KOCHI',1,4);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('AM501','DELHI','TRIVANDRUM',1,5);
Query OK, 1 row affected (0.07 sec)

mysql> insert into flights


values('MU499','MUMBAI','MADRAS',3,3);
Query OK, 1 row affected (0.07 sec)

55
mysql> insert into flights
values('IC701','DELHI','AHMEDABAD',4,0);
Query OK, 1 row affected (0.05 sec)

mysql> select * from flights;


+-------+-----------+------------+------------+-------------+
| 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 | BANGLORE | DELHI | 2 | 1 |
| IC899 | MUMBAI | KOCHI | 1 | 4 |
| MC101 | INDORE | MUMBAI | 3 | 0 |
| MU499 | MUMBAI | MADRAS | 3 | 3 |
+-------+-----------+------------+------------+-------------+
9 rows in set (0.00 sec)

TABLE:FARE
FL_NO AIRLINES FARE TAX
IC701 INDIAN 6500 10
AIRLINES
MU499 SAHARA 9400 5

AM501 JET AIRWAYS 13450 8


IC899 INDIAN 8300 4
AIRLINES
IC302 INDIAN 4300 9
AIRLINES
IC799 INDIAN 1050 10

56
AIRLINES
MC101 DECCAN 3500 4
AIRLINES

mysql> insert into fare values("IC701","INDIAN


AIRLINES",6500,10);
Query OK, 1 row affected (0.05 sec)

mysql> select * from fare;


+-------+-----------------+---------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+---------+-------+
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
+-------+-----------------+---------+-------+
1 row in set (0.00 sec)

mysql> insert into FARE values("MU499","SAHARA",9400,5);


Query OK, 1 row affected (0.07 sec)

mysql> insert into FARE values("AM501","JET AIRWAYS",13450,8);


Query OK, 1 row affected (0.04 sec)

mysql> insert into FARE values("IC899","INDIAN


AIRLINES",8300,4);
Query OK, 1 row affected (0.06 sec)

mysql> insert into FARE values("IC302","INDIAN


AIRLINES",4300,9);
Query OK, 1 row affected (0.05 sec)

57
mysql> insert into FARE values("IC799","INDIAN
AIRLINES",1050,10);
Query OK, 1 row affected (0.07 sec)

mysql> insert into FARE values("MC101","DECCAN


AIRLINES",3500,4);
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM FARE;


+-------+-----------------+----------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+----------+-------+
| AM501 | JET AIRWAYS | 13450.00 | 8.00 |
| IC302 | INDIAN AIRLINES | 4300.00 | 9.00 |
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
| IC799 | INDIAN AIRLINES | 1050.00 | 10.00 |
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 4.00 |
| MU499 | SAHARA | 9400.00 | 5.00 |
+-------+-----------------+----------+-------+
7 rows in set (0.00 sec)
mysql> SELECT * FROM FARE;
+-------+-----------------+----------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+----------+-------+
| AM501 | JET AIRWAYS | 13450.00 | 8.00 |
| IC302 | INDIAN AIRLINES | 4300.00 | 9.00 |
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
| IC799 | INDIAN AIRLINES | 1050.00 | 10.00 |

58
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 4.00 |
| MU499 | SAHARA | 9400.00 | 5.00 |
+-------+-----------------+----------+-------+
7 rows in set (0.00 sec)

Write SQL commands for the following questions:


Display flight no, no of flights arriving to the Delhi.

mysql> select FL_NO,NO_FLIGHTS from FLIGHTS where


ARRIVAL="Delhi";
+-------+------------+
| FL_NO | NO_FLIGHTS |
+-------+------------+
| IC301 | 8 |
| IC799 | 2 |
+-------+------------+
2 rows in set (0.00 sec)

Display all the airlines that have maximum no of


flights.

mysql> select AIRLINES,NO_FLIGHTS from FARE,FLIGHTS where


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

59
+-----------------+------------+
1 row in set (0.03 sec)

Display total fare of all the airlines

mysql> select sum(FARE) from FARE;


+-----------+
| sum(FARE) |
+-----------+
| 46500.00 |
+-----------+
1 row in set (0.14 sec)

Display departure and arrival points of flights no


IC302 and MU499

mysql> select DEPARTURE,ARRIVAL from FLIGHTS where FL_NO='IC302'


or FL_NO='MU499';
+-----------+---------+
| DEPARTURE | ARRIVAL |
+-----------+---------+
| DELHI | MUMBAI |
| MUMBAI | MADRAS |
+-----------+---------+
2 rows in set (0.01 sec)

Display number of distinct flights

60
mysql> select count(distinct(AIRLINES)) from FARE;
+---------------------------+
| count(distinct(AIRLINES)) |
+---------------------------+
| 4 |
+---------------------------+
1 row in set (0.03 sec)

Display the minimum and maximum fare of each airline

mysql> select FL_NO,AIRLINES,max(FARE),min(FARE) from fare group


by AIRLINES;
+-------+-----------------+-----------+-----------+
| FL_NO | AIRLINES | max(FARE) | min(FARE) |
+-------+-----------------+-----------+-----------+
| AM501 | JET AIRWAYS | 13450.00 | 13450.00 |
| IC302 | INDIAN AIRLINES | 8300.00 | 1050.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 3500.00 |
| MU499 | SAHARA | 9400.00 | 9400.00 |
+-------+-----------------+-----------+-----------+
4 rows in set (0.01 sec)

Increase the fare of Sahara airlines by 200

mysql> update fare set fare=fare+200 where airlines="SAHARA";


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

61
mysql> select * from fare;
+-------+-----------------+----------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+----------+-------+
| AM501 | JET AIRWAYS | 13450.00 | 8.00 |
| IC302 | INDIAN AIRLINES | 4300.00 | 9.00 |
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
| IC799 | INDIAN AIRLINES | 1050.00 | 10.00 |
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 4.00 |
| MU499 | SAHARA | 9600.00 | 5.00 |
+-------+-----------------+----------+-------+
7 rows in set (0.00 sec)

Create a report which contains FL_NO, AIRLINES, TOTAL


FARE of all airlines. Total fare is calculated as
fare+fare*tax%.

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


+-------+-----------------+----------------------+
| 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 | 8632.00 |
| MC101 | DECCAN AIRLINES | 3640.00 |

62
| MU499 | SAHARA | 10080.00 |
+-------+-----------------+----------------------+
7 rows in set (0.00 sec)

Display the details of airlines whose names start with


‘IC’

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


+-------+-----------------+---------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+---------+-------+
| IC302 | INDIAN AIRLINES | 4300.00 | 9.00 |
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
| IC799 | INDIAN AIRLINES | 1050.00 | 10.00 |
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
+-------+-----------------+---------+-------+
4 rows in set (0.02 sec)

Create a view which contains details of airlines which


are arriving in Mumbai

mysql> create view cl as select * from flights where


ARRIVAL="Mumbai";
Query OK, 0 rows affected (0.11 sec)

mysql> select * from cl;


+-------+-----------+---------+------------+-------------+
| FL_NO | DEPARTURE | ARRIVAL | NO_FLIGHTS | NO_OF_STOPS |

63
+-------+-----------+---------+------------+-------------+
| IC302 | DELHI | MUMBAI | 8 | 0 |
| MC101 | INDORE | MUMBAI | 3 | 0 |
+-------+-----------+---------+------------+-------------+
2 rows in set (0.01 sec)

Change the name of the column airlines to flight


name

mysql> create view cl as select * from flights where


ARRIVAL="Mumbai";
Query OK, 0 rows affected (0.11 sec)
mysql> select * from cl;
+-------+-----------+---------+------------+-------------+
| FL_NO | DEPARTURE | ARRIVAL | NO_FLIGHTS | NO_OF_STOPS |
+-------+-----------+---------+------------+-------------+
| IC302 | DELHI | MUMBAI | 8 | 0 |
| MC101 | INDORE | MUMBAI | 3 | 0 |
+-------+-----------+---------+------------+-------------+
2 rows in set (0.01 sec)

Delete the column tax

mysql> alter table FARE drop column TAX;


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

mysql> select * from fare;

64
+-------+-----------------+----------+
| FL_NO | FLIGHT_NAME | FARE |
+-------+-----------------+----------+
| AM501 | JET AIRWAYS | 13450.00 |
| IC302 | INDIAN AIRLINES | 4300.00 |
| IC701 | INDIAN AIRLINES | 6500.00 |
| IC799 | INDIAN AIRLINES | 1050.00 |
| IC899 | INDIAN AIRLINES | 8300.00 |
| MC101 | DECCAN AIRLINES | 3500.00 |
| MU499 | SAHARA | 9600.00 |
+-------+-----------------+----------+
7 rows in set (0.00 sec)

SQL program 2

Create the tables SCHOOL and ADMIN of the following


structure.

Table SCHOOL
Column Name Data Type Size Constraints
Code Integer Primary key
Teachername Varchar 20 Not null

65
Subject Char 20 Not null
DOJ Date Not null
Periods Integer
Experience Integer

mysql> create table SCHOOL(Code int primary key,


Teachername varchar(20) not null, Subject char(20) not
null, DOJ date not null, Periods int, Experience int);
Query OK, 0 rows affected (0.25 sec)

mysql> desc school;


+-------------+-------------+------+-----+---------+-------
+
| Field | Type | Null | Key | Default | Extra
|
+-------------+-------------+------+-----+---------+-------
+
| Code | int | NO | PRI | NULL |
|
| Teachername | 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.02 sec)

Table ADMIN
Column name Data Type Size Constraints
Code Integer Primary Key

66
Gender Varchar 8 Not null
Designation Char 20 Not null

mysql> create table ADMIN(Code int primary key, Gender


varchar(8) not null, Designation char(20) not null);
Query OK, 0 rows affected (0.18 sec)

mysql> desc ADMIN;


+-------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------+------+-----+---------+-------+
| Code | int | NO | PRI | NULL | |
| Gender | varchar(8) | NO | | NULL | |
| Designation | char(20) | NO | | NULL | |
+-------------+------------+------+-----+---------+-------+
3 rows in set (0.08 sec)

Insert following values into the table.

Table SCHOOL
Code Teachernam Subject DOJ Period Experienc
e s e
1001 Ravi English 2001/12/0 24 10
Shankar 3
1009 Priya Raj Physics 1998/09/1 26 12
2
1203 Lasa Anand English 2000/04/0 27 5
9
1045 Yasraj Maths 2000/08/2 24 15
4
1123 Gagan Physics 1999/07/1 28 3
6
1167 Umesh Chemistry 1998/05/1 22 5
1

mysql> insert into school values


-> (1001,"Ravi Shankar","English","2001/12/03",24,10),
-> (1009,"Priya Raj","Physics","1998/09/12",26,12),

67
-> (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","Chemistry","1998/05/11",22,5);
Query OK, 5 rows affected (0.08 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> select * from school;


+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 |
10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 |
12 |
| 1045 | Yasraj | Maths | 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-04-09 | 27 |
5 |
+------+--------------+-----------+------------+---------
+------------+
6 rows in set (0.00 sec)

Table ADMIN
Code Gender Desgination
1001 Male Vice Principal
1203 Female Coordinator
1009 Female Coordinator
1045 Male HOD
1123 Male Senior Teacher
1167 Male Senior Teacher

mysql> insert into admin values


-> (1001,"Male","Vice Principal"),

68
-> (1203,"Female","Coordinator"),
-> (1009,"Female","Coordinator"),
-> (1045,"Male","HOD"),
-> (1123,"Male","Senior Teacher"),
-> (1167,"Male","Senior Teacher");
Query OK, 6 rows affected (0.05 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.03 sec)

Write SQL commands for the following questions.

Display teacher name, periods of all teachers


whose periods are less than 25 and name starts
with either R or U

mysql> select Teachername, Periods from school where


periods <25 and (Teachername like "R%" or Teachername
like "U%");
+--------------+---------+
| Teachername | Periods |
+--------------+---------+
| Ravi Shankar | 24 |
| Umesh | 22 |
+--------------+---------+
2 rows in set (0.16 sec)

Display the contents of school table in


descending order of teacher name

69
mysql> select * from school order by Teachername desc;
+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1045 | Yasraj | Maths | 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-04-09 | 27 |
5 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 |
3 |
+------+--------------+-----------+------------+---------
+------------+
6 rows in set (0.00 sec)

Display all from table school, where period is


between 10 and 20.

mysql> select * from school order by Teachername desc;


+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1045 | Yasraj | Maths | 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-04-09 | 27 |
5 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 |
3 |
+------+--------------+-----------+------------+---------
+------------+

70
6 rows in set (0.00 sec)

mysql> select * from school where periods between 10 and


20;
Empty set (0.02 sec)

Display Teachername, Code and Designation from


tables SCHOOL and ADMIN for female teacher.

mysql> select school.Code, Teachername, Designation from


SCHOOL,ADMIN where gender="Female" and
SCHOOL.Code=ADMIN.Code;
+------+-------------+-------------+
| Code | Teachername | Designation |
+------+-------------+-------------+
| 1009 | Priya Raj | Coordinator |
| 1203 | Lasa Anand | Coordinator |
+------+-------------+-------------+
2 rows in set (0.00 sec)

Display the teacher’s name who has minimum


periods

mysql> select Teachername from school where


periods=(select min(periods) from school);
+-------------+
| Teachername |
+-------------+
| Umesh |
+-------------+
1 row in set (0.02 sec)

Increase 2 years’ 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.04 sec)

71
Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from school;


+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 |
10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 |
14 |
| 1045 | Yasraj | Maths | 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-04-09 | 27 |
7 |
+------+--------------+-----------+------------+---------
+------------+
6 rows in set (0.00 sec)

Insert a row in the ADMIN table

mysql> insert into admin


values(1011,"Female","Secretary");
Query OK, 1 row affected (0.04 sec)

Create a view of table school.

mysql> create view s1 as select * from school;


Query OK, 0 rows affected (0.11 sec)

Display the highest experience among all male


teachers.

mysql> select max(Experience) from school,admin where


gender="Male";
72
+-----------------+
| max(Experience) |
+-----------------+
| 15 |
+-----------------+
1 row in set (0.00 sec)

Display code, teachername, salary to be paid,


where salary to pay=period*507.50

mysql> select Code, Teachername, Periods*507.50 as Salary


from SCHOOL;
+------+--------------+----------+
| Code | Teachername | Salary |
+------+--------------+----------+
| 1001 | Ravi Shankar | 12180.00 |
| 1009 | Priya Raj | 13195.00 |
| 1045 | Yasraj | 12180.00 |
| 1123 | Gagan | 14210.00 |
| 1167 | Umesh | 11165.00 |
| 1203 | Lasa Anand | 13702.50 |
+------+--------------+----------+
6 rows in set (0.00 sec)

Display Code,Teachername and Subject of all


teachers who have joined the school after
01/01/1999

mysql> select Code,Teachername,Subject from school where


DOJ>"1999/01/01";
+------+--------------+---------+
| Code | Teachername | Subject |
+------+--------------+---------+
| 1001 | Ravi Shankar | English |
| 1045 | Yasraj | Maths |
| 1123 | Gagan | Physics |
| 1203 | Lasa Anand | English |
+------+--------------+---------+
4 rows in set (0.00 sec)

73
Display the highest experience in each subject

mysql> select subject, max(experience) from school group


by subject;
+-----------+-----------------+
| subject | max(experience) |
+-----------+-----------------+
| English | 10 |
| Physics | 14 |
| Maths | 15 |
| Chemistry | 5 |
+-----------+-----------------+
4 rows in set (0.01 sec)

Display teachername, designation of male


teachers.

mysql> select Teachername,Designation from school,admin


where SCHOOL.Code=ADMIN.Code and gender="Male";
+--------------+----------------+
| Teachername | Designation |
+--------------+----------------+
| Ravi Shankar | Vice Principal |
| Yasraj | HOD |
| Gagan | Senior Teacher |
| Umesh | Senior Teacher |
+--------------+----------------+
4 rows in set (0.00 sec)

Display the number of teachers in each


designation

74
mysql> select Designation,count(Teachername) from
school,admin where SCHOOL.Code=ADMIN.Code group by
designation;
+----------------+--------------------+
| Designation | count(Teachername) |
+----------------+--------------------+
| Vice Principal | 1 |
| Coordinator | 2 |
| HOD | 1 |
| Senior Teacher | 2 |
+----------------+--------------------+
4 rows in set (0.00 sec)

Display the number of distinct subjects

mysql> select count(Distinct Subject) from SCHOOL;


+-------------------------+
| count(Distinct Subject) |
+-------------------------+
| 4 |
+-------------------------+
1 row in set (0.00 sec)

Delete all the records of subject physics


mysql> delete from school where subject="Physics";
Query OK, 2 rows affected (0.18 sec)
mysql> select * from school;
+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 |
10 |
| 1045 | Yasraj | Maths | 2000-08-24 | 24 |
15 |
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 |
5 |

75
| 1203 | Lasa Anand | English | 2000-04-09 | 27 |
7 |
+------+--------------+-----------+------------+---------
+------------+
4 rows in set (0.00 sec)

SQL program 3

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

CoachName Varchar 20 Not Null

Age Integer 2 >=18

Sports Varchar 20

DateOfApp Date

Pay Decimal 8,3

Gender Char 2

mysql> create table CLUB(Coach_ID integer(4) primary key,


CoachName varchar(20) not null, Age integer(2)
check(age>=18), Sports varchar(20), DateOfApp date, Pay
decimal(8,3), Gender char(2));
Query OK, 0 rows affected, 2 warnings (0.41 sec)

mysql> desc CLUB;


+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| CoachName | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |

76
| DateOfApp | date | YES | | NULL | |
| Pay | decimal(8,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
7 rows in set (0.04 sec)
Insert the following values into table.

Table COACH
CoachI Cname Age Sports DateOfAp Pay Gende
D p r
1 Kukrej 35 Karate 27/03/199 1000 M
a 6
2 Ravina 34 Karate 20/01/199 1200 F
8
3 Karan 34 Squash 19/02/199 2000 M
8
4 Tarun 33 Basketbal 01/01/199 1500 M
l 8
5 Zubin 36 Swimming 12/01/199 750 M
8
6 Ketaki 36 Swimming 24/02/199 800 F
8
7 Amkita 39 Squash 20/02/199 2200 F
8
8 Zareen 37 Karate 22/02/199 1100 F
8
9 Kush 41 Swimming 13/01/199 900 M
8
10 Saliya 37 Basketbal 19/02/199 3700 M
l 8

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',36,'Swimming','1998/02/24',800,'F'),
-> (7,'Amkita',39,'Squash','1998/02/20',2200,'F'),
-> (8,'Zareen',37,'Karate','1998/02/11',1100,'F'),
-> (9,'Kush',41,'Swimming','1998/01/13',900,'M'),
-> (10,'Saliya',37,'Basketball','1998/02/19',3700,'M');

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

Modify the column pay size to (10,3)

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


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

mysql> desc club;


+-----------+---------------+------+-----+---------
+-------+
| Field | Type | Null | Key | Default |
Extra |
+-----------+---------------+------+-----+---------
+-------+
| Coach_ID | int | NO | PRI | NULL |
|
| CoachName | varchar(20) | NO | | NULL |
|
| Age | int | YES | | NULL |
|
| Sports | varchar(20) | YES | | NULL |
|
| DateOfApp | date | YES | | NULL |
|
| pay | decimal(10,3) | YES | | NULL |
|
| Gender | char(2) | YES | | NULL |
|
| address | varchar(20) | YES | | NULL |
|
+-----------+---------------+------+-----+---------
+-------+
8 rows in set (0.06 sec)

Add new column address with 20 characters

mysql> alter table club add column address varchar(20);

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

mysql> desc club;


+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| CoachName | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| DateOfApp | date | YES | | NULL | |
| Pay | decimal(8,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
| address | varchar(20) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
8 rows in set (0.01 sec)

Change the name of column pay as salary

mysql> alter table club rename column pay to salary;


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

mysql> desc club;


+-----------+---------------+------+-----+---------
+-------+
| Field | Type | Null | Key | Default |
Extra |
+-----------+---------------+------+-----+---------
+-------+
| Coach_ID | int | NO | PRI | NULL |
|
| CoachName | varchar(20) | NO | | NULL |
|
| Age | int | YES | | NULL |
|
| Sports | varchar(20) | YES | | NULL |
|
| DateOfApp | date | YES | | NULL |
|

79
| salary | decimal(10,3) | YES | | NULL |
|
| Gender | char(2) | YES | | NULL |
|
| address | varchar(20) | YES | | NULL |
|
+-----------+---------------+------+-----+---------
+-------+
8 rows in set (0.00 sec)

To show all information about the swimming


coaches in the club

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


+----------+-----------+------+----------+------------
+---------+--------+---------+
| Coach_ID | CoachName | Age | Sports | DateOfApp | 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)

To list the name of all coaches with their date


of appointment (DATEOFAPP) in descending order

mysql> select Coachname from CLUB order by DateOfApp


desc;
+-----------+
| Coachname |
+-----------+
| Ketaki |
| Amkita |

80
| Karan |
| Saliya |
| Zareen |
| Ravina |
| Kush |
| Zubin |
| Tarun |
| Kukreja |
+-----------+
10 rows in set (0.16 sec)

To display a report showing Coach name, Pay, Age


and Bonus (15% of pay) for all coaches

mysql> select coachname, salary, age, salary*0.15 as


bonus from club;
+-----------+----------+------+-----------+
| coachname | 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 |
| Saliya | 3700.000 | 37 | 555.00000 |
+-----------+----------+------+-----------+
10 rows in set (0.00 sec)

Display the number of distinct sports

mysql> select count(distinct Sports) from CLUB;


+------------------------+
| count(distinct Sports) |
+------------------------+
| 4 |

81
+------------------------+
1 row in set (0.01 sec)

Display all female coaches belonging to various


sports except in karate.

mysql> select CoachName from CLUB where Gender='F' and


Sports<>'Karate';
+-----------+
| CoachName |
+-----------+
| Ketaki |
| Amkita |
+-----------+
2 rows in set (0.00 sec)

Display name of all coaches whose name ends with


‘N’

mysql> select CoachName from CLUB where CoachName like


'%n';
+-----------+
| CoachName |
+-----------+
| Karan |
| Tarun |
| Zubin |
| Zareen |
+-----------+
4 rows in set (0.00 sec)

Display the minimum and maximum age of female


coaches

mysql> select min(Age),max(Age) from CLUB where


Gender='F';
+----------+----------+

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

Display the average salary of karate coaches

mysql> select round(avg(Salary),2) as 'Average Salary'


from CLUB where Sports='Karate';
+----------------+
| Average Salary |
+----------------+
| 1100.00 |
+----------------+
1 row in set (0.00 sec)

83
SQL program 4

Create the tables MOBILE MASTER of the following


structure

Table MOBILE MASTER


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

mysql> create table MOBILEMASTER(M_ID varchar(10) primary


key, M_Company varchar(10), M_Name varchar(10),M_Price int,
M_Mf_Date date);
Query OK, 0 rows affected (0.67 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 | int | YES | | NULL | |
| M_Mf_Date | date | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.01 sec)

mysql> insert into MOBILEMASTER values


-> ('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'),

84
-> ('MB006', 'Oppo', 'SelfieEx', 8500, '2010/08/21');
Query OK, 5 rows affected (0.06 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 | 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 |
+-------+-----------+----------+---------+------------+
5 rows in set (0.00 sec)

Create the tables MOBILE STOCK of the following


structure

Table MOBILE STOCK


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

mysql> create table MOBILESTOCK(S_ID varchar(5) primary


key, M_ID varchar(6), M_Qty int, M_Supplier varchar(20));
Query OK, 0 rows affected (0.38 sec)

mysql> desc MOBILESTOCK;


+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| S_ID | varchar(5) | NO | PRI | NULL | |
| M_ID | varchar(6) | YES | | NULL | |

85
| M_Qty | int | YES | | NULL | |
| M_Supplier | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.04 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, 6 rows affected (0.07 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from MOBILESTOCK;


+------+-------+-------+----------------------+
| 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 |
+------+-------+-------+----------------------+
6 rows in set (0.00 sec)

Write SQL commands for the following questions based on


the above table

Display the Mobile company, mobile name and price in


descending order of their manufacturing date

mysql> select M_Company, M_Name, M_Price from MOBILEMASTER order


by M_Mf_Date desc;
+-----------+----------+---------+
| M_Company | M_Name | M_Price |

86
+-----------+----------+---------+
| Sony | XperiaM | 7500 |
| Micromax | Unite3 | 4500 |
| Samsung | Galaxy | 4500 |
| Nokia | N1100 | 2250 |
| Oppo | SelfieEx | 8500 |
+-----------+----------+---------+
5 rows in set (0.01 sec)

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 | 2010-08-21
|
+-------+-----------+----------+---------+------------
+
1 row in set (0.00 sec)

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 |
| Classic Mobile Store | 300 |
| A-one Mobiles | 150 |
| Mobile Center | 50 |
+----------------------+-------+
4 rows in set (0.03 sec)
To display the name of mobile company having
price between 3000 and 5000

87
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)

SQL program 5

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

mysql> create table TRAINER(TID int primary key, TNAME


varchar(20) not null, CITY varchar(15), HIREDATE date, SALARY
int);
Query OK, 0 rows affected (0.35 sec)

mysql> desc trainer;


+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| TID | int | NO | PRI | NULL | |
| TNAME | varchar(20) | NO | | NULL | |

88
| CITY | varchar(15) | YES | | NULL | |
| HIREDATE | date | YES | | NULL | |
| SALARY | int | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.08 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', 'Chennai', '2001/12/12', 69000);
Query OK, 6 rows affected (0.08 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from 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 |
+-----+------------+------------+------------+--------+
6 rows in set (0.00 sec)

89
Table COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018/07/02 101
C202 ADCA 15000 2018/07/15 103
C203 DCA 10000 2018/10/01 102
C204 DDTP 9000 2018/09/15 104
C205 DHN 20000 2018/08/01 101
C206 O LEVEL 18000 2018/07/25 105

mysql> create table COURSE(CID varchar(6) primary key, CNAME


varchar(15) not null, FEES int, STARTDATE date, TID int);
Query OK, 0 rows affected (0.47 sec)

mysql> desc COURSE;


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

mysql> insert into COURSE values


-> ('C201', 'AGDCA', 12000, '2018/07/02', 101),
-> ('C202', 'ADCA', 15000, '2018/07/15', 103),
-> ('C203', 'DCA', 10000, '2018/10/01', 102),
-> ('C204', 'DDTP', 9000, '2018/09/15', 104),
-> ('C205', 'DHN', 20000, '2018/08/01', 101),

90
-> ('C206', 'O Level', 18000, '2018/07/25', 105);
Query OK, 6 rows affected (0.11 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 | 103 |
| C203 | DCA | 10000 | 2018-10-01 | 102 |
| C204 | DDTP | 9000 | 2018-09-15 | 104 |
| C205 | DHN | 20000 | 2018-08-01 | 101 |
| C206 | O Level | 18000 | 2018-07-25 | 105 |
+------+---------+-------+------------+------+
6 rows in set (0.00 sec)

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 |
| Deepti | Chandigarh | 82000 |
| Maniprabha | Chennai | 69000 |
| Sunaina | Mumbai | 90000 |

91
| Richa | Mumbai | 95000 |
| Anamika | Delhi | 80000 |
+------------+------------+--------+
2 rows in set (0.12 sec)

To display the TNAME and CITY of trainers 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)

To display TNAME, HIREDATE, CNAME, STARTDATE from


tables TRAINER and COURSE of all those courses whose
FEES is less than or equal to 10,000

mysql> select TNAME, HIREDATE, CNAME, STARTDATE from


TRAINER,COURSE where TRAINER.TID=COURSE.TID and fees <=
10000;
+-----------+------------+-------+------------+
| TNAME | HIREDATE | CNAME | STARTDATE |
+-----------+------------+-------+------------+
| Anamika | 1994-12-24 | DCA | 2018-10-01 |
| Meenakshi | 2002-12-25 | DDTP | 2018-09-15 |
+-----------+------------+-------+------------+
2 rows in set (0.00 sec)

To display the number of Trainers from each city

mysql> select CITY,count(*) from TRAINER group by CITY;

92
+------------+----------+
| CITY | count(*) |
+------------+----------+
| Mumbai | 2 |
| Delhi | 2 |
| Chandigarh | 1 |
| Chennai | 1 |
+------------+----------+
4 rows in set (0.04 sec

93

You might also like