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

practical file cs

This document is a practical file for Computer Science (083) for the academic year 2024-25, completed by Smriti Joshi from PM SHRI KENDRIYA VIDYALAYA, NOIDA. It includes a certificate of completion for 25 practicals, an index of practical tasks, and detailed Python programs covering various topics such as file handling, data structures, and database connectivity. Each practical is dated and includes code examples demonstrating the concepts learned.

Uploaded by

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

practical file cs

This document is a practical file for Computer Science (083) for the academic year 2024-25, completed by Smriti Joshi from PM SHRI KENDRIYA VIDYALAYA, NOIDA. It includes a certificate of completion for 25 practicals, an index of practical tasks, and detailed Python programs covering various topics such as file handling, data structures, and database connectivity. Each practical is dated and includes code examples demonstrating the concepts learned.

Uploaded by

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

Computer Science

Practical File

Academic Year: 2024-25

Computer Science (083)


Name: Smriti Joshi
School: PM SHRI KENDRIYA VIDYALAYA, NOIDA

Class: XII G
Roll no.: 48
CERTIFICATE
This is to certify that I smriti joshi of Class XII G PM
shri Kendriya Vidyalaya Noida , have successfully completed 25
Practicals out of 25 Practicals in computer science for the
AISSCE as prescribed by CBSE .

Date :

Roll No. :48

Signature of Internal Signature of External


Examiner Examiner

__________________ __________________

PRINCIPAL
Index
Aim Date Sign

1. Write a program in python to check a 07.07.2024


number whether it is Prime or not using
user defined function.

2. Write a program to input a character and 08.07.2024


to print whether a given character is an
alphabet, digit or any other character.

3. Write a python function sin(x,n) to 09.07.2024


calculate the value of sin(x) using its
Taylor series expansion up to n terms.

4. Write a program to generate random 10.07.2024


numbers between 1 to 6 and check
whether a user won a lottery or not.

5. Write a program to count the number of 15.07.2024


vowels present in a text file

6. Write a program to write those lines 20.07.2024


which have the character 'p' from one
text file to another text file.

7. Write a program to count number of 22.07.2024


words in a Text file

8. Write a program to insert n records in a 24.07.2024

Page | 2
binary file student.dat.

9. . Write a program to read records from 30.07.2024


binary file student.dat.

10. Write a program to implement search 11.08.2024


operation in a binary file.

11. Write a program to update a record 14.08.2024


stored in binary file student.dat

12. Write a program to delete a record from 05.08.2024


binary file

13 Write a program to create a CSV file and 10.08.2024


read it.

14 Write a program to count umber of 15.08.2024


records from CSV file

15 Write a program to save some user id 20.08.2024


and passwords in a csv file. Ask user to
enter a user id and password, if
combination matches it should print
‘welcome’ other wise print ‘data
mismatch’

16 Write a program to insert an element in 25.08.2024


the list .

17 Write a menu based program to 30.08.2024


perform PUSH, POP and DISPLAY

Page | 3
operation on stack in python
using list.
18 Write a menu based program to 03.09.2024
perform PUSH, POP and DISPLAY
operation on stack in python
using Dictionary.
19 Write a program to connect 11.09.2024
Python with MySQL using
database connectivity and
perform the following operations
on data in
database:company(Table:employe
e) Add, Search, Update, Delete
and View complete Table.

20 Write a program to connect 12.09.2024


Python with MySQL using
database connectivity and
perform the following operations
on data in
database:Class_management(Tabl
e:Class_info) Fetch, Update and
delete the data

21 Create the following table 13.09.2024


PRODUCT in MySql and answer
the questions follows:

22 Consider following tables and 15.09.2024


answer queries (i) to (iv)
23 Consider following tables and answer 01.10.2024
queries (a) to (c) and write down the
output of (d) : -

Page | 4
24 Consider following tables and answer 16.10.2024
queries (i) to (iv): -

25 Write queries (a) to (d) based on the 03.11.2024


tables CUSTOMER and ORDER given
below:

Page | 5
1. Write a program in python to check a number whether it is Prime or not using
user defined function.

def prime(f):
i=2
while i<=f-1:
if f%i==0:
break
i=i+1
if f==i:
print("Prime")
else:
print ("Not Prime")
a=int (input ("Enter the number"))
prime(a)

Page | 6
2. Write a program to input a character and to print whether a given character is an
alphabet, digit or any other character.
ch=input ("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")

Page | 7
3. Write a python function sin(x,n) to calculate the value of sin(x) using its Taylor
series expansion up to n terms.
import math
def fact(k):
if k<=1:
return 1
else:
return k*fact(k-1)

step=int(input("How many terms : "))


x=int(input("Enter the value of x :"))
sum=0
for i in range(step+1):
sum+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)
print("The result of sin",'(', x, ')', "is :", sum)

Page | 8
4. Write a program to generate random numbers between 1 to 6 and check
whether a user won a lottery or not.
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

Page | 9
5. Write a program to count the number of vowels present in a text file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for f1 in f.read():
if f1=='a'or f1=='e'or f1=='i'or f1=='o‘ or f1=='u':
count=count+1
print(count)
f.close()

Page | 10
6. Write a program to write those lines which have the character 'p' from one text
file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines()
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
7. Write a program to count number of words in a Text file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for word in f.read().split():
count=count+1
print(count)
f.close()

Page | 11
8. Write a program to insert n records in a binary file student.dat.
import pickle
ch='y'
f = open('d:/student.dat','wb')
while ch=='y':
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks'))
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
pickle.dump(rec,f)
ch=input("more entry?")
f.close()

Page | 12
9. Write a program to read records from binary file student.dat.

import pickle
f = open('d:/student.dat','rb')
while True:
try:
rec = pickle.load(f)
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
except EOFError:
break
f.close()

Page | 13
10. Write a program to implement search operation in a binary file.

import pickle
f = open('d:/student.dat','rb')
flag = False
r=int(input("Enter rollno to be searched"))
while True:
try:
rec = pickle.load(f)
if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()

Page | 14
11. Write a program to update a record stored in binary file student.dat.

import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be updated"))
m=int(input("enter correct marks"))
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
for i in range (len(reclst)):
if reclst[i]['Rollno']==r:
reclst[i]['Marks'] = m
f = open('d:/student.dat','wb')
for x in reclst:
pickle.dump(x,f)
f.close()

Page | 15
12. Write a program to delete a record from binary file.

import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be deleted"))
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f = open('d:/student.dat','wb')
for x in reclst:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()

Page | 16
13. Write a program to create a CSV file and read it.

import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP Name""%10s"%"Salary")
print(" ")
for row in myreader:
if len(row)!=0:

print("%10s"%row[0],"%15s"%row[1],"%10s"%row[2])
Note:
1. Create a notepad file myfile.csv in d:\. Write data for
file with comma separated.
2. Go to Tools->Folder Option->view->uncheck hide
extension for unknown file types
3. Rename myfile.csv.txt -> myfiel.csv

Page | 17
14. Write a program to count umber of records from CSV file.

import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
count=0
print("%10s"%"EMPNO","%20s"%"EMP
Name""%10s"%"Salary")
print(" ")
for row in myreader:
if len(row)!=0:

print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])
count=count+1
print(" ")
print("%30s"% "Total Records are:", count)
print(" ")

Page | 18
15. Write a program to save some user id and passwords in a csv file. Ask user to
enter a user id and password, if combination matches it should print ‘welcome’
other wise print ‘data mismatch’.

import csv
newFile=open('d:\\a.csv','w')
nfw = csv.writer(newFile)
#nfw.writerow(['user_id','password'])
ch='y'
while ch=='y':
userid=input("enter userid")
password=input("Enter password")
nfw.writerow([userid,password])
ch=input("More entry?(y/n)")
newFile.close()
newFile.close()
newFile=open('d:\\a.csv','r')
newFileReader = csv.reader(newFile)
flag=False
userid=input("enter userid")
password=input("Enter password")
for row in newFileReader:
if len(row)!=0:
if row[0]==userid and row[1]==password:
print('Welcome')
flag=True
break
if flag==False:
print(‘Either username or Password is incorrect')

Page | 19
16. Write a program to insert an element in the list.

def findpos(ar,item):
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1
for i in range(size-1):
if(ar[i]<=item and item<ar[i+1]):
pos=i+1
break
if(pos==-1 and i<=size):
pos=size
return pos
def shift(ar,pos):
ar.append(None) # add an empty element at the end
size=len(ar)
i=size-1
while i>=pos:
ar[i]=ar[i-1]
i=i-1
list=[10,20,30,40,50,60,70]
print("list in sorted order is")
print(list)
item=int(input("Enter element to be inserted:"))
position=findpos(list,item)
shift(list,position)
list[position]=item
print("The list after insertion is:",item,"is")
print(list)

Page | 20
17. Write a menu based program to perform PUSH, POP and
DISPLAY operation on stack in python using list.

s=[]
def push(a):
s.append(a)
def pop():
if(s==[]):
print("Stack Empty")
else:
print("Element Deleted is :",s.pop())
def display():
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
c="y"
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
choice=int(input("Enter your choice"))
if(choice==1):
a=input("Enter any number: ")
push(a)
elif (choice==2):
pop()

elif(choice==3):
display()
else:
print("Wrong Input")
c=input("Do you want to continue?")

Page | 21
Page | 22
18. Write a menu based program to perform PUSH, POP and
DISPLAY operation on stack in python using Dictionary.

score={'anuj':40,'sachin':55,'saurav':80,'raj':35,'ajay':42}

def PUSH():
k=input('Enter Key')
val=int(input('Enter Value'))
s={k:val}
score.update(s)
def POP():
L=list(score.keys())
print('Popped Value is:')
print('Key=',L[-1])
print('value=',score.pop(L[-1]))
def DISPLAY():
temp = dict(reversed(list(score.items())))
print("The reversed order dictionary ", temp)

c='y'
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
choice=int(input("Enter your choice"))
if(choice==1):
PUSH()
elif (choice==2):
POP()
elif(choice==3):
DISPLAY()
else:
print("Wrong Choice")
c=input("Do you want to continue?")

Page | 23
Page | 24
19. Write a program to connect Python with MySQL using
database connectivity and perform the following operations on data
in database:company(Table:employee) Add, Search, Update, Delete
and View complete Table.
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="employee")
mycursor=mydb.cursor()

def employeeadd():
L=[]
eno=int(input("Enter eno:"))
L.append(eno)
ename=input("Enter ename:")
L.append(ename)
esalary=int(input("Enter esalary:"))
L.append(esalary)
value=L
value=(eno,ename,esalary)
sql="insert into
employee(eno,ename,esalary)values(%s,%s,%s)"
mycursor.execute(sql,value)
mydb.commit()
def employeesearch():
en=int(input("Enter eno to search"))
rl=(en,)
sql="select * from employee where eno=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("Details are as follows:")
print("(eno,ename,esalary)")
for x in res:
print(x)
def employeedelete():
e=int(input("Enter the eno to delete:"))
rl=(e,)

Page | 25
sql="delete from employee where eno=%s"
mycursor.execute(sql,rl)
mydb.commit()
def employeeupdate():
e=int(input("Enter the eno to update:"))
sqll=("select * from employee where eno=%s")
rl=(e,)
value=int(input("Enter the amount to be added:"))
sql=("update employee set esalary=esalary+%s where
eno=%s")
data=(value,e)
mycursor.execute(sql,data)
mydb.commit()

def employeeview():
sql="select * from employee"
mycursor.execute(sql)
res=mycursor.fetchall()
print("(eno,ename,esalary)")
for x in res:
print(x)

def menu():
print("*************************")
print("Press 1- To add data")
print("Press 2- To search record")
print("Press 3- To delete record")
print("Press 4- To Update record")
print("Press 5- to View complete Table")
print("*************************")
userinput=int(input("Please select an option from
above"))
if(userinput==1):
employeeadd()
elif(userinput==2):
employeesearch()
elif(userinput==3):
employeedelete()

Page | 26
elif(userinput==4):
employeeupdate()
elif(userinput==5):
employeeview()
else:
print("Wrong Choice")
def runagain():
again=input("\Want to run again y/n?")
while(again=='y'):
menu()
again=input("\nWant to run again y/n?")
menu()
runagain()
print("Thanks for using Program")

Page | 27
OUTPUT

Page | 28
Page | 29
20. Write a program to connect Python with MySQL using
database connectivity and perform the following operations on data
in database:Class_management(Table:Class_info) Fetch, Update
and delete the data.

import mysql.connector
import datetime

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="Class_management")
mycursor=mydb.cursor()

def testadd():
L=[]
Rno=int(input("Enter Roll no:-"))
L.append(Rno)
Sname=input("Enter Student's name:-")
L.append(Sname)
Class=int(input("Enter Class:-"))
L.append(Class)
Dob=input("Enter DOB:-")
L.append(Dob)
Fees=float(input("Enter Fees :-"))
L.append(Fees)
Address=input("Enter Student's Address:-")
L.append(Address)
Phone_no=int(input("Enter Phone no:-"))
L.append(Phone_no)
Fname=input("Enter Father's name:-")
L.append(Fname)
Mname=input("Enter Mother's name:-")
L.append(Mname)
Sub=input("Enter Student's Subjects:-")
L.append(Sub)
value=L

Page | 30
value=(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)
sql="insert into
class_info(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mna
me,Sub)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,value)
mydb.commit()
def testsearch():
rn=int(input("Enter Roll no. to search:-"))
rl=(rn,)
sql="select * from class_info where Rno=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("Details are as follows:")

print("(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)"
)
for x in res:
print(x)
def testdelete():
r=int(input("Enter the Roll no. to delete:-"))
rl=(r,)
sql="delete from class_info where Rno=%s"
mycursor.execute(sql,rl)
mydb.commit()
def testupdate():
rr=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(rr,)
value=int(input("Enter the Roll no to update:-"))
rll=(value,)

sql=("update class_info set Rno=Rno+%s where Rno=%s")


data=(value,e)

rf=int(input("Enter the Roll no. to update:-"))


sqll=("select * from class_info where Rno=%s")
rl=(ru,)
value1=int(input("Enter the Fees to update:-"))
rll=(value1,)

Page | 31
sql=("update class_info set Fees=Fees+%s where Fees=%s")
data=(value1,e)
mycursor.execute(sql,data)
mydb.commit()
ra=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(ra,)
value2=input("Enter the Address to update:-")
rll=(value2,)

sql=("update class_info set Address=Address+%s where Address=%s")


data=(value2,e)
rp=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(rp,)
value3=int(input("Enter the Phone_no to update:-"))
rll=(value3,)

sql=("update class_info set Phone_no=Phone_no+%s where


Phone_no=%s")
data=(value,e)
def update():
print("************************************** ")
print("* Press 1- To Update Roll no * ")
print("* Press 2- To update Fees * ")
print("* Press 3- To update Address * ")
print("* Press 4- To update Phone_no * ")
print("************************************** ")
userinput=int(input("Please select an option from above"))
if(userinput==1):
value()
elif(userinput==2):
value1()
elif(userinput==3):
value2()
elif(userinput==4):
value3()

else:
print("Wrong Choice")

Page | 32
#now=datetime.datetime.now()

def menu():
print("************************************** ")
print("* Press 1- To Add Entry * ")
print("* Press 2- To Search record * ")
print("* Press 3- To Delete record * ")
print("* Press 4- To Update record * ")
print("************************************** ")
userinput=int(input("Please select an option from above"))
if(userinput==1):
testadd()
elif(userinput==2):
testsearch()
elif(userinput==3):
testdelete()
elif(userinput==4):
testupdate()

else:
print("Wrong Choice")
def runagain():
again=input("\Want to run again y/n?")
while(again=='y'):
menu()
again=input("\nWant to run again y/n?")
menu()
runagain()
print("Thanks for using Program")

Page | 33
Page | 34
21. Create the following table PRODUCT in MySql and answer the
questions follows:
TABLE : PRODUCT

P_ID ProductName Manufacturer Price


TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
PP01 Hand Wash NULL 95

i. To increase the Price of all Products by 10.


update PRODUCT set price=price+10;

Page | 35
ii. To display average price of product sorted on the basis of
Manufacturer.
select Manufacturer, avg(price) from PRODUCT group by
Manufacturer;

iii. To display minimum and maximum Price of product


Manufacturer wise.
select manufacturer, min(price), max(price) from
PRODUCT group by Manufacturer;

iv. To display details of product having name ends with ‘h’.


select * from product where ProductName like '%h';

Page | 36
v. To display product name and price of product having P_ID
either BS01 or FW12.
select ProductName,Price from product where P_ID
in('BS01','FW12');

vi. To display manufacturer wise sum of Price in descending


order of Price.
select Manufacturer, sum(Price) from PRODUCT group by
manufacturer order by sum(price) desc;

vii. To count and print unique Manufacturer.


Select count(distinct Manufacturer) from PRODUCT;

Page | 37
viii. To print average Price of product from manufacturer either
‘ABC’ or ‘XYZ’.
select avg(price) from PRODUCT where Manufacturer in
(‘ABC’,’XYZ’);

ix. To delete record of ‘Shampoo’.


delete from PRODUCT where ProductName=’Shampoo’;

x. To decrease the price of product by 20 of manufacturer ‘XYZ’.


update PRODUCT set Price=Price-20 where
Manufacturer=’XYZ’;

xi. To print P_ID, ProductName, price and price of 12 items as


BunchPrice.
select P_ID, ProductName,Price, Price*12 as BunchPrice
from PRODUCT;

xii. To print details of product with null manufacturer.


select * from PRODUCT where Manufacturer is null;

Page | 38
22. Consider following tables and answer queries (i) to (iv)
SUPPLIER
SNO SNAME CITY
1 ABC Pvt NEW DELHI
2 INDIA Enterprises JAIPUR
3 Deep Ltd UDAIPUR
4 G&G Corp JAIPUR

ITEM
CODE I_NAME PRICE SNO
C1 COLD DRINK 150 2
B2 BISCUITS 100 3
T3 TEA 200 1

a) Display Item code and item name whose price is more than 100 in the
descending order of price.

SELECT CODE,I_NAME FROM ITEM WHERE PRICE>100


ORDER BY PRICE DESC;

b) Show Item name and their respective supplier name.


SELECT I_NAME, SNAME
FROM SUPPLIER AS S, ITEM AS I WHERE S.SNO=I.SNO;

c) Display Supplier no, supplier name who have supplied item for which item code
is B2.

SELECT SNO, SNAME


FROM SUPPLIER AS S, ITEM AS I WHERE S.SNO=I.SNO AND CODE=”B2”;

d) List the Item name, price, and supplier name of item(s) which have been supplied
by a supplier
of JAIPUR.

SELECT I_NAME,PRICE, SNAME


FROM SUPPLIER AS S, ITEM AS I WHERE S.SNO=I.SNO AND CITY=”JAIPUR”;

Page | 39
23. Consider following tables and answer queries (a) to (c) and write down
the output of (d) : -
CUSTOMER
Cust_I CNAME GENDE CITY CLUB_I
D R D
C01 DEVESH M NEW 101
DELHI
C02 SURAJ M JAIPUR 102
C03 SHEELA F UDAIPUR 102
C04 MEENAKS F JAIPUR 101
HI
C04 AAKRITI F UDAIPUR 103

CLUB
CLUB_ID CLUB_NAME FEES
101 YOGA 800
102 MUSIC 1000
103 SPORTS 2000

a) Display Customer name along with their respective club name.


b) Show Customer name, customer id who have joined MUSIC Club.
c) Display Customer name, gender and club name of all customers who live in
JAIPUR.
d) SELECT CNAME,CLUB_NAME FROM CUSTOMER,CLUB
WHERE CUSTOMER.CLUB_ID=CLUB.CLUB_ID and GENDER =”M”;

a) SELECT CNAME,CLUB_NAME FROM CUSTOMER,CLUB


WHERE CUSTOMER.CLUB_ID=CLUB.CLUB_ID;

b) SELECT CUST_ID,CNAME FROM CUSTOMER,CLUB


WHERE CUSTOMER.CLUB_ID=CLUB.CLUB_ID and CLUB_NAME=”MUSIC”;

c) SELECT CNAME,GENDER,CLUB_NAME
FROM CUSTOMER,CLUB

WHERE CUSTOMER.CLUB_ID=CLUB.CLUB_ID and CITY=”JAIPUR”;


d)
CNAME CLUB_NAME

DEVESH YOGA

SURAJ MUSIC

Page | 40
24. Consider following tables and answer queries (i) to (iv): -
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL CLERK 15000 D03
SHARMA
1002 MUKESH ELECTRICIAN 11000 D01
VYAS
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOCATION MANAGER
D01 PRODUCTION GROUND FLOOR D K JAIN
D02 ACCOUNTS 1ST FLOOR S ARORA
D03 SECURITY 1ST FLOOR R K SINGH
a) How many departments are there on the first floor?
b) Display Worker name and their respective jobs whose name contains the string
‘ESH’.
c) Display the average salary of workers who are working in the “PRODUCTION”
department.
d) Display Worker name, Job and their respective manager.

a) SELECT COUNT(*) FROM DEPT WHERE Location=”1ST FLOOR”;

b) SELECT WNAME, JOB FROM WORKER WHERE WNAME LIKE ”%ESH%”;

c) SELECT AVG(SALARY) FROM WORKER NATURAL JOIN DEPT


WHERE DNAME=”PRODUCTION”;

d) SELECT WNAME, JOB, MANAGER FROM WORKER W, DEPT D WHERE


W.DNO=D.DNO;

Page | 41
25. Write queries (a) to (d) based on the tables CUSTOMER and ORDER
given below:
TABLE:CUSTOMER
CUSTOMERID CUSTOMERNAME CITY COUNTRY
101 AMAN JAIPUR INDIA
102 SURESH BARANG GERMANY
103 ANAND RODIX MEXICO
104 RISHABH TENDA GERMANY
105 AARYAN KOTA INDIA
TABLE:ORDER
ORDERID CUSTOMERID ORDERDATE
1 101 12/5/2016
2 102 3/8/1990
3 101 21/9/2020
(a) To display customer name with their order id.
(b) To display the total number of customers country-wise.
(c) To display customer names in ascending order who have placed orders.
(d) To display the total number of customers whose city name starts with “J”.

(a)
SELECT CUSTOMERNAME,ORDERID FROM CUSTOMER,ORDER
WHERE CUSTOMER.CUSTOMERID=ORDER.CUSTOMERID;
(b)
SELECT COUNTRY,COUNT(*) FROM CUSTOMER
GROUP BY COUNTRY;
(c)
SELECT CUSTOMERNAME FROM CUSTOMER,ORDER
WHERE CUSTOMER.CUSTOMERID=ORDER.CUSTOMERID
ORDER BY CUSTOMERNAME;
(d)
SELECT COUNT(*)
FROM CUSTOMER
WHERE CITY LIKE ”J%”;

*********************************************

Page | 42

You might also like