Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Informatics Practices - Practical Experiments

Data Handling
Pandas Series
Exp :1. Create a panda’s series from a dictionary of values and a ndarray.
Program:
import pandas as pd
import numpy as np
# Creating Series Using Dictionary
dsi=pd.Series({'Jan':31,'Feb':29,'Mar':31})
f={'a':5.5,'b':7.7,'c':9.9}
dic={10:100,11:200,12:300,13:400}
dsi2=pd.Series(data=f)
dsi3=pd.Series({'Year':2020,3:18,12:'December'})
di=pd.Series(data=dic,index=[10,11,12,13])
di2=pd.Series(data=dic,index=[10,111,12,13,14])
di3=pd.Series(data=dic,index=range(10,12))
print(dsi,"\n")
print(dsi2,"\n")
print(dsi3,"\n")
print(di,"\n")
print(di2,"\n")
print(di3,"\n")
# Creating Series Using ndarray
di=np.array([10,20,30,40,50])
df=np.array([10.10,20.22,30.33,40.44,50.55])
ds=np.array(['MSD','VK','RH','RD','YS'])
da=np.array({'Jan':31,'Feb':29,'Mar':31})
pi=pd.Series(data=di, dtype='float')
pf=pd.Series(data=df)
ps=pd.Series(data=ds,index=[10,20,30,40,50])
1|Page
pa=pd.Series(da,index=['a','b','c'])
print(pi,"\n")
print(pf,"\n")
print(ps,"\n")
print(pa,"\n")
Output:

Exp:2. Create a Pandas Series using Scalar Values.


Program:
import pandas as pd
s=pd.Series(55,index=['a','b','c','d','e'])
n=pd.Series(55,index=[0,1,2,3,4])
ss=pd.Series('Welcome to KPCVS IP Class XII', index=['Rohit','Yuvi','Dhoni','Kohli'])
print(s)
print(n)
print(ss)

2|Page
Output:

Exp:3. Create a Pandas Series using Range Function.


Program:
import pandas as pd
s1=pd.Series(range(5))
s2=pd.Series(range(1,6,2))
print(s1)
print(s2)
Output:

Exp:4. Create a Pandas Series with range and for loop.


Program:
import pandas as pd
s=pd.Series(range(1,15,3),index=[x for x in 'abcde'])
ss=pd.Series(range(0,5),index=[x for x in 'abcde'])
print(s)
print(ss)
3|Page
Output:

Exp:5. Create a Pandas Series for missing values using NaN (Not a Number)
Program:
import pandas as pd
import numpy as np
s=pd.Series([7.5,4,4.5,np.NaN,-34.5])
print(s)
Output:

Exp:6. Create a Pandas Series for mathematical expression, exponentiation and


NumPy.
Program:
import pandas as pd
import numpy as np
ss=np.arange(10,15)
print(ss)
s=pd.Series(index=ss,data=ss*4)
s1=pd.Series(index=ss,data=ss+4)
s2=pd.Series(index=ss,data=ss**2)
s.index.name='INDEX'
print(s)
print(s1)
print(s2)
4|Page
Output:

Exp:7. Write a Pandas Series Program to Perform Some of the Object Attribute
Functions.
Program:
import pandas as pd
data=pd.Series(range(1,15,3),index=[x for x in 'abcde'])
print(data)
print('Has NaNs: ',data.hasnans)
print('Shape : ',data.shape)
print('Data Type : ',data.dtype)
print('Dimension : ',data.ndim)
print('Index Value : ',data.index)
print('No.of Bytes: ',data.nbytes)
print('Values in Series: ',data.values)
print('Size : ',data.size)
print('Series Empty: ',data.empty)
print('Axis: ',data.axes)

5|Page
Output:

Exp:8. Create a Pandas Series to perform the Mathematical and Vector Operations
on Series Elements.
Program:
import pandas as pd
s1=pd.Series([11,12,13,14,15])
s2=pd.Series([22,24,23,24,25])
s3=pd.Series([11,12,13,14,15], index=([101,102,103,104,105]))
print('Addition :',s1+s2)
print('Subtraction :',s2-s1)
print('Multiplication :',s1*s2)
print('Division :',s2/s1)
print('Floor Division :',s2//s1)
print('Modules :',s2%s1)
print('Addition :',s1+s3)
print('Vector Multiply:',s1*3)
print('Vector Multiply:',s2+10)
print('Vector Power:',s1**2)

6|Page
Output:

Exp:9. Create a Pandas Series using Head () and Tail () Functions.


Program:
import pandas as pd
HT=pd.Series([8,10,17,18,19,25,26,30], index=['a','b','c','d','e','f','g','h'])
D=pd.Series({1:1.1,2:22,3:33.,4:44,5:5.5,6:66,7:7.7})
print(HT)
print(HT.head())
print(HT.tail())
print(HT.head(3))
print(HT.tail(2))
print(D)
print(D.head(3))
print(D.tail(2))
7|Page
Output:

Exp:10. Create a Pandas Series to access data from it, with position (Slicing &
Indexing).
Program:
import pandas as pd
s=pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
print(s)
print(s[0])
print(s['c'])
print(s[:3])
print(s[-3:])
print(s[1:5])
print(s[2:-2])

8|Page
Output:

Exp:11. Create a Pandas Series to access elements of series using ‘loc’ and ‘iloc’.
Program:
import pandas as pd
s=pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
ss=pd.Series(['a','b','c','d','e'],index=[1,2,3,4,5])
print(s.iloc[1:4])
print(s.loc['b':'e'])
print(ss.iloc[2:5])
print(ss.iloc[2:-2])
Output:

9|Page
Exp:12. Create a Pandas Series & Retrieve the Data using Some Conditions.
Program:
import pandas as pd
s=pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
ss=pd.Series([10,20,30,40,50],index=[1,2,3,4,5])
print(s<10)
print(ss[ss<30])
print(ss[ss==10])
print(ss[ss>=30])
print(ss[ss!=30])
Output:

Exp :13. Create a Series and print all the elements that are above the 75th percentile.
Program:
import pandas as pd
import numpy as np
s=pd.Series(np.array([7,10,27,18,99,17,888,333,33,9]))
print(s)
res=s.quantile(q=0.75)
print("\n")

10 | P a g e
print('75th Percentile of the Series is : ')
print(res)
print("\n")
print('The Elements that are above the 75th Percentile: ')
print(s[s>res])
Output:

Pandas Data Frame:


Exp:14. Create a Data Frame from Dictionary, Dictionary of Series, 2darray and
also create an Empty Data Frame.
Program:
import pandas as pd
dict1 ={'m':1, 'n':2, 'o':3, 'p':'Python'}
dict2 ={'m':5, 'n':6, 'o':7, 'p':8, 'q':9.9}
Data = {'first':dict1, 'second':dict2}
df = pd.DataFrame(Data)
print(df)
Dic2 = {'One':pd.Series([1, 3],index=['a','b']), 'Two':pd.Series([3, 4],index=['a','b'])}
dfseries = pd.DataFrame(Dic2)
print(dfseries)

11 | P a g e
d1 =[[2, 3, 4], [5, 6, 7],[8, 9, 10]]
d2 =[[2, 4, 8], [1, 3, 9],[11,15,18]]
Data ={'First': d1, 'Second': d2}
df2d = pd.DataFrame(Data)
print(df2d)
dff = pd.DataFrame()
print(dff)
Output:

Exp:14. Create a Data Frame for Employee Details and Access the elements using
Head () and Tail () Functions.
Program:
import pandas as pd
dict1={101:'Rahul',102:'Kohli',103:'Dhoni',104:'Yuvi',105:'Sachin',106:'Dravid',
107:'Rohit',108:'Ganguly'}
dict2 ={101:26, 102:31,103:39,104:38,105:45,106:44,107:34,108:44}
dict3 ={101:'Developer',102:'TeamLeader',103:'ProjectHead',104:'Developer',
105:'Manager',106:'Tester',107:'Designer',108:'COE'}
dict4 ={101:17500, 102:27500,103:48500,104:18500,105:45000,106:35000,
107:20500,108:75500}
Data = {'Name':dict1, 'Age':dict2, 'Role':dict3,'Salary':dict4}
12 | P a g e
df = pd.DataFrame(Data)
print(df,'\n')
df.index.name='Roll_No'
print(df.head(),'\n')
print(df.tail(),'\n')
print(df.head(2),'\n')
print(df.tail(1),'\n')
Output:

13 | P a g e
Exp:15. Create a Data Frame and Update the Elements using Iteration Function.
Program:
import pandas as pd
names = pd.Series(['Lakshmi','Madhu','Pranee','Manju'])
m1 = pd.Series([96.0,75.5,91.0,65.0])
m2 = pd.Series([96.0,85.5,65.0,85.0])
m3 = pd.Series([96.0,65.5,63.0,65.0])
stud={'Name':names,'M1':m1,'M2':m2,'M3':m3}
df1=pd.DataFrame(stud,columns=['Name','M1','M2','M3','Total','Percentage','Grade'])
lstTotal=[] # initializing the list
per=[]
lstgrade=[]
print("\n")
print(df1)
for (row,rowseries) in df1.iterrows():
total= rowseries['M1']+rowseries['M2']+rowseries['M3']
lstTotal.append(total)
per.append(total//3) #floor/integer divsion
df1['Total']=lstTotal
df1['Percentage']=per
print("\n")
for (col,colseries) in df1.iteritems(): # for loop for col
length=len(colseries)
if col == 'Percentage':
lstgrade=[]
for row in range(length): # for loop for row
mrks=colseries[row]
if mrks >=90: # if statement to calculate the grade
lstgrade.append('A+')

14 | P a g e
elif mrks >=70:
lstgrade.append('A')
elif mrks >=60:
lstgrade.append('B')
elif mrks >=50:
lstgrade.append('C')
elif mrks >=40:
lstgrade.append('D')
else:
lstgrade.append('F')
df1['Grade']=lstgrade
print('Data Frame with grade added given below')
print(df1)
df1.describe()
Output:

Exp:16. Write a Python Program to Perform following Operations like Add, Select,
Delete & Rename Data in Rows & Columns of Data Frame.
Program:
import pandas as pd
dic={'A':[10,11,12],'B':[21,22,23],'C':[31,32,33]}
df=pd.DataFrame(dic,index=['one','two','three'])

15 | P a g e
dc={'AA':[10,11],'BB':[21,22], 'CC':[31,32]}
df2=pd.DataFrame(dc)
print("Dictionary1:\n",df)
print('='*50)
print("Dictionary2:\n",df2)
print('='*50)
dfir=df2.rename(index={0:7})
print("Rename the Dictionary2 Row:\n",dfir)
print('='*50)
dfcr=df.rename(columns={'B':5})
print("Rename the Dictionary1 Column:\n",dfcr)
print('='*50)
df['D']=[41,42,43]
print("Add a Column to Dictionary1 :\n",df)
print('='*50)
df.insert(2,'E',[51,52,53],True)
print("Add a Column to Dictionary1 at Position :\n",df)
print('='*50)
newrow=pd.Series(data={'AA':15,'BB':25})
ar=df2.append(newrow,ignore_index=True)
print("Add Row to Dictionary1:\n",ar)
print('='*50)
dic={'A':[10,11,12],'B':[21,22,23],'C':[31,32,33]}
df=pd.DataFrame(dic,index=['one','two','three'])
dc={'AA':[10,11],'BB':[21,22],'CC':[31,32]}
df2=pd.DataFrame(dc)
de=df.drop(columns=['C'])
print("Delete Column C from Dictionary1:\n",de)
print('='*50)

16 | P a g e
de2=df2.drop([0])
print("Delete Row [0] from Dictionary2:\n",de2)
print('='*50)
print("Select Columns[AA] from Dictionary2:\n",df2['AA'])
print('='*50)
print("Select Row[0] from Dictionary1:\n",df.iloc[0])
Output:

17 | P a g e
Exp:17. Create a Data Frame for Accessing data using loc & iloc (Indexing using
Labels).
Program:
import pandas as pd
cols = ['Red','Green','Blue','Yellow','Orange']
cont = [18,15,20,26,12]
price = [120,110,125,150,90]
datas={'Colors':cols,'Count':cont,'Price':price}
df1 = pd.DataFrame(datas,index=['Apple','Grapes','Blueberry','Mango','Orange'])
print(df1)
print("Indexing using Slicing")
print('='*30)
print(df1.loc['Apple',:])
print('='*30)
print(df1[df1['Count']>25])
print('='*30)
print((df1['Price']>100).all())
print('='*30)
print(df1.loc[['Blueberry'],['Colors','Price']])
print('='*30)
print(df1.loc['Grapes':'Mango',['Count']])
print('='*30)
print(df1.iloc[0:3])
print('='*30)
print(df1.iloc[[1,3]])
print('='*30)
print(df1.iloc[2:3,0:1])

18 | P a g e
Output:

Exp:18. Create Data Frames to perform Concatenation, Merge & Join Indexing.
Program:
import pandas as pd
print('='*50)
print("Concatenation Indexing")
print('='*50)
adf1 = pd.DataFrame({'Name':['Arun','Aravind'],'Age':[15,16]},index=[11,12])
adf2 = pd.DataFrame({'Name':['Ramesh','Rajesh'],'Age':[30,32]},index=[13,14])
act=adf1.append(adf2)
print(act,"\n")
dfc= pd.DataFrame({'Name':['Arun','Aravind'],'Age':[15,16]})
dfc2 = pd.DataFrame({'Name':['Ramesh','Rajesh'],'Age':[30,32],10:[55,99]})
cdf=pd.concat([dfc,dfc2])
19 | P a g e
print(cdf)
print('='*50)
print("Merge Indexing")
print('='*50)
dd = pd.DataFrame({'Name':['VK','MSD','SR'],'Age':[31,37,36],'ID':[27,33,24]})
ee = pd.DataFrame({'Name':['VK','MSD','SR'],'Age':[31,37,36],'Salary':[27000,33000,
24000]})
f=pd.merge(dd,ee)
print(f,"\n")
ba = pd.DataFrame({'Name':['Cat','Rat'],'Dno':[12,10],'UID':[16,18]})
dc= pd.DataFrame({'Name':['Cat','Dog'],'Age':[8,9],'MSalary':[7000,3000]})
ee=pd.merge(ba,dc,how='right',on='Name')
print(ee,"\n")
print('='*50)
print("Join Indexing")
print('='*50)
import pandas as pd
xx=pd.DataFrame({'Name':["Ram","Rajesh","Rubun","Ramesh"],'Degree':["B.E",
"BCA","B.Tech","MBBS"]})
yy=pd.DataFrame({'Degree2':["M.E","MCA","M.Tech","P.hD"],'Score':[80,85,82,78]})
zz=xx.join(yy)
print(zz,"\n")
xix=pd.DataFrame({'Name':["Sam","Rakesh","Rahul","Meeran"],'Degree':["B.E",
"BCA","B.Tech","MBBS"],'Key':[11,22,88,99]})
yiy=pd.DataFrame({'Degree2':["M.E","MCA","M.Tech","P.hD"],'Score':[80,85,82,78]}
,index=[11,55,66,77])
ziz=xix.join(yiy,on='Key')
print(ziz,"\n")
x=pd.DataFrame({'Name':["Sam","Rakesh","Rahul","Meeran"],'Degree':["B.E","BCA",
"B.Tech","MBBS"]},index=[11,22,33,44])

20 | P a g e
y=pd.DataFrame({'Degree2':["M.E","MCA","M.Tech","P.hD"],'Score':[80,85,82,78]},
index=[11,55,66,77])
z=x.join(y,how='outer')
print(z,"\n")
xi=pd.DataFrame({'Name':["Sam","Rakesh","Rahul","Meeran"],'Degree':["B.E",
"BCA","B.Tech","MBBS"]},index=[11,22,33,44])
yi=pd.DataFrame({'Degree2':["M.E","MCA","M.Tech","P.hD"],'Score':[80,85,82,78]},
index=[11,55,66,77])
zi=xi.join(yi,how='inner')
print(zi,"\n")
print('='*50)

Output:

21 | P a g e
Exp:19. Create a program for Importing and Exporting Data between Pandas and
CSV File.
Program:
import pandas as pd
print("\n")
Name=['Mahi','Yuvi','Kohli','Rohit','ABD']
Degree=['B.E','MBA','M.Tech','MBBS','M.E']
Score=[490,488,492,496,482]
dict={'Name':Name,'Degree':Degree,'Score':Score}
df=pd.DataFrame(dict)
print(" The File 'Exp.CSV‘ is Created(Imported) ")
df.to_csv('Exp.csv')
print("\n")
df2=pd.read_csv('FILE3.csv')
print("\n")
print(" The File Content of 'FILE3.csv' is Received(Readed)\n ")
df2.index.name='Index_No'
print(df2)
22 | P a g e
Output:

Exp:20. Create a Data Frame Quarterly Sales where each row contains the item
category, item name, and expenditure. Group the rows by the category and print
the total expenditure per category.
Program:
import pandas as pd
d={'ItemCategory':['Mobile', 'Laptop', 'DSLR Camera', 'Earbuds', 'Smart Watch', 'DSLR
Camera', 'Mobile', 'Laptop', 'Mobile'],
'ItemName':['Google Pixel', 'HP', 'Cannon', 'Sony', 'Apple', 'Nikon', 'iPhone', 'Dell',
'OnePlus'],
'Expenditure':[50000,100000,75000,12000,18000,66000,65000,90000,40000]}

23 | P a g e
df=pd.DataFrame(d)
print(df)
QS=df.groupby('ItemCategory')
print(' DataFrame After Grouping \n')
print(QS['ItemCategory','Expenditure'].sum())
print("\n")
Output:

Exp:21. Create a Data Frame for examination results and display row labels, column
labels data types of each column and the dimensions.
Program:
import pandas as pd
import numpy as np
TNS=np.array([200,180,175,188,196,180,181,191,178,180,200,200])
TNSP=np.array([200,180,174,186,196,180,180,191,178,180,199,200])
PP=TNSP/TNS
d={'Class':['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'],
'Total_No.of_Stud_Appear':[200,180,175,188,196,180,181,191,178,180,200,200],
'Total_No.of_Stud_Pass':[200,180,174,186,196,180,180,191,178,180,199,200],
'Pass_%':PP*100}

24 | P a g e
Result=pd.DataFrame(d)
print(Result)
print(Result.dtypes)
print('Shapes of the DataFrame is : ')
print(Result.shape)
Output:

Exp:22. Filter Out the Rows Based on different Criteria such as Duplicate Rows.
Program:
import pandas as pd
d={'Name':['Rohit','Dhoni','Rohit','Ganguly','Yuvaraj','Rohit','Dhoni','Kohli','Sachin','Kohli'],

'High_Score_ODI':[264,183,209,183,150,209,224,183,200,183],
'ODI_ Score':[9115,10773,9115,11363,8701,9115,10773,11867,18426,11867]}
Result=pd.DataFrame(d)
DR=Result[Result.duplicated(keep=False)]
print(Result)
print('\n')
print(DR)

25 | P a g e
Output:

Data Visualization:
Exp:1. Write a Python Program to plot Line Chart for Salary Hike of an Employee.
Program:
import matplotlib.pyplot as pl
Year = [2000,2004,2005,2006,2008,2010,2012,2014,2015,2016,2018,2020]
Salary= [10000,14000,18000,20000,24000,28000,30000,34000,38000,40000,44000,48000]

pl.plot(Year,Salary,label= 'Salary',)
pl.xlabel ('Years')
pl.ylabel ('Salary')
pl.title('Salary Hike of an Employee', fontsize=20)
pl.legend(loc='lower right')
pl.show()
Output:

26 | P a g e
Exp:2. Write a Python Program to plot the Pass Percentage of the Year 2019 & 2020,
Classes 6th to 12th using Line Chart.
Program:
import matplotlib.pyplot as pl
Class2019=[6,7,8,9,10,11,12]
PP2019=[98,98,98,90,98,86,98]
pl.plot(Class2019,PP2019,label= 'Year 2019',)
Class2020=[6,7,8,9,10,11,12]
PP2020=[100,100,100,96,100,92,100]
pl.plot(Class2020, PP2020, label= 'Year 2020')
pl.xlabel ('Class Name in Number',fontsize=16)
pl.ylabel ('Pass Percentage %',fontsize=16)
pl.title('Pass Percentage of the Years 2019 & 2020',fontsize=20)
pl.legend(title='Pass% IN')
pl.show()

Output:

Exp:3. Write a Python Program to plot Line Chart using some Random Value.
Program:
import matplotlib.pyplot as pl
import numpy as np
RV=np.arange(1,20,1)
LV=np.log(RV)

27 | P a g e
SV=np.sin(RV)
CV=np.cos(RV)
pl.plot(LV,label='Logarithm Value')
pl.plot(SV,label='Sine Value')
pl.plot(CV,label='Cosine Value')
pl.xlabel("Random Values")
pl.ylabel("Logarithm, Sine & Cosine Values")
pl.title('Line Chart using Random Values')
pl.legend(loc='best')
pl.show()
Output:

Exp:4. Write a Python Program to display a Histogram Graph for Blood Sugar
Values based on No. of Patients.
Program:
import matplotlib.pyplot as pl
BloodSugar=[115,86,90,150,147,88,93,115,135,80,77,82,129]
pl.title("BloodSugar Value & No.of.Patients")
pl.xlabel("BloodSugar Value ")
pl.ylabel("No.Of.Patients")
pl.hist(BloodSugar,bins=[75,100,125,150])
pl.legend(['Men'],title="Histogram",loc='upper right')
pl.show()
28 | P a g e
Output:

Exp:5. Given the school result data, analyses the performance of the students on
different parameters, e.g. subject wise or class wise.
Program:
import matplotlib.pyplot as pl
Subject=['Maths','Phy.','Chem.','Bio.','C.Sc.','English','Tamil','Hindi']
Class=['XI','XII']
Sub_Percentage=[86,84,78,86,94,87,90,88]
Class_Percentage=[90,100]
pl.bar(Subject,Sub_Percentage,align='center')
pl.bar(Class,Class_Percentage)
pl.xlabel('Subject & Class Names', fontsize=18)
pl.ylabel('Pass Percentage', fontsize=18)
pl.title('Student Result Analysis',fontsize=22)
pl.show()

29 | P a g e
Output:

Exp:6. For the Data Frames created above, analyse and plot appropriate charts with
title and legend.
Program:
import matplotlib.pyplot as pl
import numpy as np
Subject=['Maths','Sci.','Social','English','T/H']
UT1_Percentage=[56,54,40,50,55]
UT2_Percentage=[62,60,42,55,60]
UT3_Percentage=[50,60,40,54,65]
MT1_Percentage=[66,63,41,55,50]
l=np.arange(len(Subject))
pl.bar(l,UT1_Percentage,width=.25,label='UT1')
pl.bar(l+.25,UT2_Percentage,width=.25,label='UT2')
pl.bar(l+.50,UT3_Percentage,width=.25,label='UT3')
pl.bar(l+.75,MT1_Percentage,width=.20,label='MT1')
pl.xticks(l,Subject)
pl.xlabel('Test Names', fontsize=18)
pl.ylabel('Test Pass Percentage', fontsize=18)
30 | P a g e
pl.title('Student Result Analysis',fontsize=22)
pl.legend(title="TestNames",loc='best')
pl.show()
Output:

Exp:7. Take Data of your interest from an open source (e.g. data.gov.in), aggregate
and summarize it. Then plot it using different plotting functions of the Matplotlib
Library.
Program:
import pandas as pd
import matplotlib.pyplot as pl
cf=pd.read_csv("PEDV.csv")
print(cf,'\n')
s=(cf['Team'].head(12))
s2=(cf['Salary'].head(12))
pl.bar(s,s2)
pl.xlabel('Name of the Team', fontsize=18)
pl.ylabel('Salary Range', fontsize=18)
pl.title('Aggregated and Summarized Data',fontsize=22)
pl.legend(‘Salary’, loc=’best’)
pl.show()

31 | P a g e
Output:

32 | P a g e
Database Management:
Exp:1. Create a student table with the student id, name and marks as attributes
where the student’s id is the primary key.
Program:

Output:

Exp:2. Insert the details of a new student in the above table (Student).
Program:

Output:

33 | P a g e
Exp:3. Delete the details of a student in the above table (Student).
Program:

Output:

Exp:4. Use the select command to get the details of the students with marks more
than 80 in the above table (Student).
Program:

Output:

Exp:5. Find the Min, Max, Sum and Average of the Marks in the Student Mark
Table.
Program:

34 | P a g e
Output:

Exp:6. Find the total number of customers from each country in the table
(customer_ID, customer_name, country) using group by.
Program:

Output:

35 | P a g e
Exp:7. Write a SQL command to Order the (Student ID, Marks) table of marks in
descending order.
Program:

Output:

Exp:8. Find the Record which having the Customer Name ‘AB de Villiers’, from
each country in the table (customer id, customer name, country) using group by &
having function.
Program:

Output:

Exp:9. Write a SQL Query to Find the “POWER, MOD” of Marks and “ROUND”
of the Percentage in the Table (Name, Marks, Percentage).
Program:
select * from StudResult;
select POWER(Marks,2) from StudResult;
select MOD(Marks,5) from StudResult;
select ROUND(Percentage) from StudResult;

36 | P a g e
Output:

37 | P a g e
Exp:10. Write a SQL Query to Find the “LENGTH, INSTR” of Book Name and
Convert the Book Name using “LCASE, UCASE”, in the Table (Book Details).
Program:
Select * from BookDetails;
select LENGTH(Book_Name)from BookDetails where Book_Price>400;
select INSTR(Book_Name,'a')from BookDetails where Book_Price>=400;
select LCASE(Book_Name)from BookDetails where Book_Price=500;
select UCASE(Book_Name)from BookDetails where Book_Price<=450;
Output:

38 | P a g e
Exp:11. Write a SQL Query to Select the Book Name, using “MID, LEFT, RIGHT,
LTRIM, RTRIM” in the Table (Book No, Book Name, Book Price).
Program:
Select * from BookDetails;
select MID(Book_Name,10,20)from BookDetails where Book_Price=455;
select LEFT(Book_Name,7)from BookDetails where Book_Price=370;
select RIGHT(Book_Name,12)from BookDetails where Book_Price=370;
select LTRIM(Book_Name)from BookDetails where Book_Price=500;
select RTRIM(Book_Name)from BookDetails where Book_Price=500;
Output:

39 | P a g e
Exp:12. Consider the table Loan_Account (Account Number, Customer Name,
Loan Amount, Instalments, Interest Rate, Start Date) and get the answer for
following SQL Queries.
Write a SQL Query to Returns the “DAY, DATE, MONTH & YEAR” of Start Date
in the Table.
Program:
select * from loan_account;
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
DAY(Start_Date) from loan_account where Interest_Rate<12.55;
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
DATE(Start_Date) from loan_account where Interest_Rate<12.55;
select AccountNumber, Customer_Name, Loan_Amount, Instalments,
Interest_Rate,MONTH(Start_Date) from loan_account where Interest_Rate<12.55;
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
YEAR(Start_Date) from loan_account where Interest_Rate<12.55;

40 | P a g e
Output:

41 | P a g e
Exp:13. Write a SQL Query to Return the “NOW, DAYNAME, MONTHNAME”
of Start Date in the Table (Use the table Loan_Account)
Program:
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
NOW(Start_Date) from loan_account where Interest_Rate<12.55;
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
DAYNAME(Start_Date) from loan_account where Interest_Rate<12.55;
select AccountNumber, Customer_Name, Loan_Amount, Instalments, Interest_Rate,
MONTHNAME(Start_Date) from loan_account where Interest_Rate<12.55;
Output:

42 | P a g e

You might also like