XII CS Practical Solution
XII CS Practical Solution
CERTIFICATE
This is to certify that, Practical on Computer Science
is successfully completed by
….……………………… of
Class: XII, Division: …….
Roll no. :………………..
for the academic year
2024-2025.
Signature:
Examiner (Subject Teacher)
Principal
Date: / / 202
INDEX
XII CS – Practical Assignments for TERM 1
Assignment 1:
Ans:
L=[]
c=0
n=int(input('how many items you want to enter in list:'))
for i in range(0,n):
a=int(input('enter item:'))
L.append(a)
print(L)
S=set(L)
S=list(S)
D={}
for i in S:
c=0
for j in L:
if i==j:
c+=1
D[i]=c
for k in D:
print("The frequency of ",k," is ", D[k])
Output is:
how many items you want to enter in list:5
enter item:4
enter item:3
enter item:4
enter item:4
enter item:7
[4, 3, 4, 4, 7]
The frequency of 3 is 1
The frequency of 4 is 3
The frequency of 7 is 1
Enter item to be search:4
Element found at index 0 and position 1
Assignment 2: Write a python program to find minimum and maximum number from
a list . Write user defined function.
def Range(list1):
largest = list1[0]
lowest = list1[0]
li=[]
n=int(input('Enter size of elements to be enter in list:'))
for i in range(n):
a=int(input('Enter numbers in list:'))
li.append(a)
Range(li)
Output is
Enter size of elements to be enter in list:3
Enter numbers in list:6
Enter numbers in list:8
Largest element is: 8
Smallest element is: 6
Enter numbers in list:67
Largest element is: 8
Smallest element is: 6
Largest element is: 67
Smallest element is: 6
Assignment 3:
Write a python program using function to pass list to a function and double
the odd values and half even values of a list and display list element after
changing.
Ans:
def splitevenodd(A):
evenlist = []
oddlist = []
for i in A:
if (i % 2 == 0):
evenlist.append(i//2)
else:
oddlist.append(i*i)
print("Even lists:", evenlist)
print("Odd lists:", oddlist)
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Elements of List ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
splitevenodd(A)
Output is:
Enter the size of List: 5
Enter the Elements of List:
12
3
14
5
1
Even lists: [6, 7]
Odd lists: [9, 25, 1]
Assignment 4:
Write a Python program input n numbers in tuple and count how many
even and odd numbers are entered.
Ans:
l=[]
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Output is:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 34
Please enter the 1 Element of List1 : 3
Please enter the 2 Element of List1 : 2
Please enter the 3 Element of List1 : 56
Please enter the 4 Element of List1 : 3
Number of even numbers : 3
Number of odd numbers : 2
Assignment 5:
Write a menu driven program in python to delete name of a student from dictionary and
to search phone no of a student by student name. Create menu as below:
MENU
1. Delete from Dictionary
2. Search Phone number using name from Dictionary
3. Exit
Ans:
phonebook=dict()
while True:
print("******MENU\*******n")
print('1:Delete from Dictionary')
print('2:Search Phone number using name from Dictionary')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
n=int(input("Enter total number of friends:"))
i=1
while(i<=n):
a=input("enter name :")
b=int(input("enter phone number:"))
phonebook[a]=b
i=i+1
print(phonebook)
print('---------------------------------')
name=input("Enter name to delete:")
del phonebook[name]
k=phonebook.keys()
print("Phonebook Information")
print('---------------------')
print("Name",'\t',"Phone number")
for i in k:
print(i,'\t',phonebook[i])
if ch==2:
name=input("Enter name to search:")
f=0
k=phonebook.keys()
for i in k:
if(i==name):
print("Phone number= ",phonebook[i])
f=1
if (f==0):
print("Given name not exist")
if ch==3:
break
Output is:
******MENU\*******n
1:Delete from Dictionary
2:Search Phone number using name from Dictionary
3:Exit
Assignment 6:
Write a menu driven program in python to do following
MENU
4. Reverse String
5. Check Whether string is Palindrome
6. Make half string in Uppercase
7. Exit
Ans:
while True:
print("******MENU*******\n")
print('1:Reverse String')
print('2:Check whether string is palindrome')
print('3:Make half string in Uppercase')
print('4:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
st = input('Enter String:')
print(st[::-1])
if ch==2:
st = input('Enter String:')
if st==st[::-1]:
print('This string is palindrome')
else:
print('String is not palindrome')
if ch==3:
st = input('Enter String:')
print("The original string is : " + str(st))
# computing half index
hlf_idx = len(st) // 2
res = ''
for idx in range(len(st)):
# uppercasing later half
if idx >= hlf_idx:
res += st[idx].upper()
else :
res += st[idx]
# printing result
print("The resultant string : " + str(res))
if ch==4:
break
Output is:
******MENU*******
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit
Assignment 7:
Write a program to read a list of n integers (positive as well as negative).
Create two new lists, one having all positive numbers with sum and the
other having all negative numbers with sum from the given list.
Ans:
list1=[]
plist1=[]
nlist1=[]
sum=0
sum1=0
n=int(input('how many elements u want in list:'))
for i in range(0,n):
a=int(input('enter item in list:'))
list1.append(a)
print('Original list is:',list1)
for i in range(0,n):
if list1[i]<0:
nlist1.append(list1[i])
sum=sum+list1[i]
else:
plist1.append(list1[i])
sum1=sum1+list1[i]
print('positive list is;',plist1)
print('sum of +ve numbers:',sum1)
print('Negative list is;',nlist1)
print('sum of -ve numbers:',sum)
Output is:
how many elements u want in list:4
enter item in list:3
enter item in list:2
enter item in list:-1
enter item in list:-1
Original list is: [3, 2, -1, -1]
positive list is; [3, 2]
sum of +ve numbers: 5
Negative list is; [-1, -1]
sum of -ve numbers: -2
Assignment 8:
Ans:
a=[]
n=int(input('how many elements u want in list:'))
for i in range(0,n):
n1=int(input('enter item in list:'))
a.append(n1)
print('Original list is:',a)
print('List after removing duplicate elements:')
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Output is:
how many elements u want in list:5
enter item in list:34
enter item in list:2
enter item in list:34
enter item in list:2
enter item in list:1
Original list is: [34, 2, 34, 2, 1]
List after removing duplicate elements:
{1, 34, 2}
Assignment 9:
Write a python code using function to search an element in a list using Binary search
method.
Ans:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
# Initial list1
list1=[]
y=int(input('how many elements u want in list:'))
for i in range(0,y):
n1=int(input('enter item in ascending/descending order in list:'))
list1.append(n1)
x=(int(input('Enter item to search:')))
# Function call
result = binary_search(list1, x)
if result != -1:
print("Element is present at index", str(result),'and at position:',str(result+1))
else:
print("Element is not present in list1")
Output is:
how many elements u want in list:5
enter item in ascending/descending order in list:20
enter item in ascending/descending order in list:15
enter item in ascending/descending order in list:14
enter item in ascending/descending order in list:13
enter item in ascending/descending order in list:12
Enter item to search:14
Element is present at index 2 and at position: 3
Assignment 10:
Write a menu driven program to generate random numbers given in
specific range and to display calendar after giving month and year.
MENU
1. Generate Random numbers
2. Calender of a month
3.Exit
Ans:
# Program to display calendar of the given month and year
import random
import calendar
while True:
print("******MENU*******\n")
print('1:Random Number generators')
print('2:Calender of a month')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
num = 10
start = 20
end = 40
res = []
for j in range(num):
res.append(random.randint(start, end))
print(res)
if ch==2:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))
if ch==3:
break
Output is:
******MENU*******
******MENU*******
Ans:
file=input('Enter the file: ')
f =open( file,'r')
item=[]
for line in f:
words=line.split()
for i in words:
item.append(i)
print('#'.join(item))
Output is:
Enter the file: i.txt
i#like#india
Assignment 12:
Write a python program Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Ans:
def cnt():
f=open('i.txt','r')
cont=f.read()
v=0
c=0
lcl=0
ucl=0
for ch in cont:
if(ch.islower()):
lcl=lcl+1
elif (ch.isupper()):
ucl=ucl+1
if (ch in['a','e','i','o','u'] or ch in['A','E','I','O','U']):
v=v+1
elif (ch in ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
or ch in['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W','X', 'Y','Z']):
c=c+1
f.close()
print('Vowels are:',v)
print('Consonents are:',c)
print('Lowercase letters are:',lcl)
print('Uppercase letters are:',ucl)
cnt()
Output is:
Vowels are: 6
Consonents are: 4
Lowercase letters are: 10
Uppercase letters are: 0
Assignment 13:
Write a python code that accepts a filename, and copies all lines that do
not start with a lowercase letter from the first file into the second.
Ans:
Output is:
Assignment 14:
Write a python program to remove all the lines that contain the character
‘a’ in a file and write it to another file.
Ans:
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it as
harry grows\nthe books were written by J.K rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
Output is:
Assignment 15:
Write a python program to create a binary file with name and roll number.
Search for a given roll number and display name, if not found display
appropriate message.
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()
Output is:
Enter roll number:1
Enter Name:APARNA DHIRDE
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANGESH
Wish to enter more record (Y/N):Y
Enter roll number:3
Enter Name:VEERA
Wish to enter more record (Y/N):N
Enter rollno to be searched=2
Roll Num: 2
Name: MANGESH
Assignment 16:
Write a python program to create a binary file with roll number, name and
marks. Input a roll number and update name and marks
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks:'))
#Creating the dictionary
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
#Writing the Dictionary
f = open('student1.dat','ab')
pickle.dump(rec,f)
ch=input('Wish to enter more record (Y/N):')
if ch=='N' or ch=='n':
break
f.close()
f=open('student1.dat','rb+')
found=0
f.close()
Output is:
Enter roll number:1
Enter Name:ASHWINI UPARE
Enter Marks:456
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANOJ PATIL
Enter Marks:400
Wish to enter more record (Y/N):N
Enter roll no to search :2
Current name is: MANOJ PATIL
Current Marks are: 400
Enter new name:MANOJ ASHOK PATIL
Enter new marks:500
Record updated
Assignment 17:
Write a menu driven python program to create a CSV file by entering dept-
id, name and city, read and search the record for given dept-id.
MENU
1. Create csv
2. Search record as per dept no
3.Exit
Ans:
import csv
while True:
print('*** MENU ***\n')
print('1: create csv file')
print('2: Search as per id')
print('3: Exit')
ch=int(input('Enter choice:'))
if ch==1:
f=open('dept.csv','a')
mywriter=csv.writer(f,delimiter=',')
ans='y'
while ans.lower()=='y':
rno=int(input('Enter dept no:'))
name=input('Enter dept name:')
clas=input('Enter city:')
mywriter.writerow([rno,name,clas])
print('## Data Saved ##')
ans=input('Add More?:')
f.close()
if ch==2:
print("Search a Record")
print("===================")
f=open('dept.csv','r',newline='\r\n') #Remove new line character
from output
r=input('Enter DEPT no you want to search:')
s=csv.reader(f)
for rec in s:
if rec[0]==r:
print("Rollno=",rec[0])
print("Name=",rec[1])
print("Marks=",rec[2])
f.close()
if ch==3:
break
Output is:
*** MENU ***
Assignment 18:
Write a Menu driven program in python to count spaces, digits, words and
lines from text file try.txt
Ans:
while True:
print('*** MENU ***\n')
print('1: count spaces')
print('2: count digits')
print('3: count words')
print('4: count lines')
print('5: exit')
ch=int(input('enter your choice:'))
if ch==1:
F1=open('abc.txt', 'r')
c=0
F=F1.read()
for letter in F:
if( letter.isspace( )):
c=c+1
print('No. of spaces are:',c)
F1.close()
if ch==2:
c=0
F1=open('abc.txt', 'r')
F=F1.read()
for letter in F:
if( letter.isdigit( )):
c=c+1
F1.close()
if ch==3:
f=open("abc.txt","r")
linesList=f.readlines()
count=0
for line in linesList:
wordsList=line.split()
print(wordsList)
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()
if ch==4:
count =0
f=open("abc.txt","r")
data=f.readlines()
print(data)
for line in data:
count=count+1
print("Number of lines : " ,count)
f.close()
if ch==5:
break
Output is:
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:1
No. of spaces are: 8
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:2
No. of digits are: 4
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:3
['Sky', 'is', 'blue', '2021.']
['i', 'like', 'rainy', 'season.']
The number of words in this file are : 8
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:4
['Sky is blue 2021.\n', 'i like rainy season.\n']
Number of lines : 2
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:5
>>>
Assignment 19: Write a Python program to implement a stack using list (PUSH & POP
Operation on Stack).
SQL QUERIES
[1] Consider the following MOVIE table and write the SQL queries based on it.
1. Display all information from the movie.
2. Display the type of movies.
3. Display movieid, movie name, total_eraning by showing the business
done by the movies. Calculate the business done by movie using the
sum of production cost and business cost.
4. Display movie id, movie name and production cost for all movies with
production cost greater than 150000 and less than 1000000.
5. Display the movie of type action and romance.
6. Display the list of movies which are going to release in February, 2022.
Answers:
Output:
2. select distinct from a movie ;
4. select movie_id, movie name, production cost from movie where product is
>150000 and <1000000 ;
5. select movie name from movie where type =’action’ or type=’romance’ ;
Answers:
M1 2021/12/ 1 2 107 93
20
M3 2021/12/ 1 3 86 81
22
M4 2021/12/ 2 4 65 67
23
M5 2021/12/ 1 4 52 88
24
M6 2021/12/ 2 3 97 68
25
Answers:
desc team;
Inserting data:
1. Display the matchid, teamid, team score who scored more than 70 in
first inning along with team name.
2. Display matchid, team name and second team score between 100 to
160.
3. Display matchid, team names along with matchdates.
4. Display unique team names
5. Display matchid and match date played by Anadhi and Shailab.
Answers:
[2] select matchid, team name, second team score from match_details, team
were match_details.secondteamid=team.teamid and
match_details.secondteamscore between 100 and 160;
[4] select dcode,avg(unit price) from stock group by dcode having avg(unit
price)>5;
************************************************************
Enter string to check : nitin
Yes, the string is a palindrome
************************************************************
***********************************************************
Write a python program using function PUSH(Arr), where Arr is a list of numbers. From
this list push all numbers divisible by 5 into a stack implemented by using a list. Display
the stack if it has at least one element, otherwise display appropriate error message.
Ans:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
if item%5==0:
Arr.append(item)
top=len(Arr)-1
def show(Arr):
if isEmpty(Arr):
print('No item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
show(Arr)
elif ch==0:
print('Bye')
break
Output is:
Assignment 21:
Write a python program using function POP(Arr), where Arr is a stack implemented by a
list of numbers. The function returns the value deleted from the stack.
Ans:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
Arr.append(item)
top=len(Arr)-1
def pop(Arr):
if isEmpty(Arr):
return 'Underflow occurs'
else:
val=Arr.pop()
if len(Arr)==0:
top=None
else:
top=len(Arr)-1
return val
def show(Arr):
if isEmpty(Arr):
print('no item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
val=pop(Arr)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
show(Arr)
elif ch==0:
print('Bye')
break
Output is:
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:1
Enter no to push:34
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:1
Enter no to push:3
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:3
(TOP)3 <==34 <==
****** STACK IMPLEMENTATION USING LIST ******
1: PUSH
2: POP
3: Show
0: Exit
Enter choice:2
Assignment 22:
Write a python program to push 5 strings which do not include vowel and pop the stack
novowel=[]
All=[]
for count in range (5):
word=input("\nenter a word")
push(All,word)
pushnv(All)
while True:
if novowel!=[]:
print (pop(novowel),end="")
else:
break
Output is:-
>>>
Assignment 23:
Create a table and insert data. Implement all SQL commands on the table
SQL Commands on EMPLOYEE table
MySQL Practical
1. CREATING TABLES IN MYSQL
E.g. in order to create table EMPLOYEE given below :
ECODE ENAME GENDER GRADE GROSS
We write the following command :
CREATE TABLE employee ( ECODE integer ,
ENAME varchar(20) , GENDER char(1) ,
GRADE char(2) , GROSS integer ) ;
2. INSERTING DATA INTO TABLE
- e.g. to enter a row into EMPLOYEE table (created above), we write command as :
INSERT INTO employee VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
e.g.In order to retrieve everything from Employee table, we write SELECT command as :
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965
FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE , GROSS
FROM EMPLOYEE ;
E.g.2. in order to select rows where salary is greater than 48000, then
command is : SELECT * FROM EMPLOYEE
WHERE GROSS > 48000 ;
GENDER
M
M
F
M
F
F
DISTINCT(GENDER)
M
F
e.g. to view the structure of table EMPLOYEE, commandis : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;
FROM EMPLOYEE ;
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000 and 50000,
command is:
SELECT ECODE ,
ENAME ,GRADE FROM
EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
ECOD ENAM GRADE
E E
1001 Ravi E4
1006 Ruby A1
SELECT * FROM
EMPLOYEE WHERE
GRADE IN (‘A1’ , ‘A2’);
Output will be :
ECOD ENAM GENDE GRADE GROSS
E E R
1002 Akash M A1 35000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000
- The NOT IN operatorfinds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
ECOD ENAM GENDE GRADE GROSS
E E R
1001 Ravi M E4 50000
1004 Neela F B2 38965
e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME FROM EMPLOYEE
Output will be :
ENAM
E
Ravi
Ruby
Output will be :
ECOD ENAM GENDE GRADE GROSS
E E R
1004 Neela F B2 38965
1009 Neema F A2 52000
Output will be :
ECOD ENAM GENDE GRADE GROSS
E E R
1005 Sunny M A2 30000
1006 Ruby F A1 45000
e.g.
STUDENT
Roll_N Name Mark
o s
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL
to display the names of those students whose marks is NULL, we use the
command : SELECT Name
FROM EMPLOYEE
Output will be :
Name
ARUN
SANJAY
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use
command : SELECT *
FROM
EMPLOYEE
ORDER BY
ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM
EMPLOYEE
WHERE GROSS >
40000 ORDER BY
ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE SET GROSS = 55000 WHERE ECODE = 1009 ;
OTHER EXAMPLES
Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE
WHERE GRADE =’A1’ ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted.
Thus above line will delete all rows from employee table.
Once this command is given, the table name is no longer recognized and no more commands can be given on
that table. After this command is executed, all the data in the table along with table structure will be deleted.
e.g. Given a table namely Test with the following data in it.
Co Co
l1 l2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testtADD col6 VARCHAR(3);
In table EMPLOYEE , change the column ENAME to EM_NAME and data type from
VARCHAR(20) to VARCHAR(30).
In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).
DROP GRADE ;
Table : EMPL
EMP ENA JOB SAL DEPT
NO ME NO
8369 SMIT CLERK 2985 10
H
8499 ANYA SALESM 9870 20
AN
8566 AMIR SALESM 8760 30
AN
8698 BINA MANAGE 5643 20
R
8912 SUR NULL 3000 10
1. AVG( )
This function computes the average of given data.
e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where
COLUMN is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
3. MAX( )
This function returns the maximum value from a given column or expression.
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
Output
SUM(SAL)
30258
The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.
Table : EMPL
EMP ENA JOB SAL DEPT
NO ME NO
8369 SMIT CLERK 2985 10
H
8499 ANYA SALESM 9870 20
AN
8566 AMIR SALESM 8760 30
AN
8698 BINA MANAGE 5643 20
R
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiplefields in the GROUP BY
expression.
e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on
individual rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can
do so.
- e.g. To display the jobs where the number of employees is less than 2,
- SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB
HAVING COUNT(*) < 2 ;
Output
JOB COUNT(*)
CLERK 1
MANAG 1
ER
MySQL FUNCTIONS
Types of MySQL functions : String Functions , Maths Functions and Date & Time Functions.
Table : EMPL
EMP ENA JOB SAL DEPT
NO ME NO
8369 SMIT CLERK 2985 10
H
8499 ANYA SALESM 9870 20
AN
8566 AMIR SALESM 8760 30
AN
8698 BINA MANAGE 5643 20
R
8912 SUR NULL 3000 10
STRING FUNCTIONS
Output
CONCAT(EMPNO ,
ENAME)
8369SMITH
8912SUR
2. LOWER( ) / LCASE( ) - Returns the argument in
lowercase. Syntax : LOWER(Column
name)
e.g.
SELECT LOWER(ENAME) FROM EMPL ;
Output
LOWER(ENAME)
smith
anya
amir
bina
sur
e.g.
SELECT UPPER(ENAME) FROM EMPL ;
Output
UPPER(ENAM
E)
SMITH
ANYA
AMIR
BINA
SUR
Syntax : SUBSTR(Column name, m , n), where m specifies starting index and n specifies number of
characters from the starting index m.
e.g.
SELECT SUBSTR(ENAME,2,2) FROM EMPL WHERE DEPTNO=20;
Output
SUBSTR(ENAME,2,2)
NY
IN
LENGTH(ENAME)
5
4
4
4
3
e.g.2. Output
9. LEFT( ) – Returns the leftmost numberof characters as specified.
e.g. SELECT LEFT(‘CORPORATE FLOOR’ , 3) ;
Output
LEFT(‘CORPORATE FLOOR’,
3)
COR
NUMERIC FUNCTIONS
These functions accept numeric values and after performing the operation, return numeric value.
1. MOD( ) – Returns the remainder of given two numbers. e.g. SELECT MOD(11 , 4);
Output
MOD(11, 4 )
3
2. POW( ) / POWER( ) - This function returns mn i.e , a numberm raised to the nth power.
e.g. SELECT POWER(3,2) ;
Output
POWER(3,
2)
9
e.g. 2. SELECT ROUND(15.193 , -1); - This will convert the number to nearest ten’s .
Output
ROUND(15.193 , -1)
20
Output
TRUNCATE(15.79 , 1)
15.7
E.g. 2. SELECT TRUNCATE(15.79 , -1); - This command truncate value 15.79 to nearest ten’s place.
Output
TRUNCATE(15.79 , -1)
10
DATE AND TIME FUNCTIONS
Date functions operate on values of the DATE datatype.
2. DATE( ) – This function extracts the date part from a date. E.g.
SELECT DATE( ‘2016-02-09’) ;
Output
DATE( ‘2016-02-09’)
09
6. DAYOFMONTH( ) – This function returns the day of month. Returns value in range of 1 to 31.
E.g. SELECT DAYOFMONTH( ‘2016-12-14’) ;
Output
DAYOFMONTH( ‘2016-12-
14’)
14
7. DAYOFWEEK( ) – This function returns the day of week. Return the weekdayindex for date.
(1=Sunday, 2=Monday,……., 7=Saturday)
SELECT DAYOFWEEK( ‘2016-12-14’) ;
Output
DAYOFWEEK( ‘2016-12-14’)
4
8. DAYOFYEAR( ) – This function returns the day of the year. Returns the value between 1 and
366. E.g. SELECT DAYOFYEAR(‘2016-02-04) ;
Output
DAYOFYEAR( ‘2016-02-04’)
35
10. SYSDATE( ) – It also returns the current date but it return the time at which SYSDATE( ) executes. It differs
from the behavior for NOW( ), which returns a constant time that indicates the time at which the statement
began to execute.
e.g. SELECT SYSDATE( ) ;
Assignment 24:
Integrate MySQL with Python by importing the MySQL module and add records of
student and display all the record.
Ans:
import os
import platform
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database
="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()
def stuInsert():
L=[]
roll=int(input("Enter the roll number : "))
L.append(roll)
name=input("Enter the Name: ")
L.append(name)
age=int(input("Enter Age of Student : "))
L.append(age)
clas=input("Enter the Class : ")
L.append(clas)
stud=(L)
sql="insert into stud (roll,name,age,clas) values (%s,%s,%s,%s)"
mycursor.execute(sql,stud)
mydb.commit()
def stuview():
mycursor.execute("select * from stud")
myrus=mycursor.fetchall()
for x in myrus:
print(x)
Output is:
<mysql.connector.connection.MySQLConnection object at 0x02272110>
Enter 1 : To Add Student
Enter 2 : To View Students
Please Select An Above Option: 2
(1, 'ANJU JHA', 17, 12)
(2, 'YASH', 16, 11)
(3, 'ANIKET JAISWAR', 16, 12)
(4, 'SANGEETA', 15, 10)
(5, 'SANGEETA SETH', 15, 10)
(6, 'YAMINI', 16, 11)
(7, 'ANJU', 15, 10)
(8, 'OM', 16, 12)
(9, 'MANGALA', 16, 11)
Assignment 25:
Integrate MySQL with Python by importing the MySQL module to search student using
rollno, name, age, class and if present in table display the record, if not display
appropriate method.
Ans:
import os
import platform
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()
def stuview():
print("Select the search criteria : ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Class")
print("5. All")
ch=int(input("Enter the choice : "))
if ch==1:
s=int(input("Enter roll no : "))
rl=(s,)
sql="select * from stud where roll=%s"
mycursor.execute(sql,rl)
elif ch==2:
s=input("Enter Name : ")
rl=(s,)
sql="select * from stud where name=%s"
mycursor.execute(sql,rl)
elif ch==3:
s=int(input("Enter age : "))
rl=(s,)
sql="select * from stud where age=%s"
mycursor.execute(sql,rl)
elif ch==4:
s=input("Enter Class : ")
rl=(s,)
sql="select * from stud where clas=%s"
mycursor.execute(sql,rl)
elif ch==5:
sql="select * from stud"
mycursor.execute(sql)
res=mycursor.fetchall()
print("The Students details are as follows : ")
print("(ROll, Name, Age, Class)")
for x in res:
print(x)
runAgain()
Assignment 26:
Integrate MySQL with Python by importing the MySQL module to search a student using
rollno, delete the record.
Ans:
import os
import platform
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="student",charset="utf8")
print(mydb)
mycursor=mydb.cursor()
def removeStu():
roll=int(input("Enter the roll number of the student to be deleted : "))
rl=(roll,)
sql="Delete from stud where roll=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()
def stuview():
mycursor.execute("select * from stud")
myrus=mycursor.fetchall()
for x in myrus:
print(x)
Assignment 27:
Integrate SQL with Python by importing the MySQL module to search a student using
rollno, update the record.
Ans:
Import mysql.connector as mycon
cn =
mycon.connect(host='localhost',user='root',password="root",database="student",chars
et="utf8")
cur = cn.cursor()
print('Welcome to student Details Updation screen... ')
cur.execute(query)
cn.commit()
print("\n## RECORD UPDATED ##")
Output is:
Welcome to student Details Updation screen...
*******************EDIT STUDENT DETAILS **************************
Enter Student's roll number to edit :1
**************************************************
ROLL NO NAME AGE CLASS
**************************************************
1 ANJU JHA 17 12
--------------------------------------------------
Are you sure to update ? (y/n)y
Enter new name to update (enter old value if not to update) :ANJU
Enter new age to update (enter old value if not to update) :16
## RECORD UPDATED ##
Assignment 28:
JOINS
- A join is a query that combines rows from two or more tables. In a join- query,
more than one table are listed in FROM clause.
Table : empl
EMP ENA JOB SAL DEPT
NO ME NO
8369 SMIT CLERK 2985 10
H
8499 ANYA SALESM 9870 20
AN
8566 AMIR SALESM 8760 30
AN
8698 BINA MANAGE 5643 20
R
Table : dept
This query will give you the Cartesian product i.e. all possible concatenations are formed of
all rows of both the tables EMPL and DEPT. Such an operation is also known as Unrestricted
Join. It returns n1 x n2 rows where n1 is number of rows in first table and n2 is number of
rows in second table.
EQUI-JOIN
- The join in which columns are compared for equality, is called Equi- Join. In equi-
join, all the columns from joining table appear in the output even if they are
identical.
e.g. SELECT * FROM empl, dept
WHERE empl.deptno = dept.deptno ;
deptno column is appearing
twice in output.
Q: with reference to empl and dept table, find the location of employee
SMITH.
ename column is present in empl and loc column is present in dept. In order to obtain the result,
we have to join two tables.
SELECT ENAME,
LOC FROM EMPL,
DEPT
WHERE EMPL.DEPTNO = DEPT.DEPTNO AND ENAME=’SMITH’;
SELECT EMPL.deptno,
dname,empno,ename,job,sal FROM EMPL,DEPT
WHERE
EMPL.DEPTNO=DEPT.DEPTNO ORDER
BY EMPL.DEPTNO;
QUALIFIED NAMES
Did you notice that in all the WHERE conditions of join queries given so far, the field(column) names
are given as: <tablename>.<columnname>
This type of field names are called qualified field names. Qualified field names are very useful in
identifying a field if the two joining tables have fields with same time. For example, if we say deptno
field from joining tables empl and dept, you’ll definitely ask- deptno field of which table ? To avoid
such an ambiguity, the qualified field names are used.
TABLE ALIAS
- A table alias is a temporary label given along with table name in FROM clause.
e.g.
SELECT E.DEPTNO,
DNAME,EMPNO,ENAME,JOB,SAL FROM
EMPL E, DEPT D
WHERE E.DEPTNO =
D.DEPTNO ORDER BY
E.DEPTNO;
In above command table alias for EMPL table is E and for DEPT table , alias is D.
NATURAL JOIN
By default, the results of an equijoin contain two identical columns. One of the two identical
columns can be eliminated by restating the query. This result is called a Natural join.
empl.* means select all columns from empl table. This thing can be used with any table.
LEFT JOIN
- You can use LEFT JOIN clause in SELECT to produce left join i.e.
- When using LEFT JOIN all rows from the first table will be returned whether there are
matches in the second table or not. For unmatched rows of first table, NULL is shown
in columns of second table.
S1 S2
Roll_n Nam Roll_n Class
o e o
1 A 2 III
2 B 4 IX
3 C 1 IV
4 D 3 V
5 E 7 I
6 F 8 II
SELECT S1.ROLL_NO, NAME,CLASS
FROM S1 LEFT JOIN S2 ON S1.ROLL_NO=S2.ROLL_NO;
RIGHT JOIN
- It works just like LEFT JOIN but with table order reversed. All rows from the second
table are going to be returned whether or not there are matches in the first table.
- You can use RIGHT JOIN in SELECT to produce right join i.e.