Practicle File 1
Practicle File 1
GSBV BURARI
COMPUTER SCIENCE
PRACTICAL FILE
Table of Content:
S. No. Practical Name Page No. Teacher’s
Sign
PYTHON PRACTICALS
1. WAP in Python to find the factorial of a number using
function.
2. WAP in Python to implement default and positional
parameters.
3. Write a program in Python to input the value of x and n and
print the sum of the following series
1+x+x^2+x^3+-----------------x^n
4. WAP in Python to read a text file and print the number of
vowels and consonants in the file.
5. WAP in Python to read a text file and print the line or
paragraph starting with the letter ‘S’
6. WAP in Python to read a text file and print the number of
uppercase and lowercase letters in the file.
7. WAP in Python to create a binary file with name and roll
number of the students. Search for a given roll number and
display the name of student.
8. Create a binary file with roll_no, name and marks of some
students and update the marks of specific student.
9. Create a binary file with eid, ename and salary and update
the salary of the employee.
10. Create a text file and remove the lines from the file which
contains letter ‘K’
11. Create a binary file with 10 random numbers from 1 to 40
and print those numbers.
12. Write a program in Python to create a CSV file with the
details of 5 students.
13. WAP in Python to read a CSV file.
MYSQL PRACTICALS
1. Write a SQL query to create a database.
20. Use the Select command to get the details of the students
with marks more than 30.
21. AMAN PAL, a student of class XII, created a table “CLASS”.
Grade isone of the columns of this table. Write the SQL query
to find the details of students whose grade have not been
entered.
22. AMAN PAL is using a table with the following
details: Students(Name, Class, Stream_id,
Stream_Name) Write the SQL query to display
def fact(n):
f=1
while(n>0):
f=f*n
n=n-1
return f
n=int(input("Enter a number to find the factorial: "))
if(n<0):
print("Factorial of -ive number is not possible.")
elif(n==0):
print("Factorial of 0 is 1")
else:
factorial=fact(n)
print("Factorial of ",n," is =",factorial)
OUTPUT :
=RESTART:C:\Users\S P SHARMA\AppData\Local\Programs\Python\Pythons38-32\P-4.py
Enter a number : 5
Factorial of 5 is 120
>>>
=RESTART:C:\Users\S P SHARMA\AppData\Local\Programs\Python\Pythons38-32\P-4.py
Enter a number : 0
Factorial of 0 is 1
>>>
=RESTART:C:\Users\S P SHARMA\AppData\Local\Programs\Python\Pythons38-32\P-4.py
Enter a number : -5
Factorial of -ive number is not possible.
#default parameters
show(5,6)
show(5,6,10)
show(5)
show(5,6)
show(5,6,10)
#Positional parameters
def show2(a,b):
print(“Sub=”,(a-b))
show2(15,6)
show2(6,15)
OUTPUT :
=RESTART:C:\Users\S P SHARMA\AppData\Local\Programs\Python\Pythons38-32\P-4.py
Sum= 19
Sum= 21
Sum1=22
Sum1=19
Sum1=21
Sub= 9
Sub= -9
sum=()
for I n range(0,n+1):
sum=sum+x**i
print(“sum of series=”,sum)
OUTPUT :
=RESTART:C:\Users\S P SHARMA\AppData\Local\Programs\Python\Pythons38-32\P-4.py
Practical No – 4: WAP in Python to read a text file and print the number of
vowels and consonants in the file.
f-open("Vowel.txt","r")
data=f.read()
V=['A','E','I','O', 'U','a','e','i', 'o','u']
C=['B','C','D','F','G', 'H','J', 'K', 'L', 'M', 'N','P', 'Q','R', 'S', 'T', 'V', 'W','X', 'Y','Z',
'b','c','d', 'f','g', 'h','j', 'k', 'T', 'm','n','p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y','z']
cv=0
cc=0
fori in data:
if i in V:
cv=cv+1
elif i in C:
cc=cc+1
ct=0
for i in data:
ct=ct+1
print("Number of Vowels in the file=",cv)
print("Number of Consonants in the file=",cc)
print("Number of Total Chars in the file=",ct)
f.close()
OUTPUT :
Practical No – 5: WAP in Python to read a text file and print the line or
paragraph starting with the letter ‘S’.
f=open("abc.txt","r")
line=f.readline()
Ic=0
while line:
if line[0]=='s' or line[0]=='S':
print(line,end="")
Ic=lc+1
line=f.readline()
f.close()
OUTPUT :
Sam
Sameer
Sanjay
Sunil
Practical No – 6: WAP in Python to read a text file and print the number of
uppercase and lowercase letters in the file.
f=open("Vowel.txt","r")
data=f.read()
cu=0
cl=0
for i in data:
if i.isupper():
cu=cu+1
elif i.islower:
cl=cl+1
ct=0
fori in data:
ct=ct+1
print("Number of Uppercase letters in the file=",cu)
print("Number of Lowercase Letters in the file=",cl)
print("Number of Total Chars in the file=",ct)
f.close()
OUTPUT :
Practical No – 7: WAP in Python to create a binary file with name and roll
number of the students. Search for a given roll number and display the
name of student.
import pickle
S={}
f=open('stud.dat','wb')
c='y'
while c=='y' or c=='Y':
S['RollNo']=rno
S['Name']=name
pickle.dump(S,f)
f.close()
f=open('stud.dat','rb')
rno=int(input("Enter the roll no. of the student to be search: "))
K={}
m=0
try:
while True:
K=pickle.load(f)
if K["RollNo"] == rno:
print(K)
m=m+1
except EOFError:
f.close()
if m==0:
OUTPUT :
Practical No – 8: Create a binary file with roll no, name and marks of some
students and update the marks of specific student.
import pickle
S={}
f=open('stud.dat','wb')
c='y'
while c=='y' or c=='Y':
rno=int(input("Enter the roll no. of the student :"))
name=input("Enter the name of the student: ")
marks=int(input("Enter the marks of the student: "))
S['RollNo']=rno
S['Name']=name
S['Marks']=marks
pickle.dump(S,f)
c=input("Do You Want to add more students(y/n): ")
f.close()
f=open('stud.dat','rb+')
rno=int(input("Enter the roll no. of the student to be updated: "))
marks=int(input("Enter the updated marks of the student: "))
14 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
f.seek(0,0)
m=0
try:
while True:
pos=f.tell()
S=pickle.load(f)
If S["RollNo"] == rno:
f.seek(pos)
S["Marks"]=marks
pickle.dump(S,f)
m=m+1
except EOFError:
f.close()
if m==0:
print("Student not Found")
else:
f=open('stud.dat','rb')
try:
while True:
S=pickle.load(f)
print(S)
except EOFError:
f.close()
OUTPUT :
= RESTART: C:\Users\S P SHARMA\AppData\Local\Programs\Python\Python38-32\P-4.py
Practical No – 9: Create a binary file with eid, ename and salary and update
the salary of the employee.
import pickle
E=0
f=open('emp.dat', 'wb')
c='y'
while c=='y' or c=='Y':
eid=int(input("Enter the Emp Id of the Employee: "))
ename=input("Enter the name of the Employee: ")
salary-float(input("Enter the salary of the Employee: "))
E['Emp_id']=eid
E['Emp_Name']=ename
E['Salary']=salary
pickle.dump(E,f)
c=input("Do You Want to add more employee (y/n): ")
f.close()
f-open('emp.dat','rb+')
eid=int(input("Enter the Emp Id of the employee to be updated: "))
salary=float(input("Enter the updated salary of the employee: "))
f.seek(0,0)
m=0
try:
while True:
pos=f.tell()
E=pickle.load(f)
if E["Emp_id"] == eid:
f.seek(pos)
16 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
E["Salary"]=salary
pickle.dump(E,f)
m=m+1
exceptEOFError:
f.close()
if m==0:
print("Employee not Found")
else:
f=open('emp.dat','rb')
try:
while True:
E=pickle.load(f)
print(E)
except EOFError:
f.close()
OUTPUT :
Practical No - 10: Create a text file and remove the lines from the file which
contains letter 'K'.
import sys
f-open("sps.txt", "w+")
print("Enter the lines/data to insert in the file: ")
data = sys.stdin.readlines()
for i in data:
f.write(i)
f.close()
print("****")
print("Content of File:
") f=open("sps.txt","r")
data=f.read()
print(data)
f.close()
f=open("sps.txt","r+")
data=f.readlines()
f.seek(0)
for i in data:
if "K" not in i:
f.write(i)
f.truncate()
f.close()
print("**********")
print("Content of File After Deletion: ")
f=open("sps.txt","r")
data=f.read() print(data)
OUTPUT :
Practical No - 11: Create a binary file with 10 random numbers from 1 to 40 and
print those numbers.
Import pickle,random
N=[]
f=open("sps.txt","wb")
for i in range(10):
N.append(random.randint(1,40))
pickle.dump(N,f)
f.close()
print("File Created:")
19 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
print("Content of File:")
f=open("sps.txt","rb")
data-pickle.load(f)
for i in data:
print(i)
f.close()
OUTPUT :
= RESTART: C:\Users\S P SHARMA\AppData\Local\Programs\Python\Python38-32\P-4.py
File Created:
Content of File:
24
14
18
14
26
9
333
7
10
33
Practical No - 12: Write a program in Python to create a CSV file with the
details of 5 students.
Import csv
f=open("student.csv","w",newline=")
cw=csv.writer(f)
cw.writerow(['Rollno', 'Name','Marks'])
fori in range(5):
print("Student Record of ",(i+1))
rollno=int(input("Enter Roll No. :"))
name=input("Enter Name: ")
marks float(input("Enter Marks: "))
sr=[rollno,name,marks]
20 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
cw.writerow(sr)
f.close()
print("File Created Successfully")
OUTPUT :
Student Record of 1
Enter Roll No.: 11
Enter Name: Shiva
Enter Marks: 34
Student Record of 2
Enter Roll No.: 23
Enter Name: Saanvi
Enter Marks: 37
Student Record of 3 Enter Roll No.: 27
Enter Name: Sachin
Enter Marks: 24
Student Record of 4
Enter Roll No.: 28
Enter Name: Ram
Enter Marks: 40
Student Record of 5
Enter Roll No.: 29
Enter Name: Raj
Enter Marks: 37
File Created Successfully
>>>
import csv
f=open("student.csv","r”)
cr=csv.reader(f)
for r in cr:
print(r)
f.close()
OUTPUT:
Practical No-14: Write a menu driven program which insert, delete and display
the details of an employee such as eid, eneme and salary using Stack.
Employee=[]
c = ‘y’
while(c=="y" or c=="Y"):
print("1: Add Employee Detail:")
print("2: Delete Employee Detail: ")
print("3: Display Employee Detail:")
choice=int(input("Enter your choice: "))
if(choice ==1):
eid= int(input("Enter Employee Id: "))
ename= input("Enter Employee Name:")
salary= float(input("Enter Employee Salary:"))
emp= (eid,ename,salary)
Employee.append(emp)
elif(choice==2):
if(Employee==[]):
print("Stack Empty")
else:
print("Deleted element is:", Employee pop())
elif(choice==3):
L=len(Employee)
while(L>0):
print(Employee[L-1])
L=L-1
else:
print("Wrong Input")
c=input("Do you want to continue? Press ‘y’ to Continue:")
Output:
Practical No-15: Write a menu driven program which insert, delete and display
the details of a book such as book_id, book_name and price using Stack.
Book=[]
c= ‘y’
while(c== ‘y’ or c== ‘y’):
print("1: Add Book Details: ")
print("2: Delete Book Details:")
print("3: Display Book Details: ")
choice= int(input("Enter Your Choice: ")
if(choice == 1):
book_id= int(input("Enter Book Id:"))
24 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Output:
Practical No-16: Write a menu driven program which insert, delete and display
the details of a student such as roll_no, sname and course using Stack.
Student=[]
c= ‘y’
while(c=='y' or c=='Y’):
Output:
Practical No-17: Write a menu driven program which insert, delete and display
the details of a movie such as movie_id, mname and rating using Stack.
movie=[]
c= ‘y’
while(c=='y' or c== 'Y'):
print("1:Add Movie Details")
print("2:Delete Movie Details")
print("3:Display Movie Details:")
Choice=int(input("Enter Your Choice"))
if(Choice==1):
mid=int(input("Enter Movie id: "))
mname=input("Enter Movie Name:"))
rating=float(input("Enter Movie Rating"))
mov =(mid,mname, rating)
movie.append(mov)
elif(Choice==2):
if([movie]):
print("stack empty")
else:
print("Deleted element is ",movie pop())
elif(Choice==3):
L=len[movie]
while(L>0):
print(movie[L-1])
L=L-1
else:
print("wrong input")
c = input("Do you want to continue? press ‘y’ to continue: ")
Output:
=RESTART: C:\Users\SP SHARMA\AppData\Local\Programs\Python\Python38-321P-4.py
Practical No-18: Write a menu driven program which insert, delete and display
the details of a product such as pid, pname and price using Stack.
Product=[]
c= “y”
while(c=="y" or c== "Y"):
print("1: Insert Product Details: ")
print("2: Delete Product Details: ")
print("3: Display Product Details:")
choice=int(input("Enter Your Choice: "))
if(choice==1):
pid=int(input("Enter Product Id:")
pname=input("Enter Product Name:")
price=float(input("Enter Product Price: ")
Prd=(pid,pname.price)
Product.append(Prd)
elif(choice==2):
if(Product==[]):
print("Stack Empty")
else:
print("Deleted Product is: "Product.pop())
elif(choice ==3):
L=len(Product)
while(L>0):
print(Product[L-1])
L=L-1
else:
print("Wrong input")
c=input("Do you want to continue?, Press ‘y’ to continue: ")
Output:
=RESTART: C:\Users\SP SHARMA\AppData\Local\Programs\Python\Python38-32\P-4.py
31 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Practical No-19: Write a menu driven program which insert, delete and display
the details of a club such as club_id, cname and city using Stack.
Club= []
c= ‘y’
while (c=="y" or c=="Y"):
print("1: Add Club Details: ")
print("2: Delete Club Details: ")
print("3: Display Club Details:")
choice = int(input("Enter choice: ")
if (choice == 1):
cid=int(input("Enter Club Id:"))
cname=input("Enter Club
Name:") city=input("Enter Club
City: ") clu= (cid,cname,city)
Club.append(clu)
elif (choice ==2):
if(Club==[]):
print("Stack Empty")
else:
print("Delete Element is: Club.pop())
elif (choice == 3):
L=len(Club)
while (L>0):
print(Club[L-1])
L=L-1
else:
print("Wrong Input")
c=input("Do you want to continue? Press ‘y’ to continue.")
Output:
33 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Import mysql.connector
con=mysql.connector.connect(host="localhost",username="root",passwd="root")
mycursor=con.cursor()
mycursor.execute("create database if not exists Sbvburarig")
mycursor.execute("use Sbvburarig")
mycursor.execute("create table if not exists book (bid int primary
key,bnamevarchar(20),bprice float(5,2))")
c= “y"
while(c=="y" or "Y"):
print("1. Press 1 for add new book: ")
print("2. Press 2 for Show the details of Books: ")
print("3. Press 3 for Update Book Details: ")
print("4. Press 4 for Delete Book Details: ")
print("5. Press 5 for Exit:")
choice=int(input("Enter Your Choice 1 or 2 or 3 or 4 or 5: "))
if(choice==1):
bid=int(input("Enter Book Id: "))
bname=input("Enter Book Name:")
bprice=float(input("Enter Book Price: "))
mycursor.execute("insert into book values(%s, %s, %s) ",
(bid,bname,bprice))
con.commit()
elif(choice ==2):
35 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Output:
= RESTART: C:\Users\S P SHARMA\AppData\Local\Programs\Python\Python38-321-4py
import mysql.connector
con=mysql.connector.connect(host ="localhost",username="root",passwd="root")
mycursor=con.cursor
mycursor.execute("create database if not exists Sbvburarig")
mycursor.execute("use Sbvburarig")
mycursor.execute("create table if not exists product (pid int primary key,pname
varchar(20),pprice float(8,2))")
c= “y”
while(c=="y" or c== "Y"):
print("1. Press 1 for add new product:")
print("2. Press 2 for Show the details of product:")
print("3. Press 3 for Update product Details: ")
Output:
-RESTART: C:\Users\S P SHARMA\AppData\Local\Programs\Python\Python38-32\P-4.py
import mysql.connector
con = mysl.connector.connect(host "localhost"username="root",passwd="root")
mycursor = con.cursor()
mycursor.execute("create database if not exists Sbvburari”)
mycursor.execute("use Sbvburarig”)
mycursor.execute("create table if not exists club (cid int primary
key,cnamevarchar(20) ,varchar(20))”)
c= “y”
while(c=="y" or "Y"):
print("1. Press 1 for add new club: ")
print("2. Press 2 for Show the details of club: ")
print("3. Press 3 for Update club Details:")
print("4. Press 4 for Delete club Details: ")
print("5. Press 5 for Exit:")
choice=int(input("Enter Your Choice 1 or 2 or 3 or 4 or 5: "))
if(choice ==1):
cid=int(input("Enter club Id:"))
cname=input("Enter club Name: ")
city=input("Enter club city:")
mycursor.execute("insert into club values(%s,%s,%s)",(cid,cname,city))
con.commit()
elif(choice==2):
mycursor.execute("select * from club")
myclubs=mycursor:fetchall()
for x in myclubs:
print(x)
elif(choice==3):
cid=int(input("Enter the club id for update:"))
cname=input("Enter club New Name:")
42 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Output:
=RESTART: C:\Users\SP SHARMA\AppData\Local\Programs\Python\Python38-32\P-4.py
1. Press 1 for add new club:
2. Press 2 for Show the details of club:
3. Press 3 for Update club Details:
4. Press 4 for Delete club Details:
5. Press 5 for Exit:
Enter Your Choice 1 or 2 or 3 or 4 or 5:1
Enter club id: 101
Enter club Name: C1
Enter club city: Delhi
Press 'y' for continue and 'n' for exit: y
1. Press 1 for add new club:
2. Press 2 for Show the details of club:
3. Press 3 for Update club Details:
4. Press 4 for Delete club Details
5. Press 5 for Exit:
Enter Your Choice 1 or 2 or 3 or 4 or 5: 1
Enter club Id: 102
import mysql.connector
con = mysl.connector.connect(host "localhost"username="root",passwd="root")
mycursor = con.cursor()
mycursor.execute("create database if not exists Sbvburari”)
mycursor.execute("use Sbvburarig”)
mycursor.execute("create table if not exists Student(sid int primary
key,snamevarchar(20), course varchar(20))”)
c= “y”
while(c=="y" or "Y"):
print("1. Press 1 for add new Student:")
print("2. Press 2 for Show the details of Students:")
prints( Press 3 for Update Student Detail:")
print("4. Press 4 for Delete Student Details:")
print( Press 5 for Exit: ")
choice=int(input("Enter Your Choice 1 or 2 or 3 or 4 or 5:")
if(choice==1):
Output:
import mysql.connector
con=mysql.connector.connect(host="localhost",username="root",passwd="root")
mycursor con.cursor()
mycursor.execute("create database if not exists Sbvburarig")
mycursor.execute("use Sbvburarig")
mycursor.execute (“create table if not exists movie (mid int primary key,mname
varchar(20),rating float(5,2))”)
c== “y”
while(c=="y" orc== “Y "):
print(“1. Press 1 for add new movie: ")
print(“ 2.Press 2 for Show the details of movie:")
print("3. Press 3 for Update movie Details:")
print("4. Press 4 for Delete movie Details:")
print("5. Press 5 for Exit:")
choice = input("Enter Your Choice 1 or 2 or 3 or 4 or 5:”)
if(choice==1):
mid=int[input("Enter movie id:")
mname=input("Enter movie Name:")
rating float(input("Enter movie rating: ")
mycursor.execute("insert into movie
values(%s,%s,%s,%s)",(mid_mname,rating))
con.commit()
elif(choice==2):
mycursor.execute("select * from movie")
mymovies=mycursor.fetchall()
for x in mymovies:
print(x)
elif(choice ==3):
mid=int(input("Enter the movie id for update:"))
mname=input("Enter movie New Name:")
49 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
OUTPUT:
=RESTART: C:\Users\SP SHARMA\AppData\Local\Programs\Python\Python 38-32\P-4py
import mysql.connector
con = mysl.connector.connect(host "localhost"username="root",passwd="root")
mycursor = con.cursor()
mycursor.execute("create database if not exists Sbvburari”)
mycursor.execute("use Sbvburarig”)
mycursor.execute("create table if not exists Student(eid int primary
key,enamevarchar(20), salary float(8,2))”)
c= “y”
while(c=="y" or "Y"):
print("1. Press 1 for add new Employee: ")
print("2. Press 2 for Show the details of Employees: ")
print (“3. Press 3 for Update Employee Detail: ")
print("Press 4 for Delete Employee Detail:”)
print("5. Press 5 for Exit:")
choice=int(input (“Enter Your Choice 1 or 2 or 3 or 4 or 5:")
if(choice==1):
eid=int(input("Enter Employee Id:”))
ename=input("Enter Employee Name:")
salary=input("Enter Employee Salary:")
mycursor execute("insert into Employee
values(%s,%s,%s)”(eid,ename,salary))
con.commit()
elif(choice==2):
mycursor.execute("select * from Employee")
myemp=mycursoc.fetchall()
for x in myemp:
print(x)
elif choice==3):
eid=int(input("Enter the Employee id for update: "))
ename=input("Enter Employee New Name:")
salary=input("Enter Employee New Salary:")
mycursor.execute("update Employee set ename=%s,
salary=%s where eid=%s",(ename,salary.eid))
con.commit()
elif(choice ==4):
eid=int(input("Enter the Employee id for delete: "))
mycursor.execute("delete from Employee where
eid=%s",(eid,))
con.commit()
elif(choice ==5):
break
else:
print("Wrong Choice")
c=input("Press 'y' for continue and 'n' for exit:")
Output:
Python 3.8.5 (3.8.558060, Jul 20 2020, 15:43:08) MSC 3526 32 bit (intel) on win32 Type "help",
"copyright", "credit" or "can" for more information.
Mysql Queries
Ques.1. Write a SQL query to create a database.
Ans:
To create a database we use create query.
Syntax:
Create database database_name;
To check/show the already created databases use the following query
Show databases ;
Syntax:
Create table table_name(col_name1 type primary key,col_name2 type, …..);
Ans: To delete the specific record from the table use delete command/query.
Syntax:
Delete from table_name where condition;
Note: Ifwe don’t use where clause it delte all the records one by one from the
table.
Ans: UPDATE:
Update is a SQL query used to update/change/modify the record of a table.
Syntax
updatetable name set col_name=value,col_name=value,….where condition;
Ques.8: Write a SQL query to find the average marks from the
student table.
Ans:
Aggerate Function:
Aggerate Function in SQL:
1. SUM( ): Find the sum of the values of specific column.
2. MAX( ): Find the maximum values from the specific column.
3. MIN( ): Find the manimum values from the specific column.
4. AVG( ): Find the average of all values from the specific column.
5. COUNT( ) : Count the value from the specific column.
Ans:
Ans:
Ans:
Ans:
Ans:
Ans:
Ans:
Ans:
Ans:
1. DROP Command
The DROP command is used to remove a table, database, or other database objects completely from the
database.
Effect:
o It deletes the entire table, including its structure (schema), data, and indexes.
o Once dropped, the table cannot be recovered (unless a backup exists).
69 AMAN PAL GSBV BURARI, DELHI
CS Practical File Session 2024-25 CLASS 12
Example:
2. DELETE Command
The DELETE command is used to remove rows from a table based on a condition. The data is deleted row by row,
and the table structure remains intact.
Effect:
o Deletes data from a table.
o The table structure, columns, and indexes remain.
o The deletion can be conditional (using a WHERE clause).
o Supports rollback if wrapped in a transaction (since it is a DML command).
Example:
To delete specific rows based on a condition (e.g., delete students with age > 20):
3. TRUNCATE Command
The TRUNCATE command is used to remove all rows from a table, but unlike DELETE, it does not log individual
row deletions, making it faster.
Effect:
o Removes all rows in the table.
o Does not remove the table structure (only data).
o Cannot be selective (no WHERE clause).
o Cannot be rolled back in many systems (unless wrapped in a transaction).
o Resets auto-increment counters (if the table has an auto-increment field).
Example:
Ques.24: Write the sort notes on group by, having and where
clause with example.
Ans:
1. GROUP BY Clause
The GROUP BY clause is used in SQL to group rows that have the same values in specified columns into
summary rows. It is often used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX() to
perform operations on each group of rows.
Purpose:
To aggregate data and apply functions to groups of rows rather than individual rows.
Syntax:
Example:
To find the total marks for each student in a table student_marks grouped by the student name:
2. HAVING Clause
The HAVING clause is used in SQL to filter records that have been grouped by the GROUP BY clause. It is
similar to the WHERE clause but is applied after grouping data.
Purpose:
To filter groups or aggregate results based on conditions, especially when using aggregate functions.
Syntax:
Example:
To find the students whose total marks are greater than 200 from the student_marks table:
3. WHERE Clause
The WHERE clause is used to filter rows before any grouping or aggregation takes place. It is used to specify the
conditions that must be met for a row to be included in the result set.
Purpose:
To filter records based on specified conditions before applying any grouping or aggregation.
Syntax:
Example:
To get the details of students who scored more than 50 marks from the student_marks table:
Ques.25: Write the SQL query to find out the square root of 26.
Ans:
Ques.29: Write the SQL Query for inner join of two tables
Emp(eid, ename, salary, dept_id) and Dept(dept_id, dname).
Ans:
Ques.30: Write the SQL Query for full outer join of two tables
Emp(eid, ename,salary,dept_id) and Dept(dept_id, dname).
Ans:
Ans:
Ans:
Ans:
Ans:
Ans:
Similarity: Column with both the constraints will only take unique values.
Difference: Column with Primary key constraints will not be able to hold NULL values
while Column with Unique constraints will be able to hold NULL values.
CHAR data type is used tostore VARCHAR data type is used to store
1. character strings of fixed length. character strings of variable length.
In CHAR, If the length of the string is In VARCHAR, If the length of the string
2. less than set or fixed-length then it is is less than the set or fixed-length then
padded with extra memory space. it will store as it is without padded with
extra memory spaces.
CHAR stands for "Character". VARCHAR stands for "Variable
3. Character".
Storage size of CHAR data types is The storage size of the VARCHAR data
4. equal to n bytes i.e. set length. type is equal to the actual length of the
entered string in bytes.
We should use the CHAR data type We should use the VARCHAR data type
5. when we expect the data values in a when we expect the data values in a
column are ofthe same length. column are of variable length.
CHAR takes 1 byte for each character. VARCHAR takes 1 byte for each
6. character and some extra bytes for
holding length information.
Better performance than VARCHAR(). Performance is not good as compared to
7. CHAR().
Ans:
1. COUNT(column_name)
• Definition:
COUNT (column_name) counts only the non-NULL values in the specified column. It
evaluates the values in a specific column and ignores rows where the value in that column
is NULL.
• Key Characteristics:
o If a column has NULL values, those rows are excluded from the count.
o The function focuses on the presence of meaningful, non-NULL data in the specified
column.
• Use Case:
Use COUNT (column_name) when you want to count how many non-NULL values
exist in a particular column. This is helpful when you're interested in data
completeness or valid entries for a specific field.
Example:
• Query:
• Result:
The query returns 3 because the row with a NULL value is excluded.
2. COUNT(*)
• Definition:
COUNT(*) counts all rows in the table, regardless of whether they contain NULL values in
any column. It does not evaluate any specific column but instead counts each row as a
whole.
• Key Characteristics:
o Includes all rows, even if all columns in a row contain NULL values.
o Used to calculate the total number of rows in a table or a query result set.
• Use Case:
Use COUNT(*) when you want the total number of rows in a table or when
checking the overall row count, regardless of the values in any particular
column.
• Example:
Query:
• Result:
The query returns 4 because all the row, including the one with a NULL value,
are counted.
Key Differences
1. NULL Handling:
• COUNT (column_name) ignores rows where the specified column has NULL
values.
• COUNT(*) counts all rows, including those with NULL values in the specified
column or even if all columns are NULL.
2. Scope of Operation:
3. Purpose:
Practical Scenarios
2. Counting All Rows in a Table: To find the total number of employees in the table,
including those who haven't provided salary information, use:
3. Combining Both: To compare the total num rows with the number of that have
non- NULL salary values, you can use:
OUTPUT:
Conclusion
• Use COUNT (column_name) when you need to count only the meaningful,
non-NULL entries in a specific column.
• Use COUNT(*) when you want to count all rows in a table, regardless of the
Presence of NULL values.