You are on page 1of 55

KENDRIYA VIDYALAYA

ONGC RAJAHMUNDRY, A.P.

PRACTICAL FILE
COMPUTER SCIENCE
SUBJECT CODE- 083

AISSCE 2023-2024

Submitted By- Submitted To-


___________________________ Mr. P.K. SARMA
(PGT-CS)
DECLARATION

I _____________________________, bearing roll no ___________________, a student of


Class XII KV ONGC RAJAHMUNDRY, hereby declare that I own the full
responsibility for the information, results etc. provided in this Practical File.
It has been created successfully by using the Database Tool MySQL and SQL
commands at KV ONGC RAJAHMUNDRY, School in complete fulfillment of
practical (curriculum of Central Board of Secondary Education CBSE of
COMPUTER SCIENCE (083) conducted by CBSE, New Delhi for the
academic session 2023-24.

__________________________

Roll No: ___________________

Class 12

KV ONGC RAJAHMUNDRY,
CERTIFICATE

This is to certify that the Computer Science (083) Practical File has been
successfully completed by ______________________________ of Class XII, KV
ONGC RAJAHMUNDRY School for consideration in partial fulfillment of
curriculum of Central Board of Secondary Education (CBSE) of Computer
Science (083) for the award of AISSCE Practical Examination 2023-24.

I certify that this practical is up to my expectation and as per the


guidelines issued by the CBSE.

____________________ ___________________

(Examiner) (Principal)
ACKNOWLEDGEMENT

I take this opportunity to express my deep sense of gratitude to all


those who have been instrumental in preparation of this project.

I feel great pleasure to express my obligation to Principal of KV


ONGC RAJAHMUNDRY.

I am also sincerely grateful to Mr. P.K. Sarma , PGT (CS), KV ONGC


RAJAHMUNDRY for his encouragement and valuable guidance during the
entire period of work.

I would also thank all of my parents and friends for their whole
hearted support and encouragement without with this project would not
have been successful.

I could not forget Internet, Textbooks which provided me with


sufficient matter for reference.
TABLE OF CONTENT

Sr Topic Page Remark


No. No.
1 Overview of Python
2 Overview of MySQL
3 System Requirement and Specifications
Data File Handling Practical
Practical1 - To write a Python program to generate random
4 number between 1 to 6 to simulate the dice.
Practical2 - Write a program in Python language to count the
5 total number of characters "A" or "a" present in data file
LINES.TXT.
Practical3 - Write a Python Program to read a text file
6 "Story.txt" and displays the number of Vowels/ Consonants/
Lowercase / Uppercase characters in the file.
Practical4- Write a program using data file concepts to read
7 the contents of # a data file "LINES.TXT" and display the total
count of Lowercase Characters, Uppercase Characters, Digits
and No. of Special Characters present in this file.
Practical5- Write a program in python language to read the
8 contents of a text file "LINES.TXT" and display the count of
"THE" and "IS" in the data file.
Practical6- Write a program in python language to read the
10 contents of a text file "LINES.TXT" and display the total
number of words in the data file.
Practical7- Write a program in python language to read the
11 contents of a text file "LINES.TXT" and display the total
number of lines in the data file.
Practical8- To write a Python Program to Read a text file
12 "Story.txt" line # by line and display each word separated by
'#'.
Practical9- To write a python program to read lines from a
13 text file "Sample.txt" and copy those lines into another file
which are starting with an alphabet 'a' or 'A'.
Practical10- Write a Python Program to create a binary file
14 with roll number and name. Search for a given roll number
and display the name, if not found display appropriate
message.
Practical 11- Write a Python Program to create/store content
15 in a binary file “Marks.dat” with roll number, name, mark
and update/modify the mark for # a given roll number if it is
present, otherwise display appropriate message.
TABLE OF CONTENT
Sr. Topic Page Remark
No. No.
Practical 12- Write a Python Program to create/store content
16 in a binary # file “emp.dat” with empno, name, post and
salary, display sum of salaries for # the given post.
Practical 13- Write a Python program to create a CSV file to
17 store Empno, Name, Salary and search any Empno and
display Name, Salary and if not found display appropriate
message.
Practical 14- Write a Python Program to create a CSV file with
18 employee number, name and salary. #Search for given
employee number and if the given employee number is
present display its #name and salary otherwise give
appropriate message.
Practical 15- Write a Program in Python Language to create a
19 CSV file by entering userid and password, read and search
the password for given userid.
Practical 16- Write a program using data file concepts to
20 create a CSV file to store Employee Number, Employee Name
and Employee Salary. Accept Employee Number of an
employee and display Name and Salary of all Employees
whose salary is more than 50000.
Practical17- Write a menu driven program to implement a
21 STACK using a list. Menu to appear is "STACK OPERATIONS: 1.
PUSH 2. POP 3. PEEK 4. DISPLAY STACK 5. EXIT" and related
operations are to be performed as per the given choice.
Practical18- Write a Program to create a list containing
22 integer values. With separate user defined functions perform
the following operations based on this list.
● Traverse the content of the list and push the even numbers
into a stack.
● Pop and display the content of the stack.
For Example: If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
38 22 98 56 34 12
Practical19- Write a Program to create a list containing
23 integer values. With separate user defined functions perform
the following operations based on this list.
● Traverse the content of the list and push the ODD numbers
into a stack.
● Pop and display the content of the stack.
For Example: If the sample Content of the list is as follows:
N=[9,6,5,7,4]
Sample Output of the code should be:
Enter the values of List [9,6,5,7,4]
759
TABLE OF CONTENT
Sr. Topic Page Remark
No. No.
Practical20- Accept values of a dictionary containing names
24 and marks as key value pairs. Write a program, with separate
user defined functions to perform the following operations:
● Push the keys (name of the student) of the dictionary into a
stack, where the corresponding value (marks) is greater than
75.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={"OM":76,"JAI":45,"BOB":89,"ALI":65,"ANU":90,"TOM":82}
The output from the program should be:
TOM ANU BOB OM
SQL QUERIES - PRACTICALS

Practical21- SQL COMMANDS 1. Create a database named


25 practical. Create a student table with the student id, class,
section, gender, name, dob, and marks as attributes where
the student id is the primary key. To insert the details of at
least 10 students in the above table and to perform given
queries.
Practical22- SQL COMMANDS 2- Create and open Database
26 named MYORG. Create a table named Emp with given
structure. Insert the given Records and perform the given
queries.
Practical23- SQL COMMANDS 3- Create and open Database
27 named office. Open Database office. Create a table
EMPLOYEE (with structure given). Insert records of table
EMPLOYEE. Create a table DEPARTMENT (with structure
given). Insert records of table DEPARTMENT. Write queries
based on the tables EMPLOYEE and DEPARTMENT.
Practical24- SQL COMMANDS 4- Create and open Database
28 named office. Create a table EMPLOYEE (with given
structure). Insert records of table EMPLOYEE. Create a table
DEPARTMENT (with given structure). Insert records of table
DEPARTMENT. Write SQL queries based on Order by, Group
by, etc.
Practical25- SQL COMMANDS 5- Create a database named
29 purchase. Create a table shop with fields - pid integer, pname
varchar(20), price double, SID Integer. Insert 05 records in
table shop. Create a table store with fields - SID Integer,
sname varchar(20), loc varchar(20). Insert detail of 03 stores
as given below in table store. Apply queries based on GROUP
BY and JOINS.
TABLE OF CONTENT
Sr. Topic Page Remark
No. No.
PYTHON – MYSQL CONNECTIVITY BASED PRACTICAL

Practical 26- Write a program using MYSQL-PYTHON


30 database connectivity to create a database school, then
create a table student (Roll INT(4) primary key, Name
VARCHAR(20),AGE INT(2), CITY CHAR(10), MARKS INT(3), in
this database which should then store any # two records in it
and then display only those records city is "LUCKNOW".
Practical 27- Write a program using MYSQL-PYTHON
31 database connectivity to create a database school,
then create a table student in this database which
should then store any two records in it and then
display only those records where AGE<=15.
Practical 28- Write a program using MYSQL-PYTHON
32 database connectivity to create a database school,
then create a table student in this database which
# should then store any two records in it and then
display only those records # where marks>=300.
Practical 29- To write a Program using PYTHON-MYSQL
33 Connectivity to insert records in Emp table and
display the records. Use While loop to store multiple
records.
Practical 30- Write a program using MYSQL-PYTHON
34 database connectivity to create a database school, then
create a table student (Roll INT(4) primary key, Name
VARCHAR(20),AGE INT(2), CITY CHAR(10), MARKS INT(3) in
this database which should then store any two records in it
and then display only those records where city is
"LUCKNOW"
35 Bibliography
OVERVIEW OF PYTHON

Python is a general purpose, dynamic, high-level, and interpreted programming


language. It supports Object Oriented programming approach to develop applications. It
is simple and easy to learn and provides lots of high-level data structures. Guido Van
Rossum is known asthe founder of Python programming.

Features of Python:

 Python is a high level language. It is a free and open source language.

 It is an interpreted language, as Python programs are executed by an interpreter.

 Python programs are easy to understand as they have a clearly defined syntax
andrelatively simple structure.

 Python is case-sensitive. For example, NUMBER and number are not same in
Python.

 Python is portable and platform independent, means it can run on various


operatingsystems and hardware platforms.

 Python has a rich library of predefined functions.

 Python is also helpful in web development. Many popular web services


andapplications are built using Python.

 Python uses indentation for blocks and nested blocks.


OVERVIEW OF MYSQL

MySQL is a relational database management system (RDBMS). It is


pronounced as "My Sequel”. MySQL was originally founded and developed in
Sweden by David Axmark, Allan Larsson and Michael Widenius, who had worked
together since the 1980s.

Characteristics of MySQL:

● MySQL is released under an open-source license so it is customizable.


● It requires no cost or payment for its usage.
● MySQL has superior speed, is easy to use and is reliable.
● MySQL uses a standard form of the well-known ANSI-SQL standards.
MySQL is a platform independent application which works on many operating
systems like

● Windows, UNIX, LINUX etc. and have compatibility with many languages
includingJAVA, C++, PHP, PERL, etc.
● MySQL is an easy to install RDBMS and is capable of handling large data sets.

Since MySQL is released under an open-source license, it does not require any cost or
payment for its usage. Anyone can download and use this software from specific
location on Internet.
SYSTEM REQUIREMENT AND SPECIFICATIONS

Software Requirements:

Operating System Window-7 and later versions (32bit, 64 bit)


Language Java
Plateform Netbeans IDE 8.2 (min)
Database MySQL
Database driver MySQL Connector

Hardware Requirements:

Processor Pentium Dual Core (min) 32bit or 64 bit


Hard-Disk 160GB (min)
RAM 1GB (min)

Input/output Requirements:

Input Mouse (any)


Input Keyboard (any)
Output Monitor (any)
Output Printer (any)
#Practical No. 1 - To write a Python program to generate random number between 1 to 6 to simulate the dice.

Source Code:

import random
while True:
Choice=input ("\nDo you want to roll the dice (y/n) : ")
no=random. randint (1, 6)
if Choice == 'y' :
print ("\nYour Number is:", no)
else:
break

Output:
# Practical No. 2 - Write a program in Python language to count the
# total number of characters "A" or "a" present in data file LINES.TXT.

c=0
f=open("LINES.TXT","r")
rec=f.read()
l=len(rec)
for i in range(0,l,1):
if(rec[i]=='A' or rec[i]=='a'):
c=c+1;
print("Total count of A or a is = ",c)
f.close()
#Practical No. 3 - Write a Python Program to read a text file "Story.txt" and displays the number of Vowels/
Consonants/ Lowercase / Uppercase characters in the file.

Source Code:

f=open("Story.txt",'r')
Contents=f.read()
Vowels=0
Consonants=0
Lowercase=0
Uppercase=0
for ch in Contents:
if ch in 'aeiouAEIOU':
Vowels=Vowels+1
if ch in 'bedfghjklmmperstvwxyzBCDFGHJKLMNPORSTVWXYZ':
Consonants=Consonants+1
if ch.islower():
Lowercase=Lowercase+1
if ch.isupper():
Uppercase=Uppercase+1
f.close()
print("The total numbers of vowels in the file: ",Vowels)
print("The total numbers of consonants is the file: ",Consonants)
print("The total numbers of uppercase in the file: ",Uppercase)
print("The total numbers of lowercase in the file: ",Lowercase)

Content of story.txt :
Like a Joy on the heart of a sorrow.
The sunset hangs on a cloud.
# Practical No.4 - Write a program using data file concepts to read the contents of
# a data file "LINES.TXT" and display the total count of Lowercase Characters,
# Uppercase Characters, Digits and No. of Special Characters present in this file.

uc=0
lc=0
d=0
sp=0
f=open("LINES.TXT","r")
rec=f.read()
l=len(rec)
for i in range(0,l,1):
if (rec[i].islower()):
lc=lc+1
elif (rec[i].isupper()):
uc=uc+1
elif (rec[i].isdigit()):
d=d+1
else:
sp=sp+1
print(" No. of Lowercase Characters=",lc)
print(" No. of Uppercase Characters=",uc)
print(" No. of Digits=",d)
print(" No. of Special Characters=",sp)
f.close()
#Practical No.-5 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the count of "THE" and "IS" in the data file.

c=0
d=0
f=open("LINES.TXT","r")
rec=f.read()
words=rec.split(" ")
l=len(words)
for i in range(0,l,1):
if(words[i].upper()=="THE"):
c=c+1
elif(words[i].upper()=="IS"):
d=d+1
print("Total count of the =",c)
print("Total count of is =",d)
print("Total count of the and is =",(c+d))

f.close()
#Practical No.-6 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the total number of words in the data file.

f=open("LINES.TXT","r")
rec=f.read()
words=rec.split(" ")
l=len(words)
print("Total words = ",l)
f.close()
#Practical No.-7 Write a program in python language to read the contents of a
#text file "LINES.TXT" and display the total number of lines in the data file.

c=0
f=open("LINES.TXT","r")
rec=f.readline()
while rec:
c=c+1
rec=f.readline()

print("Total lines = ",c)


f.close()
#Practical No. 8- To write a Python Program to Read a text file "Story.txt" line # by line and display each word
separated by '#'.

Source Code:

f=open ("Story.txt",'r')
Contents=f.readlines()
for line in Contents:
words=line.split()
for i in words:
print(i+'#',end=' ')
print("")
f.close ()

Content of story.txt :
Like a Joy on the heart of a sorrow.
The sunset hangs on a cloud.
#Practical No. 9 - To write a python program to read lines from a text file "Sample.txt" and copy those lines into
another file which are starting with an alphabet 'a' or 'A'.

Program :
#Program No. - To write a python program to read lines from a text file "Sample.txt"
# and copy those lines into another file which are starting with an alphabet 'a' or 'A'.

F1=open("Sample.txt",'r')
F2=open("New.txt",'w')
while True:
line=F1.readline()
if line == '' :
break
if line [0] == 'a' or line[0] == 'A':
F2.write(line)

print("All lines which are starting with character 'a' or 'A' has been copied successfully into New.txt")
F1. close ()
F2. close ()

Content of story.txt :
Aeroplane was invented by the Right Brothers.
My favorite color is skyblue.
An apple a day keeps the doctor away.

Output:

Content of new.txt :
#Practical No. 10 - Write a Python Program to create a binary file with roll number and name. Search for a given
roll number and display the name, if not found display appropriate message.

Source Code :

#Write a Python Program to create a binary file with roll number and name.
#Search for a given roll number and display the name, if not found display
#appropriate message.

import pickle

def Create():
F=open ("Students.dat",'ab')
opt='y'
while opt == 'y' or opt=='Y':
RollNo=int(input('Enter roll number: '))
Name=input("Enter Name: ")
L=[RollNo,Name]
pickle.dump(L,F)
opt=input("Do you want to add another student detail (y/n) :")
F.close()

def Search():
F=open("Students.dat",'rb')
no=int(input("Enter Roll. No of student to search:"))
found=0
try:
while True:
S=pickle.load(F)
if S[0]==no:
print("The searched Roll. No is found and Details are:",S)
found=1
break
except:
F.close()

if found==0:
print("The Searched Roll. No is not found")

#Main Program
Create()
Search()
Output:
#Practical No. 11 - Write a Python Program to create/store content in a binary
# file “Marks.dat” with roll number, name, mark and update/modify the mark for
# a given roll number if it is present, otherwise display appropriate message.

Source Code:

import pickle

def Create():
F=open("Marks.dat",'ab')
opt='y'

while opt == 'y' or opt=='Y':


RollNo=int(input('Enter roll number: '))
Name=input("Enter Name: ")
Mark=int(input("Enter Marks: "))
L=[RollNo,Name,Mark]
pickle.dump(L,F)
opt=input("Do you want to add another student detail (y/n) : ")

F.close ()

def Update () :
F=open("Marks.dat",'rb+')
no=int(input("Enter Student Roll. No to modify marks: "))
found=0

try:

while True:
Pos=F.tell()
S=pickle.load(F)
if S[0]==no:
print ("The searched Roll. No is found and Details are: ",S)
S[2]=int(input("Enter New Mark to be update: "))
F.seek(Pos)
pickle.dump(S,F)
found=1
F.seek(Pos) #moving the file pointer again beginning of the current record
print("Mark updated Successfully and Details are:",S)
break

except:
F. close ( )

if found==0:
print("The Searched Roll No is not found")

#Main Program

Create()
Update()
Output:
#Practical No. 12 – Write a Python Program to create/store content in a binary
# file “emp.dat” with empno, name, post and salary, display sum of salaries for
# the given post.

import pickle
def NewEmp():
print("Enter the details of an employee : ")
no=int(input("Enter the Empno ? "))
name=input("Enter the name ? ")
post=input("Enter the post ? ")
sal=float(input("Enter the salary ? "))
rec=[no,name,post,sal]
f=open("EMP.dat","ab")
pickle.dump(rec,f)
print("New record saved")
f.close()
def SumSalary(Post):
f=open("EMP.dat","rb")
c=0
sum=0
try:
while True:
rec=pickle.load(f)
if rec[2]==Post:
sum+=rec[3]
except EOFError:
f.close()

print("Sum of salary for the post -",Post," is : ",sum)


n=int(input("Enter number of employees for which record is to be stored? "))
for k in range(1,n+1,1):
print("Enter Record ",k)
NewEmp()
pst=input("Enter post for which sum of salary is required ?")
SumSalary(pst)

Output:
#Practical No. 13 - Write a Python program to create a CSV file to store Empno, Name, Salary and search any
Empno and display Name, Salary and if not found display appropriate message.

Source Code:

#Program No. - Write a Python Program to Create a binary file with roll number, name, mark
#and update/modify the mark for a given roll number.

import csv

def Create():
F=open ("Emp.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Sal=float(input ("Enter Employee Salary: "))
L=[No,Name,Sal]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()

def Search():
F=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search : "))
found=0
row=csv.reader(F)
for data in row:
if data[0] == str(no) :
print("\nEmployee Deatils are:")
print(" ----------------------")
print("Name : ",data[1])
print("Salary: ",data[2])
print("-----------------------")
found=1
break

if found == 0:
print ("The searched Employee number is not Found")
F. close ()

#Main Program
Create ()
Search ()
Output:
#Program No. 14- Write a Python Program to create a CSV file with employee number, name and salary.
#Search for given employee number and if the given employee number is present display its
#name and salary otherwise give appropriate message.
import csv
def Create():
F=open ("Emp.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Sal=float(input ("Enter Employee Salary: "))
L=[No,Name,Sal]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()
def Search():
F=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search : "))
found=0
row=csv.reader(F)
for data in row:
if data[0] == str(no) :
print("\nEmployee Deatils are:")
print(" ----------------------")
print("Name : ",data[1])
print("Salary: ",data[2])
print("-----------------------")
found=1
break
if found == 0:
print ("The searched Employee number is not Found")
F. close ()
#Main Program
Create ()
Search ()
Output:
#Practical No. 15 – Write a Program in Python Language to create a CSV file by entering userid and password,
read and search the password for given userid.
Source Code:
#Program No. - Write a Program in Python Language to Create a CSV file by
# entering userid and password, read and search the password for given userid.

import csv
def Create():
F=open ("userid.csv",'a', newline='')
W=csv.writer(F)
opt= 'y'
while opt=='y' or opt=='Y' :
uid=input("Enter User ID: ")
pwd=input("Enter Password: ")
L=[uid,pwd]
W.writerow(L)
opt=input("Do you want to continue (y/n) ?")
F.close()

def Search():
F=open("userid.csv",'r',newline='\r\n')
user=input("Enter the User ID to search : ")
found=0
row=csv.reader(F)
for data in row:
if data[0] == user :
print("\nUser ID Details are:")
print(" ----------------------")
print("User ID : ",data[0])
print("Password: ",data[1])
print("-----------------------")
found=1
break

if found == 0:
print ("The searched User ID is not Found")
F. close ()
#Main Program
Create ()
Search ()

Output :
# Practical No.16- Write a program using data file concepts to create a CSV file
# to store Employee Number, Employee Name and Employee Salary.
# Accept Employee Number of an employee and display Name and Salary
# of all Employees whose salary is more than 50000.

import csv

with open('myfile.csv',mode='a') as csvfile:


mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number? "))
name=input("Enter Employee Name? ")
salary=float(input("Enter Employee Salary? "))
mywriter.writerow([eno,name,salary])
print("##Data Saved..##")
ans=input("Add More...Press(Y/y) ?")
ans='y'

with open('myfile.csv',mode='r') as csvfile:


myreader=csv.reader(csvfile,delimiter=',')
while ans=='y':

found=False
for row in myreader:
if len(row)!=0:
if float(row[2])>50000:
print("====================")
print("NAME : ",row[1])
print("SALARY : ",row[2])
found=True
break
if not found:
print("====================")
print(" EMPNO NOT FOUND")
print("====================")
ans=input("Search More?(Y)")
# PRACTICAL NO. 17 - Write a menu driven program to implement a STACK using a list.
# Menu to appear is "STACK OPERATIONS: 1. PUSH 2. POP 3. PEEK 4. DISPLAY STACK 5. EXIT"
# and related operations are to be performed as per the given choice.

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def disp(stk):
if isempty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])

stack=[]
top=None
while True:
print("STACK OPERATIONS:")
print("1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. DISPLAY STACK")
print("5. EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter item:"))
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Popped item is:",item)
elif ch==3:
item=peek(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Topmost item is:",item)
elif ch==4:
disp(stack)
elif ch==5:
break
else:
print("Invalid Choice")
# Practical No. 18 - Write a Program to create a list containing integer values.
# With separate user defined functions perform the
# following operations based on this list.
# ● Traverse the content of the list and push the even numbers into a stack.
# ● Pop and display the content of the stack.
# For Example:
# If the sample Content of the list is as follows:
# N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
# Sample Output of the code should be:
# 38 22 98 56 34 12

def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

N=eval(input("Enter the values of List"))


ST=[]

for k in N:
if k%2==0:
PUSH(ST,k)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
# Practical No. 19 - Write a Program to create a list containing integer values.
# With separate user defined functions perform the
# following operations based on this list.
# ● Traverse the content of the list and push the ODD numbers into a stack.
# ● Pop and display the content of the stack.
# For Example:
# If the sample Content of the list is as follows:
# N=[9,6,5,7,4]
# Sample Output of the code should be:
# Enter the values of List[9,6,5,7,4]
#759

def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

N=eval(input("Enter the values of List"))


ST=[]

for k in N:
if k%2==1:
PUSH(ST,k)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
# Practical No.20 -Accept values of a dictionary containing names and marks as
#key value pairs. Write a program, with separate user
#defined functions to perform the following operations:
#● Push the keys (name of the student) of the dictionary into a
#stack, where the corresponding value (marks) is greater than 75.
#● Pop and display the content of the stack.
#For example:
#If the sample content of the dictionary is as follows:
#R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90,"TOM":82}
#The output from the program should be:
#TOM ANU BOB OM

def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

R=eval(input("Enter the values of Dictionary"))

ST=[]

for k in R:
if R[k]>=75:
PUSH(ST,k)

print(ST)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
PRACTICAL NO. 21 – SQL COMMANDS 1.

1. Create a database named practical.


mysql> create database practical;

2. Create a student table with the student id, class, section, gender, name, dob, and marks as attributes where
the student id is the primary key.
mysql> use practical;
mysql> create table student(studentid int NOT NULL primary key, class int, section varchar(1), gender
varchar(1), name varchar(30), dob date, marks int);

3. To insert the details of at least 10 students in the above table.


mysql>insert into student values(1,11,”A”,”M”,”Aman”,”2005-04-28”,87);
mysql>insert into student values(2,11,”B”,”F”,”Priya”,”2004-06-18”,78);
mysql>insert into student values(3,11,”C”,”F”,”Supriya”,”2004-07-12”,98);
mysql>insert into student values(4,11,”A”,”M”,”Shashank”,”2004-09-10”,67);
mysql>insert into student values(5,11,”B”,”F”,”Anjali”,”2005-08-24”,86);
mysql>insert into student values(6,11,”C”,”M”,”Vikas”,”2006-05-13”,76);
mysql>insert into student values(7,11,”A”,”M”,”Bipin”,”2004-03-06”,82);
mysql>insert into student values(8,11,”B”,”F”,”Deepika”,”2005-02-15”,73);
mysql>insert into student values(9,11,”C”,”M”,”Raj”,”2004-01-30”,54);
mysql>insert into student values(10,11,”B”,”F”,”Kajal”,”2005-09-09”,66);
mysql>insert into student values(11,11,”B”,”M”,”Varun”,”2004-07-08”,65);

4. Delete the details of a particular student in the above table.


mysql> delete from student where studentid=11;

5. Increase marks by 5% for those students who have studentid is more than 20.
mysql>update student set marks=marks+0.05*marks where studentid >20;

6. Display the entire content of the table.


mysql>select * from student;

7. Display studentid, Name and Marks of those students who are scoring marks more than 50.
mysql>select studentid,name,marks from student where marks>50;

8. Find the average of marks from the student table.


mysql>select avg(marks) from student;

9. Find the number of students, who are from section ‘A’.


mysql>select count(*) from student where section=”A”;

10. Add a new column email in the above table with appropriate data type.
mysql>alter table student add column email varchar(25);

11. Add the email ids of each student in the previously created email column.
mysql>update student set email=”aman123@gmail.com” where studentid=1;
mysql>update student set email=”priya456@gmail.com” where studentid=2;
mysql>update student set email=”aman123@gmail.com” where studentid=3;
mysql>update student set email=”priya456@gmail.com” where studentid=4;
mysql>update student set email=”aman123@gmail.com” where studentid=5;
mysql>update student set email=”priya456@gmail.com” where studentid=6;
mysql>update student set email=”aman123@gmail.com” where studentid=7;
mysql>update student set email=”priya456@gmail.com” where studentid=8;
mysql>update student set email=”aman123@gmail.com” where studentid=9;
mysql>update student set email=”priya456@gmail.com” where studentid=10;

12. Display the information of all the students, whose name starts with ‘AN’ (Examples: ANAND, ANGAD,..)
mysql>select * from student where name like “AN%”;

13. Display studentid, Name, DOB of those students who are born between ‘2005- 01-01’ and ‘2005-12-31’.
mysql>select studentid,name,dob from student where dob between ‘2005- 01-01’ and ‘2005-12-31’;

14. Display studentid, Name, DOB, Marks, Email of those male students in ascending order of their names.
mysql>select studentid,name,dob,marks,email from student where gender=”M” order by name
ascending;

15. Display studentid, Gender, Name, DOB, Marks, Email in descending order of their marks.
mysql>select studentid,gender,name,dob,marks,email from student order by marks descending;

16. Display the unique section available in the table.


mysql> select distinct(section) from student;
PRACTICAL NO. 22 – SQL COMMANDS 2.

Q1. Create and open Database named MYORG.


Solution:-
mysql> CREATE DATABASE MYORG;
Query OK, 1 row affected (0.00 sec)

mysql> USE MYORG;


Database changed

Q2. Create a table name Emp with following structure :


EmpID EmpName Designation DOJ sal comm
Number Varchar(20) Varchar(10) Date Number Number
Solution:-
mysql> CREATE TABLE EMP(EmpID INT, EmpName VARCHAR(20),Designation VARCHAR(10), DOJ DATE, Sal float,
Comm float);
Query OK, 0 rows affected (0.14 sec)

Q3. Insert the following Records-


EmpID EmpName Designation DOJ Sal comm
8369 SMITH CLERK 1990-12-18 800.00 NULL
8499 ANYA SALESMAN 1991-02-20 1600.00 300.00
8521 SETH SALESMAN 1991-02-22 1250.00 500.00
8566 MAHADEVAN MANAGER 1991-04-02 2985.00 NULL
8654 MOMIN SALESMAN 1991-09-28 1250.00 400.00
8698 BINA MANAGER 1991-05-01 2850.00 NULL
8882 SHIVANSH MANAGER 1991-06-09 2450.00 NULL
8888 SCOTT ANALYST 1992-12-09 3000.00 NULL
8839 AMIR PRESIDENT 1991-11-18 5000.00 NULL
8844 KULDEEP SALESMAN 1991-09-08 1500.00 0.00

Solution:-
mysql> INSERT INTO EMP VALUES(8369,'SMITH','CLERK','1990-12-18',800,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8499,'ANYA','SALESMAN','1991-02-20',1600.00,300.00);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8521,'SETH','SALESMAN','1991-02-22',1250.00,500.00);
Query OK, 1 row affected (0.07 sec)
mysql> INSERT INTO EMP VALUES(8566,'MAHADEVAN','MANAGER','1991-04-02',2985.00,NULL);
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO EMP VALUES(8654,'MOMIN','SALESMAN','1991-09-28',1250.00,400.00);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8698,'BINA','MANAGER','1991-05-01',2850.00,NULL);
Query OK, 1 row affected (0.07 sec)
mysql> INSERT INTO EMP VALUES(8882,'SHIVANSH','MANAGER','1991-06-09',2450.00,NULL);
Query OK, 1 row affected (0.02 sec)
mysql> INSERT INTO EMP VALUES(8888,'SCOTT','ANALYST','1992-12-09',3000.00,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8839,'AMIR','PRESIDENT','1991-11-18',5000.00,NULL);
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO EMP VALUES(8844,'KULDEEP','SALESMAN','1991-09-08',1500.00,0.00);
Query OK, 1 row affected (0.06 sec)
Q4. Write a query to display all the records with all the columns.
Solution:-
mysql> SELECT * FROM EMP;

+-------+-----------+-------------+------------+------+------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
| 8499 | ANYA | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | SETH | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8654 | MOMIN | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8844 | KULDEEP | SALESMAN | 1991-09-08 | 1500 | 0 |
+-------+-----------+-------------+------------+------+------+
10 rows in set (0.00 sec)

Q5. Write a query to display EmpName and Sal of employees whose salary are greater than or equal to 2200
Solution:-
mysql> SELECT EmpName,Sal FROM EMP WHERE Sal>=2200;
+-----------+------+
| EmpName | Sal |
+-----------+------+
| MAHADEVAN | 2985 |
| BINA | 2850 |
| SHIVANSH | 2450 |
| SCOTT | 3000 |
| AMIR | 5000 |
+-----------+------+
5 rows in set (0.00 sec)

Q6. Write a query to display employee name and salary of those employees who don’t have their salary in range
of 2500 to 4000.
Solution:-
mysql> SELECT EmpName,Sal FROM EMP WHERE Sal NOT BETWEEN 2500 AND 4000;
+----------+------+
| EmpName | Sal |
+----------+------+
| SMITH | 800 |
| ANYA | 1600 |
| SETH | 1250 |
| MOMIN | 1250 |
| SHIVANSH | 2450 |
| AMIR | 5000 |
| KULDEEP | 1500 |
+----------+------+
7 rows in set (0.00 sec)

Q7. Write a query to display the name of employee whose name contains “A” as third alphabet in Ascending
order of employee names.
Solution:-
mysql> SELECT EmpName FROM EMP WHERE EmpName LIKE '_ _A%' ORDER BY EmpName;
Empty set (0.00 sec)

Q8. Write a query to display the ename and sal with 50% of sal as DA.
Solution:-
mysql> SELECT EmpName,Sal,Sal*0.50 AS DA FROM EMP;
+-----------+------+---------+
| EmpName | Sal | DA |
+-----------+------+---------+
| SMITH | 800 | 400.00 |
| ANYA | 1600 | 800.00 |
| SETH | 1250 | 625.00 |
| MAHADEVAN | 2985 | 1492.50 |
| MOMIN | 1250 | 625.00 |
| BINA | 2850 | 1425.00 |
| SHIVANSH | 2450 | 1225.00 |
| SCOTT | 3000 | 1500.00 |
| AMIR | 5000 | 2500.00 |
| KULDEEP | 1500 | 750.00 |
+-----------+------+---------+
10 rows in set (0.00 sec)

Q9. Write a query to display details of employees with the text “Not given”, if commission is null.
Solution:-
mysql> SELECT EmpID,EmpName,Designation,DOJ,Sal,'Not Given' AS 'Comm' FROM EMP WHERE Comm IS NULL;
+-------+-----------+-------------+------------+------+-----------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+-----------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | Not Given |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | Not Given |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | Not Given |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | Not Given |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | Not Given |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | Not Given |
+-------+-----------+-------------+------------+------+-----------+
6 rows in set (0.02 sec)

Q10. Display the distinct job titles offered by the Organization.


Solution:-
mysql> SELECT DISTINCT DESIGNATION FROM EMP;
+-------------+
| DESIGNATION |
+-------------+
| CLERK |
| SALESMAN |
| MANAGER |
| ANALYST |
| PRESIDENT |
+-------------+
5 rows in set (0.03 sec)
Q11. Display the Names of employees who are working as Manager or Analyst.
mysql> SELECT EmpName,DESIGNATION FROM EMP WHERE DESIGNATION IN('ANALYST','MANAGER');
+-----------+-------------+
| EmpName | DESIGNATION |
+-----------+-------------+
| MAHADEVAN | MANAGER |
| BINA | MANAGER |
| SHIVANSH | MANAGER |
| SCOTT | ANALYST |
+-----------+-------------+
4 rows in set (0.00 sec)
Q12. Display the names of employees who joined on or after 01/05/1991.
mysql> SELECT EmpName,DOJ FROM EMP WHERE DOJ>='1991-05-01';
+----------+------------+
| EmpName | DOJ |
+----------+------------+
| MOMIN | 1991-09-28 |
| BINA | 1991-05-01 |
| SHIVANSH | 1991-06-09 |
| SCOTT | 1992-12-09 |
| AMIR | 1991-11-18 |
| KULDEEP | 1991-09-08 |
+----------+------------+
6 rows in set (0.00 sec)
Q13. Display the employee records in order by DOJ.
mysql> SELECT * FROM EMP ORDER BY DOJ;
+-------+-----------+-------------+------------+------+------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
| 8499 | ANYA | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | SETH | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8844 | KULDEEP | SALESMAN | 1991-09-08 | 1500 | 0 |
| 8654 | MOMIN | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
+-------+-----------+-------------+------------+------+------+
10 rows in set (0.00 sec)
Q14. Display the Distinct Designation in the Organisation.
mysql> SELECT DISTINCT DESIGNATION FROM EMP;
+-------------+
| DESIGNATION |
+-------------+
| CLERK |
| SALESMAN |
| MANAGER |
| ANALYST |
| PRESIDENT |
+-------------+
5 rows in set (0.03 sec)
PRACTICAL NO. 23 – SQL COMMANDS 3.
Q1. Create the following Table DEPT with DeptID as Primary Key.
DeptID DeptName MgrID Location
Number Varchar Number Char(40)
Solution:-
mysql> CREATE TABLE DEPT(DeptID INTEGER PRIMARY KEY NOT NULL,DeptName VARCHAR(25), MgrID
INTEGER,Location CHAR(40));
Query OK, 0 rows affected (0.13 sec)

Q2. Insert the following record in the DEPT Table.


DeptID DeptName MgrID Location
10 SALES 8566 Mumbai
20 PERSONEL 8698 Delhi
30 ACCOUNTS 8882 Delhi
40 RESEARCH 8839 Banglore
Solution:-
mysql> INSERT INTO DEPT VALUES(10,'SALES',8566,'MUMBAI');
Query OK, 1 row affected (0.09 sec)

mysql> INSERT INTO DEPT VALUES(20,'PERSONEL',8698,'DELHI');


Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO DEPT VALUES(30,'ACCOUNTS',8882,'DELHI');


Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO DEPT VALUES(40,'RESEARCH',8839,'BANGLORE');


Query OK, 1 row affected (0.05 sec)

Q3. Alter the table EMP as Add a column DeptID (Number)


Solution:-
mysql> ALTER TABLE EMP ADD (DeptID INTEGER);
Query OK, 10 rows affected (0.23 sec)
Records: 10 Duplicates: 0 Warnings: 0

Q4. Add Foreign Key as DeptID which refers DeptID column of DEPT table.
Solution:-
mysql> ALTER TABLE EMP ADD FOREIGN KEY (DeptID)REFERENCES DEPT(DeptID);
Query OK, 10 rows affected (0.22 sec)
Records: 10 Duplicates: 0 Warnings: 0

Q5. Update DeptID of EMP Table with valid DeptIDs to link both tables.
Solution:-
mysql> UPDATE EMP,DEPT SET EMP.DEPTID=DEPT.DEPTID WHERE EMP.EMPID= DEPT.MGRID;
Query OK, 4 rows affected (0.06 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Q6. Show the minimum, maximum and average salary of Managers.


Solution:-
mysql> SELECT MIN(SAL),MAX(SAL),AVG(SAL) FROM EMP WHERE DESIGNATION='MANAGER';
+----------+----------+-----------+
| MIN(SAL) | MAX(SAL) | AVG(SAL) |
+----------+----------+-----------+
| 2450 | 2985 | 2761.6667 |
+----------+----------+-----------+
1 row in set (0.05 sec)
Q7. Count the number of Clerk in the Organization.
Solution:-
mysql> SELECT COUNT(*) FROM EMP WHERE DESIGNATION='CLERK';

+----------+
| COUNT(*) |
+----------+
| 1|
+----------+
1 row in set (0.00 sec)

Q8. Display the Designation wise list of employees with name, Sal and Date of Joining.
Solution:-
mysql> SELECT EmpName,Designation,Sal,DOJ as 'DateOfJoining'FROM EMP ORDER BY Designation;
+-----------+-------------+------+---------------+
| EmpName | Designation | Sal | DateOfJoining |
+-----------+-------------+------+---------------+
| SCOTT | ANALYST | 3000 | 1992-12-09 |
| SMITH | CLERK | 800 | 1990-12-18 |
| MAHADEVAN | MANAGER | 2985 | 1991-04-02 |
| SHIVANSH | MANAGER | 2450 | 1991-06-09 |
| BINA | MANAGER | 2850 | 1991-05-01 |
| AMIR | PRESIDENT | 5000 | 1991-11-18 |
| SETH | SALESMAN | 1250 | 1991-02-22 |
| MOMIN | SALESMAN | 1250 | 1991-09-28 |
| ANYA | SALESMAN | 1600 | 1991-02-20 |
| KULDEEP | SALESMAN | 1500 | 1991-09-08 |
+-----------+-------------+------+---------------+
10 rows in set (0.00 sec)

Q9. Count the number of employees who are not getting commission.
Solution:-
mysql> SELECT COUNT(*) FROM EMP WHERE COMM IS NULL;
+----------+
| COUNT(*) |
+----------+
| 6|
+----------+
1 row in set (0.00 sec)

Q10. Display the maximum salary of employees in each Department.


Solution:-
mysql> SELECT MAX(SAL),DESIGNATION FROM EMP GROUP BY DESIGNATION;
+----------+-------------+
| MAX(SAL) | DESIGNATION |
+----------+-------------+
| 3000 | ANALYST |
| 800 | CLERK |
| 2985 | MANAGER |
| 5000 | PRESIDENT |
| 1600 | SALESMAN |
+----------+-------------+
5 rows in set (0.00 sec)
Q11. Count the number of Employees working in ACCOUNTS department.
Solution:-
select count(*) from emp,dept where deptname='accounts' and emp.empid=dept.mgrid;
+----------+
| count(*) |
+----------+
| 1|
+----------+

Q12. Display the name of employees working in Delhi.


Solution:-
select empname from emp,dept where location= 'delhi' and emp.empid=dept.mgrid;

+----------+
| empname |
+----------+
| BINA |
| SHIVANSH |
+----------+

Q13. Display the name of employees who are working in Delhi and getting more than 2000.
Solution:-
mysql> select empname from emp,dept where location='delhi'and sal>2000 and emp.empid=dept.mgrid;
+----------+
| empname |
+----------+
| BINA |
| SHIVANSH |
+----------+
2 rows in set (0.00 sec)

Q14. Write a query to display details of employs who are not getting commission.
Solution:-
mysql> SELECT * FROM EMP WHERE COMM IS NULL;
+-------+-----------+-------------+------------+------+------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
+-------+-----------+-------------+------------+------+------+
6 rows in set (0.00 sec)
PRACTICAL NO. 24-– SQL COMMANDS 4.
Write queries (1) to (10) based on the tables EMPLOYEE and DEPARTMENT given below:

Q1. Create and open Database named office.


mysql> create database office;
Query OK, 1 row affected (0.02 sec)

Q2. Open Database office.


mysql> use office;
Database changed

Q3. Create a table EMPLOYEE (with structure given above).

mysql> create table EMPLOYEE(EMPID INTEGER, NAME VARCHAR(25), DOB DATE, DEPTID VARCHAR(20), DESIG
VARCHAR(25), SALARY INTEGER);
Query OK, 0 rows affected (0.12 sec)

Q4.Insert records of table EMPLOYEE (given above)-


mysql> insert into EMPLOYEE values(120, "Alisha", "1978-1-23", "D001", "Manager", 75000);
Query OK, 1 row affected (0.03 sec)

mysql> insert into EMPLOYEE values(123, "Nitin", "1977-10-10", "D002", "AO", 59000);
Query OK, 1 row affected (0.03 sec)

mysql> insert into EMPLOYEE values(129, "Navjot", "1971-07-12", "D003", "Supervisor", 40000);
Query OK, 1 row affected (0.03 sec)

mysql> insert into EMPLOYEE values(130, "Jimmy", "1980-12-30", "D004", "Sales Rep", Null);
Query OK, 1 row affected (0.03 sec)

mysql> insert into EMPLOYEE values(131, "Faiz", "1984-4-06", "D001", "Dep Manager", 65000);
Query OK, 1 row affected (0.03 sec)

Q5. Create a table DEPARTMENT (with structure given above).


mysql> CREATE TABLE DEPARTMENT(DEPTID VARCHAR(20), DEPARTNAME VARCHAR(25), FLOORNO INTEGER);
Query OK, 0 rows affected (0.05 sec)
Q6. Insert records of table DEPARTMENT (given above)-
mysql> insert into DEPARTMENT values("D001", "Personal", 4);
Query OK, 1 row affected (0.03 sec)
mysql> insert into DEPARTMENT values("D002", "Admin", 10);
Query OK, 1 row affected (0.03 sec)
mysql> insert into DEPARTMENT values("D003", "Production", 1);
Query OK, 1 row affected (0.04 sec)
mysql> insert into DEPARTMENT values("D004", "Sales", 3);
Query OK, 1 row affected (0.03 sec)

Q7. To display the average salary of all employees, department wise.


mysql> SELECT DEPTID, AVG(SALARY) FROM EMPLOYEE GROUP BY DEPTID;
+--------+-------------+
| DEPTID | AVG(SALARY) |
+--------+-------------+
| D001 | 70000.0000 |
| D002 | 59000.0000 |
| D003 | 40000.0000 |
| D004 | NULL |
+--------+-------------+
4 rows in set (0.00 sec)

Q8. To display name and respective department name of each employee whose salary is more than 50000.
mysql> SELECT NAME, DEPTNAME FROM EMPLOYEE, DEPARTMENT WHERE
EMPLOYEE.DEPTID=DEPARTMENT.DEPTID AND SALARY>50000;
+--------+----------+
| NAME | DEPTNAME |
+--------+----------+
| Alisha | Personal |
| Nitin | Admin |
| Faiz | Personal |
+--------+----------+
3 rows in set (0.00 sec)

Q9. To display the names of employees whose salary is not known, in alphabetical order.
mysql> SELECT NAME FROM EMPLOYEE WHERE SALARY IS NULL ORDER BY NAME;
+-------+
| NAME |
+-------+
| Jimmy |
+-------+
1 row in set (0.00 sec)

Q10. To display DEPTID from the table EMPLOYEE without repetition.


mysql> SELECT DISTINCT DEPTID FROM EMPLOYEE;
+--------+
| DEPTID |
+--------+
| D001 |
| D002 |
| D003 |
| D004 |
+--------+
4 rows in set (0.00 sec)
PRACTICAL NO. 25. – SQL COMMANDS-5.

1. Create a database named purchase.


mysql> create database purchase;

2. Create a table shop with fields - pid integer, pname varchar(20), price double, SID Integer.
mysql> use purchase;
mysql> create table shop(pid integer, pname varchar(20), price double, SID Integer);
Query OK, 0 rows affected (2.03 sec)

3. Show the structure of table shop.


mysql> desc shop;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid | int(11) | NO | PRI | NULL | |
| pname | varchar(20) | YES | | NULL | |
| price | double | YES | | NULL | |
| SID | int(11) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.14 sec)

4. Insert 05 records as given below in table shop.


+-----+----------+-------+------+
| pid | pname | price | SID |
+-----+----------+-------+------+
| 1 | Lux | 18 | 222 |
| 2 | Dettol | 16 | 333 |
| 3 | Lifebuoy | 14 | 111 |
| 4 | Ponds | 19 | 333 |
| 5 | Dove | 38 | 222 |
+-----+----------+-------+------+

mysql> insert into shop values(1,'Lux',18.00, 222);


Query OK, 1 row affected (0.16 sec)
mysql> insert into shop values(2,'Dettol',16.00, 333);
Query OK, 1 row affected (0.03 sec)
mysql> insert into shop values(3,'Lifebuoy',14.00,111);
Query OK, 1 row affected (0.05 sec)
mysql> insert into shop values(4,'Ponds',19.00,333);
Query OK, 1 row affected (0.06 sec)
mysql> insert into shop values(5,'Dove',38.00,222);
Query OK, 1 row affected (0.03 sec)

5. Create a table store with fields - SID Integer, sname varchar(20), loc varchar(20)
mysql> create table store(SID Integer, sname varchar(20), loc varchar(20));
Query OK, 0 rows affected (2.25 sec)

6. Insert detail of 03 stores as given below in table store.


| SID | sname | loc |
| 111 | Deepak Stores | New Delhi |
| 222 | Arpan Stores | Patna |
| 333 | Ayangar Stores | Chennai |
mysql> insert into store values(111,'Deepak Stores','New Delhi');
Query OK, 1 row affected (0.16 sec)

mysql> insert into store values(222,'Arpan Stores','Patna');


Query OK, 1 row affected (0.02 sec)

mysql> insert into store values(333,'Ayangar Stores','Chennai');


Query OK, 1 row affected (0.05 sec)

7. Write query to display SID, sum of price group wise as per SID from table shop .
mysql> select SID,sum(price) from shop GROUP BY SID;
+------+------------+
| SID | sum(price) |
+------+------------+
| 111 | 14 |
| 222 | 56 |
| 333 | 35 |
+------+------------+
3 rows in set (0.02 sec)

8. Write query to display SID, count of each SID from table shop .
mysql> select sid, count(*) from shop group by SID;
+------+----------+
| sid | count(*) |
+------+----------+
| 111 | 1|
| 222 | 2|
| 333 | 2|
+------+----------+
3 rows in set (0.06 sec)

9. Write query to display SID, Sum of price of SID=222 from table shop.

mysql> select SID, sum(price) from shop GROUP BY SID having SID=222;
+------+------------+
| SID | sum(price) |
+------+------------+
| 222 | 56 |
+------+------------+
1 row in set (0.64 sec)

10. Write query to display PID,PNAME,PRICE from table shop and SNAME,LOC from table store.
mysql> select pid,pname,price,sname,loc from shop,store where shop.sid=store.sid;
+-----+----------+-------+----------------+-----------+
| pid | pname | price | sname | loc |
+-----+----------+-------+----------------+-----------+
| 1 | Lux | 18 | Arpan Stores | Patna |
| 2 | Dettol | 16 | Ayangar Stores | Chennai |
| 3 | Lifebuoy | 14 | Deppak Stores | New Delhi |
| 4 | Ponds | 19 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | Arpan Stores | Patna |
+-----+----------+-------+----------------+-----------+
5 rows in set (0.45 sec)
11. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store.
mysql> select pid,pname,price,shop.sid,sname,loc from shop,store where shop.sid=store.sid;
+-----+----------+-------+------+----------------+-----------+
| pid | pname | price | sid | sname | loc |
+-----+----------+-------+------+----------------+-----------+
| 1 | Lux | 18 | 222 | Arpan Stores | Patna |
| 2 | Dettol | 16 | 333 | Ayangar Stores | Chennai |
| 3 | Lifebuoy | 14 | 111 | Deppak Stores | New Delhi |
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | 222 | Arpan Stores | Patna |
+-----+----------+-------+------+----------------+-----------+
5 rows in set (0.00 sec)
12. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store for Product
Name “Ponds”.
mysql> select pid,pname,price,shop.sid,sname,loc from shop,store where pname="Ponds" AND
shop.sid=store.sid;
+-----+-------+-------+------+----------------+---------+
| pid | pname | price | sid | sname | loc |
+-----+-------+-------+------+----------------+---------+
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
+-----+-------+-------+------+----------------+---------+
1 row in set (0.41 sec)
13. Write query to display PID,PNAME,PRICE,SID from table shop and SNAME,LOC from table store in
ascending order of price;
mysql> select pid,pname,price,A.sid,sname,loc from shop A,store B where A.sid=B.sid order by price;
+-----+----------+-------+------+----------------+-----------+
| pid | pname | price | sid | sname | loc |
+-----+----------+-------+------+----------------+-----------+
| 3 | Lifebuoy | 14 | 111 | Deppak Stores | New Delhi |
| 2 | Dettol | 16 | 333 | Ayangar Stores | Chennai |
| 1 | Lux | 18 | 222 | Arpan Stores | Patna |
| 4 | Ponds | 19 | 333 | Ayangar Stores | Chennai |
| 5 | Dove | 38 | 222 | Arpan Stores | Patna |
+-----+----------+-------+------+----------------+-----------+
5 rows in set (0.02 sec)

14. Write query to display all record of table shop whose SID is same as that of pname as “LUX”.
mysql> select * from shop where sid= (select sid from shop where pname="LUX");
+-----+-------+-------+------+
| pid | pname | price | SID |
+-----+-------+-------+------+
| 1 | Lux | 18 | 222 |
| 5 | Dove | 38 | 222 |
+-----+-------+-------+------+
2 rows in set (0.08 sec)

15. Write query to display record having maximum price from table shop.
mysql> select * from shop where price=(select max(price) from shop);
+-----+-------+-------+------+
| pid | pname | price | SID |
+-----+-------+-------+------+
| 5 | Dove | 38 | 222 |
+-----+-------+-------+------+
1 row in set (0.03 sec)
# Practical No. 26 - Write a program using MYSQL-PYTHON database connectivity to create
# a database school, then create a table student (Roll INT(4)
# primary key,Name VARCHAR(20),AGE INT(2), CITY CHAR(10),
# MARKS INT(3) in this database which should then store any
# two records in it and then display only those records
# city is "LUCKNOW"

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE school")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE INT(2), CITY
CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where city='LUCKNOW'")
myresult=mycursor.fetchall()
for x in myresult:
print(x)

Output:
#Practical No. 27 - Write a program using MYSQL-PYTHON database connectivity to create a
database school, then create a table student in this database which should
# then store any two records in it and then display only those records where AGE<=15

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where AGE<=15")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
# Practical No. 28 - Write a program using MYSQL-PYTHON database connectivity to
# create a database school, then create a table student in this database which
# should then store any two records in it and then display only those records
# where marks>=300

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(101,'Pankaj',15,'Barabanki',300)
mycursor.execute(sql,val)
sql="INSERT INTO STUDENT (ROLL,NAME,AGE,CITY,MARKS) VALUES (%s,%s,%s,%s,%s)"
val=(102,'anuj',16,'Lucknow',290)
mycursor.execute(sql,val)
mycursor.execute("select * from student where marks>=300")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
# Practical No. 29 - To write a Program using PYTHON-MYSQL Connectivity to insert records in Emp
# table and display the records. Use While loop to store multiple records.

import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='root',database='emplo
yees')
if con.is_connected():
cur=con.cursor()
opt='y'
while opt == 'y' or opt=='Y':
No=int(input("Enter Employee Number: "))
Name=input("Enter Employee Name: ")
Gender=input("Enter Employee Gender (M/F) : ")
Salary=int(input("Enter Employee Salary: "))
Query="INSERT INTO EMP VALUES ( { } , ' {}', '{}', {}) ". format (No, Name, Gender, Salary)
cur.execute (Query)
con. commit ()
print ("Record Stored Successfully")
opt=input ("Do you want to add another employee details (y/n) :")

Query="SELECT * FROM EMP" ;


cur. execute(Query)
data=cur. fetchall()
for i in data:
print(i)
con.close()
# Practical No. 30 - Write a program using MYSQL-PYTHON database connectivity
# to create a database school, then create a table student (Roll INT(4)
# primary key,Name VARCHAR(20),AGE INT(2), CITY CHAR(10),
# MARKS INT(3) in this database which should then store any
# two records in it and then display only those records
# city is "LUCKNOW"

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE School5")
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school5")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE student (Roll INT(4) primary key,Name VARCHAR(20),AGE
INT(2), CITY CHAR(10), MARKS INT(3))")
n=int(input("Enter number of records to be entered ? "))
for k in range(1,n+1,1):
print("\nEnter record ",k)
ROLL=int(input("Enter Roll Number ? "))
NAME=input("Enter Name ? ")
AGE=int(input("Enter Age ? "))
CITY=input("Enter City ? ")
MARKS=int(input("Enter Marks ? "))
sql="INSERT INTO STUDENT VALUES ({},'{}',{},'{}',{})".format(ROLL,NAME,AGE,CITY,MARKS)
mycursor.execute(sql)
mydb.commit()
print("\nRecords containing city as LUCKNOW are :")
mycursor.execute("select * from student where city='LUCKNOW'")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
mydb.close()
BIBLIOGRAPHY

References and Bibliography:

 Computer Science Class-XII NCERT Publication


 Computer Science Class-XII by Sumita Arora
 python.mykvs.in
 python4csip.com

You might also like