Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

Informatics Practices

Practical File
2023-24

SUBMITTED BY:
Roll no:
Name: Harsh Rautella
Class: XII G
Submitted To:

Mr. SWAPAN KAPURIA Mrs. VANDAN TANDON


(PGT. Comp. Sc.) (Principal)
No. Name of Practical Date Pag Sign of
e no. the
Teacher
1. Create a pandas series from a dictionary of
values. Display 3 top rows using head ()

2. Create a pandas Series from an ndarray of


values. Display 3 Rows from bottom using tail()
3. Create a series and show different types of
selection like
i. retrieve 1st 3 rows
ii. Slice upto and including a particular label
4.
Draw the following bar graph representing the
number of students in each class.

5. Create a series having values 3,4,1,10,9,8,7.


Arrange the data in the series in Ascending
order and also in Descending order.
6. Create a Series using a ndarray of values and
show mean, median, maximum value, minimum
value, mode.
7. 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.
8. Create a data frame for examination result and
display row labels, column labels data types of
each column and the dimensions
9. Filter out rows based on different criteria such
as duplicate rows..
10. Find the sum of each column, or find the
column with the lowest mean.
11. Do the following :
1. locate the 3 largest values in a dataframe
2. subtract the mean of a row from each
element of the row in a dataframe.
3. replace all negative values in a dataframe
with a 0.
4. replace all missing values in a dataframe
with a 999.

12 A dictionary Grade contains the following data:


Grade={'Name':['Rashmi', 'Harsh', 'Ganesh',
'Priya', 'Vivek', 'Anita', 'karthik'], 'Grade':
['A1', 'A2', 'B1', 'A1', 'B2', 'A2', 'A1']}
Write statements for the following:
a. Create dataFrame called GR.
b. Find the output of GR.iloc[0:5] and GR[0:5}
c. Add a column called percentage with following
data: [92, 89, None, 95, 68, None, 93]
d. Rearrange the columns as Name, Percentage
and grade
e. Drop the column (i.e. Grade) by name
f. Delete the 3rd and 5th rows
g. What does the following will do?
i. Gr.drop(0, axis=0)
ii. Gr.drop(0, axis="index")
iii. Gr.drop([0, 1, 2, 3], axis=0

13. .Importing and exporting data between


pandas and CSV file
14. Implement Describe method on a dataframe
display its output.
15. Write a program to iterate over a dataframe
containing names and marks, which then
calculates grades as per marks and adds
them to the grade column.
Marks Grade
Marks>=90 A+
Marks 70-90 A
Marks 60-69 B
Marks 50-59 C
Marks 40-49 D
Marks <40 F
16. Consider a DataFrame ndf as shown below:
Name Sex position City Age Project
Budget
0 Rabia F Manager banglore 30 13 48
1 Evan M Programmer Ndelhi 27 17 13
2 Jia F Manager Chennai 32 16 32
3 Lalit M Manager Mumbai 40 20 21
4 Jaspreet M Programmer Chennai 28 21 17
5 Suji F Programmer bangalore 32 14 10

• Create the above dataframe and do the


following
• Print the details of the youngest
employee in the dataframe
• Print the details of the employee
handling the maximum number of
projects
• Print the average budget allotted
17. Create the following data frame using list

Fruits Pulses Rice Wheat


Tripura 44.1 23.2 814.6 0.5
Gujrat 11950.0 818.0 1930.0 2737.0
Punjab 7152.0 33.0 11586.2 16440.5
Uttar_P 140169.2 2184.4 13754.0 30056.0
Andhra_P 7830.0 931.0 7452.4 NaN
Kerala 113.1 1.7 2604.8 NaN

Total Production for each state


Total production for each item type
How many states produce Wheat?
Print details of the state with maximum Rice
production
Use the libraries as required
18. Given a DataFrame mks2 storing marks of 10
students in a class in five subjects as shown
below:
1 2 3 4 5 6 7 8 9
10
Acct 99 94 81 70 88 90 41 61 42 68
Eco 94 94 72 67 82 81 36 54 42
67
Eng 95 89 71 69 82 79 51 60 45
66
IP 94 87 79 65 89 81 42 63 43
64
Math 97 100 65 69 86 84 40 55 40
60
Write a program to measure the subject wise
performance of the students, so that the
teacher gets to know the following details (for
each subject)
25 percentile students scored below?
50 percentile students scored below?
75 percentile students scored below?
Also separately list the performance for the
subject ‘IP’
19. Given the school result data, analyse the
performance of the students on different
parameters, e.g subject wise or class wise.
20. For the Data frames created above, analyze and
plot appropriate charts with title and legend.
21. Write a program in Python Pandas to
create the following DataFrame batsman
from a Dictionary: B_NO Name Score1
Score2 1 Sunil Pillai 90 80 2 Gaurav
Sharma 65 45 3 Piyush Goel 70 90 4
Kartik Thakur 80 76 Perform the
following operations on the DataFrame :
1)Add both the scores of a batsman and
assign to column “Total” 2)Display the
highest score in both Score1 and Score2 of
the DataFrame
22. Generally ten different prices of a stock are
stored. However, for ABC Co only 5 prices are
available for a dat:[74.25, 76.06, 69.5, 72.55,
81.5] Write a program to create a bar chart
with the given prices:
• The graph should be plotted between the
limits -2 to 10 on x-axis
• There should be tick for every potted
point
23. Three days prices are available in three lists as
shown below:
Day1=[74.25, 76.06, 69.5, 72.55]
Day2=[56.03, 68.71,62.89, 56.42]
Day3=[59.3, 72.07, 77.65, 66.46]
Write a program to create filled lineplot from
this data with their unique labels.

ACKNOWLEDGEMENT
Primarily I would thank Principal mam for providing us a
state of the art Computer Lab where I have complete most
of my practical programs of this practical file with
success. Then I would like to thank my
“INFORMATICS PRACTICES” teacher Mr.
SWAPAN KAPURIA, whose valuable guidance has been
the ones that helped me to complete this practical file and
make it full proof success. His suggestion and his
instructions has served as the major contributor towards
the completion of the practical file.
Then I would like to thank my parents and friends who
have helped me with their valuable suggestions and
guidance has been helpful in various phases of the
completion of the practical file.
Last but not the least I would like to thank my classmates
who have helped me a lot.
CERTIFICATE
This is to certify that _Harsh Rautella_ of class XII_G
bearning roll no___________ for the session 2023-24
has successfully completed his/her
“INFORMATICS PRACTICES” practical file. He has
taken proper care and utmost sincerity in completion of
his practical file. All the works related to the practical file
was done by the candidate.

I certify that this practical is upto my expectation and as


per the guidance issued by the CBSE.

Mr. SWAPAN KAPURIA


(PGT. Comp. Sc.)

PROGRAM 1: Create a pandas series from a dictionary of


values. Display 3 top rows using head ()
import pandas as pd

data={1:"Harsh",2:"Adityansh",3:"Garv",4:"Harshit",5:"Tanya",6:"Malik"}
s=pd.Series(data)
print(s)
print(s.head(3))

OUTPUT:

PROGRAM 2 : Create a pandas Series from and array of values.


Display 3 rows from bottom using tail()
import pandas as pd
import numpy as np
data=np.array[1,2,3,4,5,6])
s=pd.Series(data)
print(s)
print(s.tail(3))

OUTPUT:
PROGRAM 3: Create a series and show different types of selection
like

• retrieve 1st 3 rows


• import pandas as pd
• import numpy as np
• s=pd.Series(np.NaN,index=[49,48,47,46,45,1,2,3,4,5])
• print(s)
• print(s.iloc[:3])
OUTPUT :

ii. Slice upto and including a particular lable


import pandas as pd
s=pd.Series(5,index=[49,48,47,46,45,1,2,3,4,5])
print(s.loc[:3])

OUTPUT :
Program 4: Draw the following bar graph representing the number of
students in each class.
import matplotlib.pyplot as plt
Classes = ['VII','VIII','IX','X']
Students = [40,45,35,44]
plt.bar("classes","students")
plt.show()
PROGRAM 5 : Create a series having values 3,4,1,10,9,8,7. Arrange the data
in the series in Ascending order and also in Descending order
import pandas as pd
s=pd.Series([3,4,1,10,9,8,7])
print(s.sort_values(ascending=False))
print(s.sort_values(ascending=True))

OUTPUT :

PROGRAM 6 : Create a Series using a ndarray of values and show mean,


median, maximum value, minimum value, mode

import pandas as pd
data=([10,9,8,7,2,2,5,7,3,10,1,7])
s=pd.Series(data)
print(s.mean())
print(s.median())
print(s.max())
print(s.min())
print(s.mode())
OUTPUT :

PROGRAM: 7 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

import pandas as pd
dic={‘itemcat’:[‘car’,’AC’,’aircoller’,’washing machine’],’itemname’:
[‘ford’,’hitachi’,’symphony’,’LG’],’expenditure’:[7000000,50000,12000,14000]}
quartsales=pd.DataFrame(dic)
print(quartsales)
qs=quartsales.groupby(‘itemcat’)
print(‘result after filtering DataFrame’)
print(qs[‘itemcat’,’expenditure’].sum())

OUTPUT:

PROGRAM :8 Create a data frame for examination result and


display row labels, column labels data types of each column and the
dimensions

import pandas as pd
dic={"Class":
["I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII"],"Pass
Percentage":[100,100,100,100,100,100,100,100,100,98.6,100,99]}
result=pd.DataFrame(dic)
print(result)
print(result.dtypes)
print("shape of the dataframe is : ", result.shape)

Output:

PROGRAM: 9 Filter out rows based on different criteria such as


duplicate rows
import pandas as pd
dic={"name":
["Harsh","Dev","chanchal","Harsh","Dev","Pranav","lucky"],"MarksinIP":
[85,45,92,85,45,96,84]}
Marks=pd.DataFrame(dic)
#find duplicate rows
duplicaterow=Marks[Marks.duplicated(keep=False)]
print(duplicaterow)
OUTPUT:

PROGRAM: 10 Find the sum of each column, or find the column


with the lowest mean.
import pandas as pd
profit={"TCS":{"qtr1":2500,"qtr2":2000,"qtr3":3000,"qtr4":2000},"WIPRO":
{"qtr1":2800,"qtr2":2400,"qtr3":3600,"qtr4":2400},"L&T":
{"qtr1":2100,"qtr2":5700,"qtr3":35000,"qtr4":2100}}
df=pd.DataFrame(profit)
print(df)
print()
print("column wise sum in DataFrame is :::")
print(df.sum(axis=0))
#print mean value of each column
print()
print("column wise mean value are:::::::")
print(df.mean(axis=0))
#return column with minimum mean value
print()
print("column with minimum mean value is:::::::::::")
df.mean(axis=0).idxmin()

OUTPUT:

PROGRAM: 11 Do the following :

1.locate the 3 largest values in a dataframe`

import pandas as pd
dic={"name":
["Harsh","Lakshay","Vanshika","shourya","Lakshay","Mann","ashiya"],"marksinIP":
[85,45,92,85,98,96,84]}
marks=pd.DataFrame(dic)
#find 3 largest value for marksinIP column
print(marks.nlargest(3,["marksinIP"]))

OUTPUT:

2. subtract the mean of a row from each element of the row in a dataframe.

import pandas as pd
profit={"TCS":{"qtr1":2500,"qtr2":2000,"qtr3":3000,"qtr4":2000},"WIPRO":
{"qtr1":2800,"qtr2":2400,"qtr3":3600,"qtr4":2400},"L&T":
{"qtr1":2100,"qtr2":5700,"qtr3":35000,"qtr4":2100}}
df=pd.DataFrame(profit)
print(df)
print()
print("mean of each row is :::::")
print(df.mean(axis=1))
print()
print("dataframe after subtracting mean value of each row from each element of
that row is :::::::")
print(df.sub(df.mean(axis=1),axis=0))

OUTPUT:
3.replace all negative values in a dataframe with a 0.

import pandas as pd
dic={"data1":[-5,-2,5,8,9,-6],"data2":[2,4,10,15,-5,-8]}
df=pd.DataFrame(dic)
print(df)
print()
print("dataframe after replacing negative values with 0:::")
df[df<0]=0
print(df)

OUTPUT:
4. replace all missing values in a dataframe with a 999

import pandas as pd
import numpy as np
empdata={"empid":[101,102,103,104,105,106],"ename":
["Harsh","Adityansh",”YY",np.nan,"chanchal","reemanshi"],"doj":["12-01-
2015","15-01-2015","05-09-2015","17-02-2015",np.nan,"16-01-2015"]}
df=pd.DataFrame(empdata)
print(df)
df=df.fillna({"ename":999,"doj":999})
print()
print(df)

OUTPUT:
PROGRAM 12 : A dictionary Grade contains the following data:
Grade={‘Name’:[‘Rashmi’, ‘Harsh’, ‘Ganesh’, ‘Priya’, ‘Vivek’,
‘Anita’, ‘karthik’], ‘Grade’:[‘A1’, ‘A2’, ‘B1’, ‘A1’, ‘B2’, ‘A2’, ‘A1’]}
Write statements for the following:
a. Create dataFrame called GR.
b. Find the output of GR.iloc[0:5] and GR[0:5}
c. Add a column called percentage with following data: [92, 89,
None, 95, 68, None, 93]
d. Rearrange the columns as Name, Percentage and grade
e. Drop the column (i.e. Grade) by name
f. Delete the 3rd and 5th rows
g. What does the following will do?
i. Gr.drop(0, axis=0)
ii. Gr.drop(0, axis=”index”)
iii. Gr.drop([0, 1, 2, 3], axis=0

import pandas as pd
grade={"name":
["Rashmi","Harsh","Ganesh","Priya","Vivek","Anita","Kartik"],"grade":
["A1","A2","B1","A1","B2","A2","A1"]}
Gr=pd.DataFrame(grade)
print(Gr)
print("=======")
print(Gr.iloc[0:5])
print(Gr[0:5])
print("======")

#question c add a column percentage


Gr["percentage"]=[92,89,"none",95,68,"none",93]
print(Gr)
print("======")
#rearrange the column as name,percentage,grade
Gr=Gr[["name","percentage","grade"]]
print(Gr)
print("======")
#drop column grade by name
b=Gr.drop("grade",axis=1)
print(b)
print("======")
#delete 3rd and 5th rows
c=Gr.drop([2,4])
print
d=Gr.drop(0,axis=0)
print(d)

OUTPUT:
PROGRAM 13: Importing and exporting data between pandas and
CSV file
import pandas as pd
df=pd.read_csv(”C:\Users\hp\Desktop\file.csv”)

print(df)

OUTPUT:
import pandas as pd

surname=[{‘name’:’manvi’,’surname’:’rajput’},

{‘name’:’jatin’,’surname’:’kumar’},

{‘name’:’ayush’,’surname’:’rollyan’},

{‘name’:’tushar’,’surname’:’rollyan’}]

df1=pd.DataFrame(surname)

df1.to_csv(r”C:\Users\hp\Desktop\file1.csv”)

PROGRAM 14 : Implement Describe method on a dataframe display its


output

import pandas as pd
numeric_dataset=pd.Series([1,2,3,4,5,6,7,8,9])
print(numeric_dataset.describe())
char_dataset=pd.Series(["a","b","c","d"])
print(char_dataset.describe())
OUTPUT:

PROGRAM 15: Write a program to iterate over a dataframe


containing names and marks, which then calculates grades as
per marks and adds them to the grade column.
Marks Grade
Marks>=90 A+
Marks 70-90 A
Marks 60-69 B
Marks 50-59 C
Marks 40-49 D
Marks <40 F
import pandas as pd
import numpy as np
names=pd.Series(['Dev','Aklavya','Ayush','Tushar'])
marks=pd.Series([91.0,56.0,91.0,67.0])
stud={'Name':names,'Marks':marks}
dfl=pd.DataFrame(stud,columns=['Name','Marks'])
dfl['grade']=np.NaN
print("initial values in DataFrame")
print(dfl)
for(col,colSeries) in dfl.iteritems:
length=len(colSeries)
if col=='Marks':
lstmrks=[]
for row in range (length):
mrks=colSeries[row]
if mrks>=90:
lstmrks.append('A+')
elif mrks>=70:
lstmrks.append('A')
elif mrks>=60:
lstmrks.append('B')
elif mrks>=50:
lstmrks.append('c')
elif mrks>=40:
lstmrks.append('D')
else:
lstmrks.append('F')
df1['grade']=lstmrks
print("\n DataFrame after calculating grades")
print(df1)

PROGRAM 16

I.
import pandas as pd
data={'Name':['Rabia','Evan', 'Jia', 'Lalit', 'jaspreet
', 'Suji'],'Sex':['F','M', 'F', 'M', 'M', 'F'], 'Age':
[30,27,32,40,28,32], 'Projects':[13,17,16,20,21,14], 'B
udget':[48,13,32,21,17,10]}
df=pd.DataFrame(data)
print(df)
OUTPUT:

II.
#print the details of the youngest employee in the datafr
ame
print('The youngest employee details')
print(df[df['Age']==df['Age'].min()])
OUTPUT:

III.
print('Maximum no. of projects=')
print(df[df['Projects']==df['Projects'].max()])
OUTPUT:

IV.
print('Average budget allotted:', df['Budget'].mean())
OUTPUT:

Program-17:
import pandas as pd
Tripura=[44.1, 23.2, 814.6, .5]
Gujrat=[11950, 818, 1930.0, 2737.0]
Punjab=[7152.0, 33.0, 11586.2, 16440.5]
Uttar_P=[140169.2, 2184.4, 13754.0, 30056.0]
Andhra_P=[7830.0, 931, 7452.4]
Kerala=[113.1, 1.7,2604.8]
data=[Tripura, Gujrat, Punjab, Uttar_P, Andhra_P, Kerala]
df=pd.DataFrame(data, index=['Tripura','Gujrat','Punjab',
'Uttar_P','Andhra_P', 'Kerala'],columns=['Fruits', 'Pulse
s', 'Rice', 'Wheat'])
print(df)

OUTPUT:

I.
#Total production for each state
print("\nTotal production for each state is")
print(df.sum(axis=1))

OUTPUT:

II.
#Total Production for each item type
print('\nTotal production for each item type\n')
print(df.sum())
OUTPUT:
III.
#how many states produce wheat?
print('\nNo. of states producing wheat\
n',df['Wheat'].count())
OUTPUT:

IV.
#print details of the state with maximum Rice production
print("\n State with maximum rice production:")
print(df[df['Rice']==df['Rice'].max()])

OUTPUT:

PROGRAM 18: Given a Data Frame mks2 storing marks of 10 students in a class in five
subject as shown below:
1 2 3 4 5 6 7 8 9 10
Acct 99 94 81 70 88 90 41 61 42 68
Eco 94 94 72 67 82 81 36 54 42 67
Eng 95 89 71 69 82 79 51 60 45 66
IP 94 87 79 65 89 81 42 63 43 64
Math 97 100 65 69 86 84 40 55 40 60
Write a program to measure the subject wise performance of the students, so that the
teacher gets to know the following details (for each subject)
25 percentile students scored below?
50 percentile students scored below?
75 percentile students scored below?

Also separately list the performance for the subject ‘IP’

import pandas as pd

#given mks2 created or loaded

mks2={1:{'acct':99,'eco':94,'eng':95,'ip':94,'math':97},2:
{'acct':94,'eco':94,'eng':89,'ip':87,'math':100},3:
{'acct':81,'eco':72,'eng':71,'ip':79,'math':65},4:
{'acct':70,'eco':67,'eng':69,'ip':65,'math':69},5:
{'acct':88,'eco':82,'eng':82,'ip':89,'math':86},6:
{'acct':90,'eco':81,'eng':79,'ip':81,'math':84},7:
{'acct':41,'eco':36,'eng':51,'ip':42,'math':40},8:
{'acct':61,'eco':54,'eng':60,'ip':63,'math':55},9:
{'acct':42,'eco':42,'eng':45,'ip':43,'math':40},10:
{'acct':68,'eco':67,'eng':66,'ip':64,'math':60}}

mks2=pd.DataFrame(mks2)

print("performance of student, subject wise")

print(mks2.quantile([0.25,0.5,0.75,1.0],axis=1))

OUTPUT:
PROGRAM 19: Given the school result data, analyse the
performance of the students on different parameters, e.g subject
wise or class wise.
import matplotlib.pyplot as plt

subject=[‘accountany’,’business studies’,’economics’,’informatics
practice’,’english’]

percentage=[85,78,65,100,95]

plt.bar(subject,percentage,align=’center’,color=’green’)

plt.xlabel(‘SUBLECTS NAME’)

plt.ylabel(‘PASS PERCENTAGE’)

plt.title(‘bar graph for result analysis’)

plt.show()

OUTPUT:
PROGRAM 20: For the Data frames created above, analyze and
plot appropriate charts with title and legend.
import matplotlib.pyplot as plt

import numpy as np

s=[‘1st’,’2nd’,’3rd’]

per_sc=[95,89,77]

per_com=[90,93,75]

per_hum=[97,92,77]

x=np.arange(len(s))

plt.bar(x,per_sc,label=’science’,width=0.25,color=’green’)

plt.bar(x+.25,per_com,label=’commerce’,width=0.25,color=’red’)

plt.bar(x+.50,per_hum,label=’humanities’,width=0.25,color=’gold’)

plt.xticks(x,s)
plt.xlabel(‘position’)

plt.ylable(‘percentage’)

plt.title(‘bar graph for result analysis’)

plt.legend()

plt.show()

OUTPUT:

PROGRAM 21:
import pandas as pd

d1={'B_NO':[1,2,3,4], 'Name':["Sunil Pillai","Gaurav Sharma","Piyush


Goel","Kartik Thakur"],'Score1':[90,65,70,80], 'Score2':[80,45,95,76] }

df=pd.DataFrame(d1)

print(df)

df['Total'] = df['Score1']+ df['Score2']

PROGRAM 22 : Generally ten different prices of a stock are stored.


However, for ABC Co only 5 prices are available for a dat:[74.25,
76.06, 69.5, 72.55, 81.5] Write a program to create a bar chart with
the given prices:
• The graph should be plotted between the limits -2 to 10 on x-
axis
There should be tick for every potted point

import matplotlib.pyplot as plt

pr=[74.25,76.06,69.5,72.55,81.5]

plt.bar(range(len(pr)),pr,width=0.4,color='m')

plt.xlim(-2,10)

plt.title("price of abc co.")

plt.xticks(range(-2,10))

plt.ylabel("price")

plt.show()

OUTPUT:
PROGRAM 23: Three days prices are available in three lists as shown below:
Day1=[74.25, 76.06, 69.5, 72.55]
Day2=[56.03, 68.71,62.89, 56.42]
Day3=[59.3, 72.07, 77.65, 66.46]

Write a program to create filled line plot from this data with their unique labels .

import matplotlib.pyplot as plt

import numpy as np

day1=[74.25,76.06,69.5,72.55]

day2=[56.03,68.71,62.89,56.42]

day3=[59.3,72.07,77.65,66.46]
finlist=[day1,day2,day3]

X = np.arange(4)

fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.bar(X + 0.00, finlist[0], color = 'b', width = 0.25)

ax.bar(X + 0.25, finlist[1], color = 'g', width = 0.25)

ax.bar(X + 0.50, finlist[2], color = 'r', width = 0.25)

plt.title("Prices Available")

plt.xlabel("Days")

plt.ylabel("Prices")

OUTPUT:
SQL(Structured Query Language)

1. Create a database say school in mysql.

mysql> create database school;

2.How to go to particular database say school?

mysql> use school;

3.Create a table dept having fields deptno as int type, dname as varchar type
and loc varchar type. Consider deptno as primary key.

mysql> create table dept( deptno int primary key, dname varchar(20), loc
varchar(20));

4.Insert record in Dept table

Deptno DnameLoc

10 Sales Delhi

20 HR Pune

30 Purchase Agra

mysql> insert into dept values(10, 'Sales', 'Delhi');

mysql> insert into dept values(20, 'HR', 'Pune');

mysql> insert into dept values(30, 'Purchase', 'Agra');


5.Create a table Employee having following details:

Table Name: Employee

Field Name Data Type Length Constraint

Eno Integer Primary Key

Ename Varchar 15 Not Null

Gender Char 1

Doj Date

Salary Decimal 10,2

Deptno Integer Foreign Key

mysql> create table employee( Eno int primary key, Ename varchar(15) not null,
Gender char(1), Doj date, Salary decimal(10,2), Deptno int, foreign key(deptno)
references dept(deptno) );

6. Display structure of the table Employee.

mysql> describe employee;

+--------+---------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+--------+---------------+------+-----+---------+-------+

| Eno | int | NO | PRI | NULL | |

| Ename | varchar(15) | NO | | NULL | |

| Gender | char(1) | YES | | NULL | |

| Doj | date | YES | | NULL | |

| Salary | decimal(10,2) | YES | | NULL | |


| Deptno | int | YES | MUL | NULL | |

+--------+---------------+------+-----+---------+-------+

7. Insert 3 records in Employee table

Eno Ename Gender Doj Salary Dept(Foreign Key)

1 Anuj M ‘2001-01- 01’ 5000010

2 Devansh M 55000 20

3 Mansi F 60000 50

mysql> insert into employee values(1, 'Anuj', 'M', '2001-01-01', 50000, 10);

mysql> insert into employee values(2, ‘Devansh', 'M',null, 55000, 20);

mysql> insert into employee values(3, 'Mansi', 'F',null, 60000, 50);

8.Display all the records in Employee table.

mysql> select * from Employee;

+-----+---------+--------+------------+----------+--------+

| Eno | Ename | Gender | Doj | Salary | Deptno |

+-----+---------+--------+------------+----------+--------+

| 1 | Anuj |M | 2001-01-01 | 50000.00 | 10 |

| 2 | Devansh | M | NULL | 55000.00 | 20 |

| 3 | Mansi | F | NULL | 60000.00 | 50 |

+-----+---------+--------+------------+----------+--------+
9. Display Eno, Ename,from Employee only for gents employee.

mysql> select Eno , Ename from Employee where Gender='M';

+-----+---------+

| Eno | Ename |

+-----+---------+

| 1 | Anuj |

| 2 | Devansh |

+-----+---------+

10. Display those names whose salary is between 40000 to 60000.

mysql> select Ename from Employee where salary between 40000 and 60000;

+---------+

| Ename |

+---------+

| Anuj |

| Devansh |

| Mansi |

+---------+

11.Display those records whose name starts with a.

mysql> select Ename from Employee where Ename like 'a%';

+-------+

| Ename |
+-------+

| Anuj |

+-------+

12. Display those Ename whose name 3rd letter is r.

mysql> select Ename from Employee where Ename like'__r%;

13. Display all records in ascending order of Ename.

mysql> select * from Employee order by Ename;

+-----+---------+--------+------------+----------+--------+

| Eno | Ename | Gender | Doj | Salary | Deptno |

+-----+---------+--------+------------+----------+--------+

| 1 | Anuj |M | 2001-01-01 | 50000.00 | 10 |

| 2 | Devansh | M | NULL | 55000.00 | 20 |

| 3 | Mansi | F | NULL | 60000.00 | 50 |

+-----+---------+--------+------------+----------+--------+

14. Display records in descending order of salary.

mysql> select * from Employee order by salary desc;

+-----+---------+--------+------------+----------+--------+

| Eno | Ename | Gender | Doj | Salary | Deptno |

+-----+---------+--------+------------+----------+--------+

| 3 | Mansi | F | NULL | 60000.00 | 50 |


| 2 | Devansh | M | NULL | 55000.00 | 20 |

| 1 | Anuj |M | 2001-01-01 | 50000.00 | 10 |

+-----+---------+--------+------------+----------+--------+

15. Add a column city in Employee.

mysql> alter table Employee add city varchar(10);

16. Delete column city.

mysql> alter table Employee drop column city;

17. Display gender wise number of employees.

mysql> select Gender, Ename from Employee;

+--------+---------+

| Gender | Ename |

+--------+---------+

|M | Anuj |

|M | Devansh |

|F | Mansi |

+--------+---------+

18. Display all the records whose salary is null.

mysql> select * from employee where salary IS NULL;

19. Make Deptno as Foreign key.

mysql> alter table employee add foreign key(deptno) references dept(deptno);

20. Display all the records.

mysql> select * from employee;


+-----+---------+--------+------------+----------+--------+

| Eno | Ename | Gender | Doj | Salary | Deptno |

+-----+---------+--------+------------+----------+--------+

| 1 | Anuj |M | 2001-01-01 | 50000.00 | 10 |

| 2 | Devansh | M | NULL | 55000.00 | 20 |

| 3 | Mansi | F | NULL | 60000.00 | 50 |

+-----+---------+--------+------------+----------+--------+

21. Display eno,ename,salary,deptno.

mysql> select eno,ename,salary,deptno from employee;

+-----+---------+----------+--------+

| eno | ename | salary | deptno |

+-----+---------+----------+--------+

| 1 | Anuj | 50000.00 | 10 |

| 2 | Devansh | 55000.00 | 20 |

| 3 | Mansi | 60000.00 | 50 |

+-----+---------+----------+--------+

22. Display eno,ename,salary,deptno for those employ who get salary more
than 50000.

mysql> select eno,ename,salary,deptno from employee where salary>50000;

+-----+---------+----------+--------+

| eno | ename | salary | deptno |

+-----+---------+----------+--------+

| 2 | Devansh | 55000.00 | 20 |
| 3 | Mansi | 60000.00 | 50 |

+-----+---------+----------+--------+

23. Display those employees who joined after 01.01.2011.

mysql> select * from employee where doj > '2011-01-01';

24. Delete those rows who earn zero.

mysql> delete from employee where salary is null;

25. Increase salary of employees by 30%.

mysql> update employee set salary=salary+(salary*30.0/100.0);

26. Write a query to calculate 2 raise to the power 3

Ans:

27. Write a query to display various forms of Round function

Ans:
28. Write a query to calculate 50 mod 3

Ans:
29. Write the output of the following:

a. Select ucase(Ename) from employee;

Ans:

b. Select Lcase(Ename) from employee;

Ans:

c. Select Substr(Ename, 2,4) from employee;

Ans:
d. Select length(Ename) from employee;

Ans:

30. Write the output of the following:

a. Select Left(‘Kamal Model School’, 5);

Ans:

b. Select Right(‘Kamal Model School’,6);

Ans:
c. Select Instr(‘Kamal Model School’, ‘School’);

Ans:

d. Select Ltrim(‘ Kamal’);

Ans:

e. Select Rtrim(‘Kamal ‘);

Ans:
31. Write the output of the following:

a. Select Month(‘2022-02-16’);

Ans:

b. Select year(‘2022-02-16’);

Ans:

c. Select Day(‘2022-02-16’);

Ans:
d. Select Dayname(‘2022-02-16’);

Ans:

e. Select Monthname(‘2022-02-16’);

Ans:

32. Consider Employee table and Write the output of the following:

a. Select Max(Salary) from employee;

Ans:

b. Select Min(Salary) from employee;

Ans:
c. Select Avg(Salary) from employee;

Ans:

d. Select Sum(Salary) from employee;

Ans:

e. Select Count(*) from employee;

Ans:

You might also like