0% found this document useful (0 votes)
8 views47 pages

PDF&Rendition 1

Uploaded by

piyusharts05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views47 pages

PDF&Rendition 1

Uploaded by

piyusharts05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Practical Class - XII

Data Handling
1. Create a panda’s series from a dictionary of values and a ndarray.
( i ). Creating series using a dictionary:
import pandas as pd
dict = { 'January': 31, 'February': 28, 'March': 31, 'April' : 30 }
sr1 = pd.Series(dict)
print(sr1)
Output-
January 31
February 28
March 31
April 30
dtype: int64

( ii ) Creating a series using ndarray:


import pandas as pd
import numpy as np
ar1 = np.arange(1, 15, 2)
sr2 = pd.Series( ar1, index = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] )
print( sr2 )
Output-
a 1
b 3
c 5
d 7
e 9
f 11
g 13
dtype: int32
2. Given a Series, print all the elements that are above the 75th percentile.
The percentile rank of a score is the percentage of scores in its frequency distribution that are equal
to or lower than it. For example, a test score that is greater than 75% of the scores of people taking
the test is said to be at the 75th percentile, where 75 is the percentile rank.

# computing 75th percentile of a series.


import pandas as pd
import numpy as np
ar2 = np.random.randint( 1, 100, 15)
sr3 = pd.Series( ar2 )
print( sr3 )
quant = sr3.quantile( 0.75 ) # or quant = np.percentile( sr3, q = 75)
print( 'The 75th percentile of Series is:', quant )
Output-
0 94
1 69
2 14
3 40
4 70
5 84
6 27
7 82
8 63
9 8
10 86
11 75
12 32
13 58
14 70
dtype: int32
The 75th percentile of Series is: 78.5
3. Create a panda’s dataframe from a list, list of lists, series, dictionary of values
and a csv file.

# Creating dataframe using a list:

import pandas as pd
lst1 = [1, 2, 3, 4, 5]
df = pd.DataFrame( lst1 )
print( df )
Output-
0
0 1
1 2
2 3
3 4
4 5

# Creating dataframe using a list of lists:


import pandas as pd
lst2 = [ ['Rohit',10], ['Mohit',12], ['Sohit',13] ]
df1= pd.DataFrame( lst2 , columns = ['Name' , 'Age’ ] )
print( df1)

Output-
Name Age
0 Rohit 10
1 Mohit 12
2 Sohit 13
# Creating dataframe using series:
import pandas as pd
stu_roll = pd.Series( {'Khushi': 101, 'Anjali': 105, 'Annu' : 104, 'Kalpana' : 109, 'Gulab' : 110} )
stu_Marks = pd.Series( {'Khushi': 89, 'Anjali': 86, 'Annu' : 92, 'Kalpana' : 93, 'Gulab' : 82} )
dict = {'Roll No' : stu_roll , 'Marks' : stu_Marks }
stu_df = pd.DataFrame(dict)
print( stu_df )
Output-
Roll No Marks
Khushi 101 89
Anjali 105 86
Annu 104 92
Kalpana 109 93
Gulab 110 82

# Creating dataframe using a dictionary:


import pandas as pd
# Dictionary containing applicants data
dict = { 'Name' : ['Vijay', 'Prince', 'Gaurav', 'Anil’], 'Age' : [17, 16, 13, 14],
'Address' : ['Delhi', 'Noida', 'Ghaziabad', 'Gurugram’],
'Qualification' : ['M Com', 'B Sc', 'BCA', 'BBA'] }
df = pd.DataFrame( dict )
print( df )
Output:
Name Age Address Qualification
0 Vijai 17 Delhi M Com
1 Prince 16 Noida B Sc
2 Gaurav 13 Ghaziabad BCA
3 Anil 14 Gurugram BBA
# Creating dataframe using a csv ( Comma Separated Value ) file:

import pandas as pd
data = pd.read_csv( 'C:\\Users\\ Desktop\\Python\\StudentsDetails.csv’ )
dt = data.head()
print( dt )
# \U in "C:\Users... starts an eight-character Unicode escape, which shows
error, You either need to duplicate all backslashes.
Output-
Sr. No name board class section city
0 52 NISHANT CBSE XII A NEW DELHI
1 53 ARYA KUMAR CBSE XII A NEW DELHI
2 54 SHASHWAT CBSE XII A NEW DELHI
3 55 RANJEET YADAV CBSE XII A NEW DELHI
4 56 YASHARTH CHAUHAN CBSE XII A NEW DELHI
4. (i). Create a Data Frame using a dictionary of students name and marks of
subjects- English, IP, Accounts, Economics. Set its index as Name column. Add a
new column ‘B St’ and then ‘Total’ as sum of marks of all subjects.
import pandas as pd
# Dictionary containing students data
data = {'Name':['Ajay', 'Vijay', 'Jay', 'Sanjay', 'Pranay' ], 'Eng':[65,70, 55, 83, 90],’IP':[ 82, 94,
90, 76, 87], 'Acc':[78, 67, 82, 56,69], 'Eco':[85, 90,64, 71, 79]}
df = pd.DataFrame(data )
# To set the Name column as index:
df.set_index( 'Name', inplace = True )
print( df )
# To add a new column 'B St' to an already existing dataframe df:
df['B St'] = [65, 79, 83, 62, 69]
print(df)
# Adding column 'Total' to a dataframe:
df['Total'] = df['Eng']+ df['IP'] + df['Acc'] + df['Eco']+ df['B St']
print( df )
Output-
Eng IP Acc Eco
Name
Ajay 65 82 78 85
Vijay 70 94 67 90
Jay 55 90 82 64
Sanjay 83 76 56 71
Pranay 90 87 69 79
Eng IP Acc Eco B St
Name
Ajay 65 82 78 85 65
Vijay 70 94 67 90 79
Jay 55 90 82 64 83
Sanjay 83 76 56 71 62
Pranay 90 87 69 79 69
Eng IP Acc Eco B St Total
Name
Ajay 65 82 78 85 65 375
Vijay 70 94 67 90 79 400
Jay 55 90 82 64 83 374
Sanjay 83 76 56 71 62 348
Pranay 90 87 69 79 69 394
4 (ii). Using the dataframe created in 4(i), write code to add a new row as-
[‘Dhananjay’,87,59,73,70,84]. Use drop() method to delete rows and columns.
Use rename method to rename row and column labels. Also write code to
access data using loc and iloc functions.
# Adding a row using loc
df.loc['Dhananjay'] = [87,59,73,70,84]
print(df)
Output-
Eng IP Acc Eco B St
Name
Ajay 65 82 78 85 65
Vijay 70 94 67 90 79
Jay 55 90 82 64 83
Sanjay 83 76 56 71 62
Pranay 90 87 69 79 69
Dhananjay 87 59 73 70 84

# Deleting rows using drop method with axis = 0


df = df.drop( 'Dhananjay', axis = 0 )
print(df)
Output-
Eng IP Acc Eco
Name
Ajay 65 82 78 85
Vijay 70 94 67 90
Jay 55 90 82 64
Sanjay 83 76 56 71
Pranay 90 87 69 79

# Use of drop() method with axis = 1


df = df.drop( 'B St' , axis = 1 )
# axis = 1 represents columns and axis = 0 represents rows, default value is zero.
print(df)
Output-
Eng IP Acc Eco
Name
Ajay 65 82 78 85
Vijay 70 94 67 90
Jay 55 90 82 64
Sanjay 83 76 56 71
Pranay 90 87 69 79
# Use of rename() method for renaming row labels
df = df.rename( {'Ajay':'Stu1', 'Vijay':'Stu2', 'Jay':'Stu3', 'Sanjay':'Stu4', 'Pranay':'Stu5',
'Dhananjay':'Stu6'}, axis = ‘index’ )
print(df)
Eng IP Acc Eco B St
Name
Stu1 65 82 78 85 65
Stu2 70 94 67 90 79
Stu3 55 90 82 64 83
Stu4 83 76 56 71 62
Stu5 90 87 69 79 69
Stu6 87 59 73 70 84

# Use of rename() method for renaming column labels


df = df.rename({'Eng':'Sub1','IP':'Sub2','Acc':'Sub3','Eco':'Sub4','B St':'Sub5'}, axis = 'columns')
>>> print(df)
Sub1 Sub2 Sub3 Sub4 Sub5
Name
Stu1 65 82 78 85 65
Stu2 70 94 67 90 79
Stu3 55 90 82 64 83
Stu4 83 76 56 71 62
Stu5 90 87 69 79 69
Stu6 87 59 73 70 84

# Use of iloc for accessing columns


df.iloc[ : , [ 0, 2] ]
Output-
Eng Eco
Name
Ajay 65 85
Vijay 70 90
Jay 55 64
Sanjay 83 71
Pranay 90 79
# Use of iloc for accessing rows
r1 = df.iloc[ [ 1, 2], : ]
print( r1 )
Output-
Eng IP Eco
Name
Vijay 70 94 90
Jay 55 90 64

# Use of loc
r2 = df.loc[ ['Jay','Sanjay']]
print( r2 )
Output-
Eng IP Eco
Name
Jay 55 90 64
Sanjay 83 76 71

# Use of loc
r3 = df.loc[ : , [ 'Eng', 'Eco' ] ]
print( r3 )
Output-
Eng Eco
Name
Ajay 65 85
Vijay 70 90
Jay 55 64
Sanjay 83 71
Pranay 90 79
5 . Create two dataframes df1 and df2. Create dataframes d3 and d4 by using
concat() function for concatenating df1 and df2 row wise and column wise
respectively.
import pandas as pd
# 1st dataframe
d1 = { 'roll_no' : [ 9, 10, 11, 12, 13, 14 ], 'name' : ['Akhil', 'Nikhil', 'Pooja','Rinki','Pinki', 'Chinki']
}
df1 = pd.DataFrame( d1, columns = [ 'roll_no', 'name' ])
print( df1 )
Output-
roll_no name
0 9 Akhil
1 10 Nikhil
2 11 Pooja
3 12 Rinki
4 13 Pinki
5 14 Chinki

# 2nd dataframe
d2 = { 'roll_no' : [ 1, 2, 3 ,4, 5, 6 ], 'name' : ['Akash', 'Prakash', 'Vikas', 'Ardas', 'Chhaya',
'Maya'] }
df2 = pd.DataFrame( d2, columns = ['roll_no', 'name'])
print( df2 )
Output-
roll_no name
0 1 Akash
1 2 Prakash
2 3 Vikas
3 4 Ardas
4 5 Chhaya
5 6 Maya
# concatenating row-wise
d3 = pd.concat( [df1, df2], axis = 0 )
print( d3 )
Output-
roll_no name
0 9 Akhil
1 10 Nikhil
2 11 Pooja
3 12 Rinki
4 13 Pinki
5 14 Chinki
0 1 Akash
1 2 Prakash
2 3 Vikas
3 4 Ardas
4 5 Chhaya
5 6 Maya

# concatenating column-wise
d4 = pd.concat( [df1, df2], axis = 1 )
print( d4 )
Output-
roll_no name roll_no name
0 9 Akhil 1 Akash
1 10 Nikhil 2 Prakash
2 11 Pooja 3 Vikas
3 12 Rinki 4 Ardas
4 13 Pinki 5 Chhaya
5 14 Chinki 6 Maya
6. Create two Data Frames df1 and df2 with given values. Use append() method
to join df1 and df2.
import pandas as pd
dFrame1 = pd.DataFrame( [ [1, 2, 3], [4, 5], [6] ], columns = ['C1', 'C2', 'C3'],
index = ['R1', 'R2', 'R3'] )

dFrame2 = pd.DataFrame( [ [10, 20], [30], [40, 50]], columns = ['C2', 'C5'],
index = ['R4', 'R2', 'R5'] )

print(dFrame1)
C1 C2 C3
R1 1 2.0 3.0
R2 4 5.0 NaN
R3 6 NaN NaN
print(dFrame2)
C2 C5
R4 10 20.0
R2 30 NaN
R5 40 50.0
# Joinig two dataframes using append() method
dFrame1 = dFrame1.append(dFrame2)
print(dFrame1)
C1 C2 C3 C5
R1 1.0 2.0 3.0 NaN
R2 4.0 5.0 NaN NaN
R3 6.0 NaN NaN NaN
R4 NaN 10.0 NaN 20.0
R2 NaN 30.0 NaN NaN
R5 NaN 40.0 NaN 50.0
7. Create a Data Frame book with columns SNo, BName, Auth, Pages, Pr. Export
the data from this dataframe to –
(i) create a new CSV file books.csv at a specified location in your computer.
(ii) append the data from dataframe book to an existing CSV file namely
BooksNBT.csv at an specified location in your computer.
# Export data to CSV –
import pandas as pd
# list of data
SNo = [ 13, 14]
BName = [ "INDIAN RAILWAYS", "INDUSTRIAL DEVELOPMENT" ]
Auth = [ "M A Rao" , "M R Kulkarni"]
Pages =[ 356, 544 ]
Pr = [ 175, 360]
# dictionary of lists
dict = {'S_No': SNo, 'Book_Name': BName, 'Author': Auth, 'No_Pages': Pages, 'Price' : Pr }
book = pd.DataFrame(dict)
(i) # saving the dataframe to a new CSV file Books.csv
df.to_csv(r"C:\Users\Admin\Desktop\Python\Books.csv", index = False)
(ii)
# saving the data to an existing file BooksNBT.csv at the end of existing data.
df.to_csv( r"C:\Users\Admin\Desktop\Python\BooksNBT.csv", mode = 'a', header = False,
index = False )
# mode = ‘a ‘means append the new data at the end of existing data.
# By default mode is ‘w’ means overwrite existing records.
#header = False means headings of columns will not be printed.
# If True headings will be printed between existing and new data.
8. 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
dictqs = { 'Item Category' : ['Grocery','Stationery','Grocery','Stationery','Fruits',
'Grocery','Fruits', 'Grocery', 'Fruits','Stationery', 'Fruits'],
'Item Name' : ['Milk', 'Pen', 'Rice', 'Notebook', 'Mangoes', 'Wheat Flour', 'Banana', 'Oil',
'Apples', 'Feviquick', 'Orange']
'Expenditure': [ 16500, 880,13600, 2700, 5600, 11200, 3800, 12800, 7400, 1240, 8300 ] }

q_sales = pd.DataFrame( dictqs )


print(q_sales)
group_sales = q_sales.groupby('Item Category')
print('------------Grocery Items--------------')
print( group_sales.get_group('Grocery') )
print('------------Stationery Items--------------')
print( group_sales.get_group('Stationery') )
print('------------Fruit Items--------------')
print( group_sales.get_group('Fruits') )
print('------------Expenditure on Grocery Items--------------')
print( group_sales.get_group('Grocery')['Expenditure'].sum() )
print('------------Expenditure on Stationery Items--------------')
print( group_sales.get_group('Stationery')['Expenditure'].sum() )
print('------------Expenditure on Fruit Items--------------')
print( group_sales.get_group('Fruits')['Expenditure'].sum() )
Output-
Item Category Item Name Expenditure
0 Grocery Milk 16500
1 Stationery Pen 880
2 Grocery Rice 13600
3 Stationery Notebook 2700
4 Fruits Mangoes 5600
5 Grocery Wheat Flour 11200
6 Fruits Banana 3800
7 Grocery Oil 12800
8 Fruits Apples 7400
9 Stationery Feviquick 1240
10 Fruits Orange 8300
------------Grocery Items--------------
Item Category Item Name Expenditure
0 Grocery Milk 16500
2 Grocery Rice 13600
5 Grocery Wheat Flour 11200
7 Grocery Oil 12800

------------Stationery Items--------------
Item Category Item Name Expenditure
1 Stationery Pen 880
3 Stationery Notebook 2700
9 Stationery Feviquick 1240

------------Fruit Items--------------
Item Category Item Name Expenditure
4 Fruits Mangoes 5600
6 Fruits Banana 3800
8 Fruits Apples 7400
10 Fruits Orange 8300

------------Expenditure on Grocery Items--------------


54100
------------Expenditure on Stationery Items--------------
4820
------------Expenditure on Fruit Items--------------
25100
Data
Visualization
Using Pyplot
(matplotlib)
9. Write a python program to create line chart for comparing two algebraic
equations y1 = 2x + 3 and y2 = 7x – 4. Take values of x using the array with
values from 1 to 10. Display the legend also.

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(1, 11)

y1 = 2 * x + 3

y2 = 7 * x - 4

plt.plot( x, y1, label = 'y = 2x + 3')

plt.plot( x, y2, label = 'y = 7x - 4' )

plt.title( " Plotting of algebric expressions " )

plt.xlabel( " x axis " )

plt.ylabel(" y axis ")

plt.legend()

plt.show()
10. Write a python program to create line chart for Sine function. The values of
x are to taken from an numpy array between -2 to 1 at an interval of 0.01.

import matplotlib.pyplot as plt

import numpy as np

xvalues = np.arange( -2, 1, 0.01 )

yvalues = np.sin( xvalues )

plt.plot( xvalues, yvalues, color = 'y’ )

plt.title( "Sine Line Chart" )

plt.xlabel( "Values" )

plt.ylabel("Sine of values")

plt.show()
11. Write a python program to create a bar chart to show comparison of
popularity of programming languages. Use the given below lists to create bars:
prog_lang = ['Python', 'Java', 'Javascript', 'C#', 'PHP', 'C/C++', 'R']

use_percent = [ 30.6, 18.5, 7.9, 7.3, 6, 5.8, 3.8 ]

import matplotlib.pyplot as plt

import numpy as np

prog_lang = ['Python', 'Java', 'Javascript', 'C#', 'PHP', 'C/C++', 'R']

x_axis = np.arange( len( prog_lang ))

use_percent = [ 30.6, 18.5, 7.9, 7.3, 6, 5.8, 3.8 ]

plt.bar( x_axis,use_percent, align ='center', color = 'g' )

plt.xticks( x_axis, prog_lang )

plt.xlabel('Use Percent')

plt.title('Programming Language Popularity as on April 2020')

plt.show()
12. Write a python program to create a bar chart showing comparison between
the sales of different car brands in December-2018 and December-2019. The
data is given below:
Brand = ['Maruti', 'Hyundai', 'Mahindra', 'Tata', 'Renault', 'Honda', 'Toyota']

Sales_Dec19 = [ 122784, 37953, 15276, 12785, 11964, 8412, 6544 ]

Sales_Dec18 = [ 119804, 42093, 14049, 14260, 7263, 13139, 11836 ]

import matplotlib.pyplot as plt

import numpy as np

Brand = ['Maruti', 'Hyundai', 'Mahindra', 'Tata', 'Renault', 'Honda', 'Toyota']

x = np.arange( len( Brand ))

width = 0.5

Sales_Dec19 = [ 122784, 37953, 15276, 12785, 11964, 8412, 6544 ]

Sales_Dec18 = [ 119804, 42093, 14049, 14260, 7263, 13139, 11836 ]

plt.bar( x - width/2, Sales_Dec18, width, label = 2018, color = 'm' )

plt.bar( x + width/2, Sales_Dec19, width, label =2019, color = 'g')

plt.xticks( x, Brand )

plt.ylabel(' Sales of car ')

plt.title('Sales of cars comparison in Dec2018 and Dec2019')

plt.legend()

plt.show()
13. Write a python program to create a histogram by generating an array of
1000 random values. Take bin value as 25. Choose Colour of histogram as
yellow and edge colour as blue.

import matplotlib.pyplot as plt

import numpy as np

y = np.random.randn( 1000 )

plt.hist( y, 25, edgecolor = 'y' )

plt.title( 'Histogram of Random set of Numbers' )

plt.ylabel("Frequencies of Randomly generated 1000 values ")

plt.xlabel('X- Axis')

plt.show()

# bin value is 25

# Edgecolour is blue
14. Write a python program to create a histogram from the given list of marks
of students. Also use savefig() method to save the image in python folder of
your computer. Take bin values with difference of 50 marks. The values are:
T_marks = [ 250, 355, 467, 167, 180, 345, 278, 478,267, 298,
345,367,387,333,324,318,435, 467,436, 456, 256, 279, 345, 381, 324,312,339,
450,470, 134, 123, 194, 199 ,245, 412]

import matplotlib.pyplot as plt

T_marks = [ 250, 355, 467, 167, 180, 345, 278, 478,267, 298,
345,367,387,333,324,318,435, 467,436, 456, 256, 279, 345, 381, 324,312,339,
450,470, 134, 123, 194, 199 ,245, 412]

bins = [ 0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500 ]

plt.hist( T_marks, bins, label ='Total marks Distribution', facecolor = 'g',


edgecolor = 'r' )

plt.title( 'Histogram of Total Marks of Students' )

plt.ylabel("Frequencies of Total Marks")

plt.xlabel('Total Marks')

plt.legend()

plt.savefig(“Totalmarks.png”)

# save figure in python folder

plt.show()
15. Write a python program to create a dataframe namely ‘df’ using the
dictionary containing roll no, marks of English and marks of IP.
dict = { 'Roll No':[ 1, 2, 3, 4, 5, 6, 7, 8 ], 'Eng':[91,67,89,56,78,84,72,63],
'IP':[95,86,72,93,69,64,82,92]}

Now Create a line chart to show the comparison of marks of English and IP using
the dataframe ‘df’.

import matplotlib.pyplot as plt

import pandas as pd

dict = { 'Roll No':[ 1, 2, 3, 4, 5, 6, 7, 8 ], 'Eng':[91,67,89,56,78,84,72,63],


'IP':[95,86,72,93,69,64,82,92]}

df =pd.DataFrame( dict )

print( df )

ax = plt.gca()

# gca() stands for get current axis. It is used to display two plots with same axis.

# Otherwise both the plots will be displayed in separate windows.

df.plot( kind ='line', x ='Roll No', y = 'Eng', ax = ax )

df.plot( kind ='line', x ='Roll No', y = 'IP', ax = ax )

plt.show()
Output-
Roll No Eng IP
0 1 91 95
1 2 67 86
2 3 89 72
3 4 56 93
4 5 78 69
5 6 84 64
6 7 72 82
7 8 63 92

( Paste printout of the graph from last page )


16. Write a python program to create a dataframe namely ‘MelaSalesdf’ from a
csv file MelaSales.csv. Now use this dataframe MelaSalesdf to create a bar chart
with column day on x-axis. The file MelaSales.csv is as under-
Day-wise sales data along with Day’s names
Week1 Week2 Week3 Day
5000 4000 4000 Monday
5900 3000 5800 Tuesday
6500 5000 3500 Wednesday
3500 5500 2500 Thursday
4000 3000 3000 Friday
5300 4300 5300 Saturday
7900 5900 6000 Sunday

import pandas as pd
import matplotlib.pyplot as plt
MelaSalesdf = pd.read_csv(r'C:\Users\Sunil Dutt\Desktop\MelaSales.csv')
print(MelaSalesdf)
# plots a bar chart with the column "Days" as x axis
MelaSalesdf.plot( kind = 'bar', x ='Day', color = ['r','y','m'], edgecolor = 'blue')
plt.title('Mela Sales Comparision')
plt.xlabel('Days')
plt.ylabel('Sales in Rs.')
plt.show()
Ques-9

Ques-10

Ques-11
Ques-12

Ques-13

Ques-14
Ques-15

Ques-16
Practical Class - XII
PART - II

1. # TO DISPLAY LIST OF EXISTING DATABASES

mysql> SHOW DATABASES;

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

| Database |

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

| information_schema |

| mysql |

| performance_schema |

| sakila |

| school |

| sys |

| world |

| xiiab |

| xiikn |

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

9 rows in set (1.88 sec)

2. # TO CREATE A NEW DATABASE

mysql> CREATE DATABASE XIIABFINAL;

Query OK, 1 row affected (1.02 sec)


3. # TO OPEN AN EXISTING DATABASE

mysql> USE XIIABFINAL

Database changed

4. # TO CREATE A NEW TABLE NAMELY 'STUDENT'

mysql> CREATE TABLE STUDENT( ADMNO INT PRIMARY KEY, SNAME


VARCHAR(20) NOT NULL, FNAME VARCHAR(20), MNAME VARCHAR(20), DOB
DATE, CLASS VARCHAR(15), ADDRESS VARCHAR(80), MOBILE BIGINT);

Query OK, 0 rows affected (2.30 sec)

5. # TO ADD A NEW RECORD TO THE TABLE STUDENT

mysql> INSERT INTO STUDENT VALUES(101, 'VISHNU', 'SATYA PAL', 'SUNITA


DEVI','2010-01-07','XII A', 'NEW DELHI', 9876543210);

Query OK, 1 row affected (0.52 sec)

mysql> INSERT INTO STUDENT VALUES(102, 'AMIT', 'SUMIT', ' NAMITA','2011-05-


07','XII B', ' DELHI', 9876543211);

Query OK, 1 row affected (0.04 sec)

mysql> INSERT INTO STUDENT(ADMNO,SNAME, CLASS) VALUES(103, 'RAMESH',


'XI A');

Query OK, 1 row affected (0.18 sec)

mysql> INSERT INTO STUDENT VALUES(104, 'AMAR', 'AMAN', 'ANITA','2009-05-


25','XI C', 'NEW DELHI', 9876543212);

Query OK, 1 row affected (0.06 sec)


6. # TO CHANGE DATA VALUES IN COLUMNS UPDATE COMMAND

mysql> UPDATE STUDENT SET FNAME = 'DINESH' WHERE ADMNO = 103;

Query OK, 1 row affected (0.08 sec)

Rows matched: 1 Changed: 1 Warnings: 0

7. # TO DISPLAY LIST OF TABLES

mysql> SHOW TABLES;

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

| Tables_in_xiiabfinal |

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

| student |

+----------------------+
1 row in set (1.84 sec)

8. # TO DISPLAY STRUCTURE OF TABLE DESC/ DESCRIBE COMMAND

mysql> DESC STUDENT;


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

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


+---------+-------------+------+-----+---------+-------+
| ADMNO | int | NO | PRI | NULL | |

| SNAME | varchar(20) | NO | | NULL | |

| FNAME | varchar(20) | YES | | NULL | |

| MNAME | varchar(20) | YES | | NULL | |

| DOB | date | YES | | NULL | |

| CLASS | varchar(15) | YES | | NULL | |

| ADDRESS | varchar(80) | YES | | NULL | |

| MOBILE | bigint | YES | | NULL | |


+---------+-------------+------+-----+---------+-------+
8 rows in set (0.92 sec)

9. # TO DISPLAY HOW THE TABLE WAS CREATED

mysql> SHOW CREATE TABLE STUDENT;

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

| Table | Create Table


|

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

| STUDENT | CREATE TABLE `student` (

`ADMNO` int NOT NULL,

`SNAME` varchar(20) NOT NULL,

`FNAME` varchar(20) DEFAULT NULL,

`MNAME` varchar(20) DEFAULT NULL,

`DOB` date DEFAULT NULL,

`CLASS` varchar(15) DEFAULT NULL,

`ADDRESS` varchar(80) DEFAULT NULL,

`MOBILE` bigint DEFAULT NULL,

PRIMARY KEY (`ADMNO`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |

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

1 row in set (0.21 sec)

10. # TO REMOVE RECORD FROM A TABLE

mysql> DELETE FROM STUDENT WHERE ADMNO = 106;

Query OK, 0 rows affected (0.31 sec)


11. # TO REMOVE ALL RECORD FROM A TABLE WITH FREE MEMORY SPACE

mysql> TRUNCATE TABLE STUDENT1;

Query OK

12. # TO DISPLAY ALL RECORDS FROM A TABLE

mysql> SELECT * FROM STUDENT;

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

| ADMNO | SNAME | FNAME | MNAME | DOB | CLASS | ADDRESS |


MOBILE |

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

| 101 | VISHNU | SATYA PAL | SUNITA DEVI | 2010-01-07 | XII A | NEW DELHI |
9876543210 |

| 102 | AMIT | SUMIT | NAMITA | 2011-05-07 | XII B | DELHI |


9876543211 |

| 103 | RAMESH | DINESH | NULL | NULL | XI A | NULL | NULL |

| 104 | AMAR | AMAN | ANITA | 2009-05-25 | XI C | NEW DELHI |


9876543212 |

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

4 rows in set (0.69 sec)

13. # TO DISPLAY SOME COLUMNS FROM A TABLE

mysql> SELECT ADMNO, SNAME, CLASS FROM STUDENT;

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

| ADMNO | SNAME | CLASS |

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

| 101 | VISHNU | XII A |

| 102 | AMIT | XII B |


| 103 | RAMESH | XI A |

| 104 | AMAR | XI C |

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

4 rows in set (0.00 sec)

14. # TO REMOVE REPEATED VALUES FROM OUTPUT

mysql> SELECT DISTINCT ADDRESS FROM STUDENT;

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

| ADDRESS |

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

| NEW DELHI |

| DELHI |

| NULL |

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

3 rows in set (0.00 sec)

15. # USE OF LIKE KEYWORD WITH '%' SYMBOL FOR PATTERN MATCH

mysql> SELECT SNAME, DOB FROM STUDENT WHERE SNAME LIKE 'A%';

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

| SNAME | DOB |

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

| AMIT | 2011-05-07 |

| AMAR | 2009-05-25 |

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

2 rows in set (0.03 sec)


mysql> SELECT SNAME, DOB FROM STUDENT WHERE DOB LIKE '%7';

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

| SNAME | DOB |

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

| VISHNU | 2010-01-07 |

| AMIT | 2011-05-07 |

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

2 rows in set (0.00 sec)

16. # USE OF LIKE KEYWORD WITH '_' SYMBOL FOR PATTERN MATCH

mysql> SELECT SNAME, CLASS FROM STUDENT WHERE SNAME LIKE '_M%';

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

| SNAME | CLASS |

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

| AMIT | XII B |

| AMAR | XI C |

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

2 rows in set (0.00 sec)

mysql> SELECT SNAME, CLASS FROM STUDENT WHERE SNAME LIKE '_ _M%';

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

| SNAME | CLASS |

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

| RAMESH | XI A |

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

1 row in set (0.00 sec)


17. # USE OF BETWEEN OPERATOR

mysql> SELECT SNAME, CLASS, DOB FROM STUDENT WHERE DOB BETWEEN
'2010-01-07' AND '2011-12-31';

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

| SNAME | CLASS | DOB |

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

| VISHNU | XII A | 2010-01-07 |

| AMIT | XII B | 2011-05-07 |

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

2 rows in set (0.02 sec)

18. # TO DISPLAY RECORD FROM LIST USE OF 'IN' OPERATOR

mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS IN ('XII A','XI C');

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

| SNAME | CLASS |

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

| VISHNU | XII A |

| AMAR | XI C |

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

2 rows in set (0.01 sec)


mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS = 'XII A' OR CLASS =
'XI C';

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

| SNAME | CLASS |

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

| VISHNU | XII A |

| AMAR | XI C |

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

2 rows in set (0.00 sec)

19. # TO EXCLUDE RECORD FROM LIST USE OF 'NOT IN' OPERATOR

mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS NOT IN ('XII A','XI
C');

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

| SNAME | CLASS |

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

| AMIT | XII B |

| RAMESH | XI A |

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

2 rows in set (0.00 sec)


20. # USE OF AND OPERATOR

mysql> SELECT SNAME, CLASS FROM STUDENT WHERE CLASS = 'XII A' AND
ADDRESS = 'NEW DELHI';

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

| SNAME | CLASS |

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

| VISHNU | XII A |

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

1 row in set (0.00 sec)

21 # TO CREATE A TABLE EMPL WITH CONSTRAINTS – PRIMARY KEY, UNIQUE,


NOT NULL, CHECK, DEFAULT

mysql> CREATE TABLE EMPL( ECODE INT PRIMARY KEY, ENAME VARCHAR(20)
NOT NULL , JOB VARCHAR(15) DEFAULT ‘MTS’ , SALARY INT(6) CHECK ( SALARY >
10000 ), DEPT VARCHAR(15), MOBILE BIGINT UNIQUE );

Query OK, 0 rows affected, 1 warning (4.15 sec)

22 # ADDING RECORD TO TABLE EMPL

mysql> INSERT INTO EMPL VALUES(1, 'SUNIL','MANAGER', 25000, 'SALES',


9812312312);

Query OK, 1 row affected (1.73 sec)

mysql> INSERT INTO EMPL VALUES(2, 'ANIL','CLERK', 15000, 'PURCHASE',


9812312333), (3, 'AMAN','ANALYST', 18000, 'PURCHASE', 9812310233);

Query OK, 2 rows affected (0.20 sec)


mysql> INSERT INTO EMPL VALUES(4, 'RAMAN','CLERK', 13000, 'SALES',
9816710233), (5, 'CHAMAN','MTS', 11000, 'SALES', 9656710233);

Query OK, 2 rows affected (0.54 sec)

23. # TO ARRANGE THE RECORD TO BE DISPLAYED IN INCREASING OR


DECREASING ORDER

mysql> SELECT ENAME, DEPT FROM EMPL ORDER BY DEPT DESC;

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

| ENAME | DEPT |

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

| SUNIL | SALES |

| RAMAN | SALES |

| CHAMAN | SALES |

| ANIL | PURCHASE |

| AMAN | PURCHASE |

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

5 rows in set (0.13 sec)

mysql> SELECT ENAME, DEPT FROM EMPL ORDER BY ENAME ASC;

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

| ENAME | DEPT |

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

| AMAN | PURCHASE |

| ANIL | PURCHASE |

| CHAMAN | SALES |

| RAMAN | SALES |

| SUNIL | SALES |

+--------+----------+
5 rows in set (0.00 sec)

24. DISPLAYING ALL RECORD FROM THE TABLE EMPL

mysql> SELECT * FROM EMPL;

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

| ECODE | ENAME | JOB | SALARY | DEPT | MOBILE |

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

| 1 | SUNIL | MANAGER | 25000 | SALES | 9812312312 |

| 2 | ANIL | CLERK | 15000 | PURCHASE | 9812312333 |

| 3 | AMAN | ANALYST | 18000 | PURCHASE | 9812310233 |

| 4 | RAMAN | CLERK | 13000 | SALES | 9816710233 |

| 5 | CHAMAN | MTS | 11000 | SALES | 9656710233 |

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

5 rows in set (0.14 sec)

25 # GROUPING RECORDS USE OF GROUP BY CLAUSE

mysql> SELECT COUNT(JOB), DEPT FROM EMPL GROUP BY DEPT;

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

| COUNT(JOB) | DEPT |

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

| 3 | SALES |

| 2 | PURCHASE |

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

2 rows in set (0.20 sec)


26 # GIVING CONDITION WITH GROUP BY USING HAVING CLAUSE

mysql> SELECT AVG(SALARY), DEPT FROM EMPL GROUP BY DEPT HAVING DEPT =
'SALES';

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

| AVG(SALARY) | DEPT |

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

| 16333.3333 | SALES |

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

1 row in set (0.13 sec)

27 # USE OF AGGREGATE/ GROUP FUNCTIONS

mysql> SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY) FROM EMPL;

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

| SUM(SALARY) | MAX(SALARY) | MIN(SALARY) |

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

| 82000 | 25000 | 11000 |

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

1 row in set (0.06 sec)


28 # USE OF SINGLE ROW FUNCTION- CONCAT()

mysql> SELECT CONCAT(ENAME, SALARY) FROM EMPL WHERE SALARY >= 12000;

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

| CONCAT(ENAME, SALARY) |

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

| SUNIL25000 |

| ANIL15000 |

| AMAN18000 |

| RAMAN13000 |

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

4 rows in set (0.06 sec)

29 # USE OF SINGLE ROW FUNCTION- SUBSTR()/ SUBSTRING()/ MID()

mysql> SELECT SUBSTR(ENAME, 1, 3), MOBILE FROM EMPL;

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

| SUBSTR(ENAME, 1, 3) | MOBILE |

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

| SUN | 9812312312 |

| ANI | 9812312333 |

| AMA | 9812310233 |

| RAM | 9816710233 |

| CHA | 9656710233 |

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

5 rows in set (0.03 sec)


30 # USE OF SINGLE ROW FUNCTION- INSTR()

mysql> SELECT INSTR(ENAME, 'AN'), ENAME FROM EMPL;

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

| INSTR(ENAME, 'AN') | ENAME |

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

| 0 | SUNIL |

| 1 | ANIL |

| 3 | AMAN |

| 4 | RAMAN |

| 5 | CHAMAN |

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

5 rows in set (0.03 sec)

31 # USE OF SINGLE ROW FUNCTION- UCASE()/UPPER()

mysql> SELECT UPPER("Informatics Pracices");

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

| UPPER("Informatics Pracices") |

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

| INFORMATICS PRACICES |

+-------------------------------+
32 # USE OF SINGLE ROW FUNCTION- LCASE() / LOWER()

mysql> SELECT LCASE("SWACHCHH BHARAT");

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

| LCASE("SWACHCHH BHARAT") |

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

| swachchh bharat |

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

33 # USE OF SINGLE ROW FUNCTION- LENGTH()

mysql> SELECT LENGTH("INDIA IS GREAT");

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

| LENGTH("INDIA IS GREAT") |

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

| 14 |

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

34 # USE OF SINGLE ROW FUNCTION- LEFT()

mysql> SELECT LEFT( "GREATEST", 3 );

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

| LEFT("GREATEST", 3) |

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

| GRE |

+---------------------+
35 # USE OF SINGLE ROW FUNCTION- RIGHT()

mysql> SELECT RIGHT("GREATEST", 4);

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

| RIGHT("GREATEST", 4) |

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

| TEST |

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

36 # USE OF SINGLE ROW FUNCTION- LTRIM()/ RTRIM()/ TRIM()

mysql> SELECT LENGTH(" DELHI "), LENGTH(LTRIM(" DELHI ")),


LENGTH(RTRIM(" DELHI ")), LENGTH(TRIM(" DELHI "));

+--------------------+----------------------------+--------------------------+-------------------------+
| LENGTH(" DELHI ") | LENGTH(LTRIM(" DELHI ")) | LENGTH(RTRIM(" DELHI ")) | LENGTH(TRIM(" DELHI ")) |

+--------------------+----------------------------+--------------------------+-------------------------+
| 9 | 7 | 7 | 5 |

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

37 # USE OF SINGLE ROW FUNCTION- POWER()/ POW()

mysql> SELECT POWER(3, 2);

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

| POWER(3, 2) |

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

| 9 |

+-------------+
38 # USE OF SINGLE ROW FUNCTION- ROUND()
mysql> SELECT ROUND(9872.38),ROUND(9872.38, 1), ROUND(9872.38, -1),ROUND(9872.38, -2);

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

| ROUND(9872.38) | ROUND(9872.38, 1) | ROUND(9872.38, -1) | ROUND(9872.38, -2) |

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

| 9872 | 9872.4 | 9870 | 9900 |

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

39 # USE OF SINGLE ROW FUNCTION- MOD()

mysql> SELECT MOD(20, 3);

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

| MOD(20, 3) |

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

| 2 |

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

40 # USE OF SINGLE ROW FUNCTION- NOW()

mysql> SELECT NOW();

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

| NOW() |

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

| 2022-11-19 21:00:04 |

+-----------------------------+
41 # USE OF SINGLE ROW FUNCTION- DATE()

mysql> SELECT DATE(NOW());

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

| DATE(NOW()) |

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

| 2022-11-19 |

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

42 # USE OF SINGLE ROW FUNCTION- MONTH()/YEAR()/DAY()/DAYNAME()


mysql> SELECT MONTH("2022-12-20"), YEAR("2022-12-20"), DAY("2022-12-20"),
DAYNAME("2022-12-20");

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

| MONTH("2022-12-20") | YEAR("2022-12-20") | DAY("2022-12-20") | DAYNAME("2022-12-20") |

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

| 12 | 2022 | 20 | Tuesday |

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

43 # ALTER COMMAND TO ADD A NEW COLUMN

mysql> ALTER TABLE EMPL ADD COLUMN ADDRESS VARCHAR(80);

Query OK, 0 rows affected (1.58 sec)

Records: 0 Duplicates: 0 Warnings: 0

44 # ALTER COMMAND TO CHANGE THE NAME OF AN EXISTING COLUMN

mysql> ALTER TABLE EMPL CHANGE ADDRESS ADDR VARCHAR(100);

Query OK, 0 rows affected (0.09 sec)

Records: 0 Duplicates: 0 Warnings: 0


45 # ALTER COMMAND TO DROP PRIMARY KEY

mysql> ALTER TABLE EMPL DROP PRIMARY KEY;

Query OK, 5 rows affected (1.80 sec)

Records: 5 Duplicates: 0 Warnings: 0

46 # ALTER COMMAND TO ADD PRIMARY KEY

mysql> ALTER TABLE EMPL ADD PRIMARY KEY(ECODE);

Query OK, 0 rows affected (0.81 sec)

Records: 0 Duplicates: 0 Warnings: 0

47 # ALTER COMMAND TO REMOVE A COLUMN

mysql> ALTER TABLE EMPL DROP COLUMN ADDR;

Query OK, 0 rows affected (1.10 sec)

Records: 0 Duplicates: 0 Warnings: 0

48 # DROP COMMAND TO REMOVE A TABLE

mysql> DROP TABLE EMPLOYEE;

Query OK

49 # DROP COMMAND TO REMOVE A DATABASE

mysql> DROP DATABASE XIIABFINAL;

Query OK

You might also like