0% found this document useful (0 votes)
75 views

Class 12 Observation - SQL-2

This document provides examples of SQL queries on sample tables and discusses aggregate functions, joins, and interfaces between Python and MySQL. It includes SQL queries to retrieve, update, delete records from tables. It discusses aggregate functions like sum, count, avg, min, max with group by clause and having clause. It also provides examples of joins between multiple tables. Finally, it discusses creating tables, altering table structure, fetching records from Python using MySQL connector.

Uploaded by

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

Class 12 Observation - SQL-2

This document provides examples of SQL queries on sample tables and discusses aggregate functions, joins, and interfaces between Python and MySQL. It includes SQL queries to retrieve, update, delete records from tables. It discusses aggregate functions like sum, count, avg, min, max with group by clause and having clause. It also provides examples of joins between multiple tables. Finally, it discusses creating tables, altering table structure, fetching records from Python using MySQL connector.

Uploaded by

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

1. Consider the following table named “GARMENT”.

1) Write command To change the colour of garment with code as 116 to “Orange”.
2) Write command to increase the price of all XL garments by 10%
3) Write command to delete the record with GCode “116”

O/P -10 lines

2. Consider the table TEACHER given below. Write commands in SQL for (1) to (3) and output for (4)

i.
To

display all information about teachers of PGT category.


ii. To list the names of female teachers of Hindi department.
iii. To list names, departments and date of hiring of all the teachers in ascending order of date of
joining
iv. SELECT DISTINCT(category) FROM teacher;

O/P -10 lines


3. Consider the table ‘PERSONS’ given below. Write commands in SQL for (i) to (iv) and write output
for (v).

(i) Display the SurNames, FirstNames and Cities of people residing in Udhamwara city.
(ii) Display the Person Ids (PID), cities and Pincodes of persons in descending order of Pincodes.
(iii) Display the First Names and cities of all the females getting Basic salaries above 40000.
(iv) Display First Names and Basic Salaries of all the persons whose firstnames starts with “G”.
(v) SELECT Surname FROM Persons Where BasicSalary>=50000;

O/P -20 lines

Consider a table Emp having following records a(Null values are excluded while (avg)aggregate
function)
EMP

CODE NAME JOB SAL CITY

E1 MOHAK HR NULL JAIPUR

E2 ANUJ HR 75000 CHENNAI

E3 VIJAY DEVELOPER NULL JAIPUR

E4 VISHAL DATA ANALYST 115000 NOIDA

E5 ANIL DATA ANALYST 125000 CHENNAI


SQL Queries :

Using Aggregate functions


mysql> Select Sum(Sal) from EMP;
mysql> Select Min(Sal) from EMP;
mysql> Select Max(Sal) from EMP;
mysql> Select Count(Sal) from EMP;
mysql> Select Avg(Sal) from EMP;
mysql> Select Count(*) from EMP;

O/P -20 lines

using sum() with GROUP BY

mysql> Select Sum(Sal) from EMP;


mysql> Select Sum(DISTINCT Sal) from EMP;
mysql> Select Sum (Sal) from EMP where City=‘Jaipur’;
mysql> Select Sum (Sal) from EMP Group By City;
mysql> Select Job, Sum(Sal) from EMP Group By Job;

O/P -20 lines

using min() with GROUP BY

mysql> Select Min(Sal) from EMP;


mysql> Select Min(Sal) from EMP Group By City;
mysql> Select Job, Min(Sal) from EMP Group By Job;

O/P -20 lines

Using MAX (<Column>)

mysql> Select Max(Sal) from EMP;


mysql> Select Max(Sal) from EMP where City=‘Jaipur’;
mysql> Select Max(Sal) from EMP Group By City;

O/P -20 lines

Using AVG (<column>)

mysql> Select AVG(Sal) from EMP;


mysql> Select AVG(Sal) from EMP Group By City;

O/P -20 lines

Using COUNT (<*|column>)

mysql> Select Count ( * ) from EMP;


mysql> Select Count(Sal) from EMP Group By City;
mysql> Select Count(*), Sum(Sal) from EMP Group By Job;
O/P -20 lines

Aggregate Functions & Conditions


HAVING <condition> clause - to apply a condition on a group

mysql> Select Job,Sum(sal) from EMP Group By Job HAVING Sum(sal)>=8000;

mysql> Select Job, Sum(sal) from EMP Group By Job HAVING Avg(sal)>=7000;

mysql> Select Job, Sum(sal) from EMP Group By Job HAVING Count(*)>=5;

mysql> Select Job, Min(sal),Max(sal), Avg(sal) from EMP Group By Job HAVING Sum(sal)>=8000;

mysql> Select Job, Sum(sal) from EMP Where City=‘Jaipur’

o/p – 20 lines

Ordering Query Result – ORDER BY Clause


mysql> SELECT * FROM EMP ORDER BY City;

mysql> SELECT * FROM Student EMP ORDER BY City DESC;

mysql> SELECT Name, Fname, City FROM Student Where Name LIKE ‘R%’ ORDER BY Class;

o/p – 20 lines

SQL - JOINS

1.. Consider the tables HANDSETS and CUSTOMER given below:

With reference to these tables, Write commands in SQL for (i) and (ii) and output for (iii) below:
(i) Display the CustNo, CustAddress and corresponding SetName for each customer.
(ii) Display the Customer Details for each customer who uses a Nokia handset.
(iii) select SetNo, SetName from Handsets, customer where SetNo = SetCode and CustAddress =
'Delhi';

O/P – 10 lines
2. Consider the tables DOCTORS and PATIENTS given below:
W1th reference to these tables, wnte commands m SQL for (1) and (II) and output for (iii) below:
(i)

Display the PatNo, PatName and corresponding DocName for each patient
(ii) Display the list of all patients whoseOPD_Days are MWF.
(iii) select OPD_Days, Count(*) from Doctors, Patients where Patients.Department =
Doctors.Department Group by OPD_Days;

O/P – 10 lines

3. Consider the tables ‘Flights’ & ‘Fares’ given below:

With reference to these tables, write commands in SQL for (i) and (ii) and output for (iii) below:
i. To display flight number, source, airlines of those flights where fare is less than Rs. 10000.
ii. To count total no of Indian Airlines flights starting from various cities.
iii. SELECT FLIGHTS.FNO, NO_OF_FL, AIRLINES FROM FLIGHTS,FARES WHERE FLIGHTS.FNO =
FARES.FNO AND
SOURCE=’DELHI’;

O/P – 10 lines

SQL - INTERFACE

1. To create table

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root" ,database="school")
mycursor=mydb.cursor()
mycursor.execute("create table student(rollno int(3) primary key,name varchar(20),age int(2))")

2. To change table structure


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root" ,database="school")
mycursor=mydb.cursor()
mycursor.execute("alter table student add (marks int(3))")
mycursor.execute("desc student")
for x in mycursor:
print(x)

3. To search records of a table at run time


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root" ,database="school")
mycursor=mydb.cursor()
nm=input("enter name")
mycursor.execute("select * from student where name='"+nm+"'")
for x in mycursor:
print (x)

4. To fetch all records of a table


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root" ,database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for x in myrecords:
print (x)

5. To fetch one record of a table at run time


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root" ,database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
row=mycursor.fetchone()
while row is not None:
print(row)
row = mycursor.fetchone()

6. consider the following table ITEM


Find the output for the given code segments
A)

B)

C)
7. Consider a table EMP , Find the output for the given code segments

a) # Assume All basic setup related to connection and cursor creation is already done
query="select * from emp"
mycursor.execute(query)
result = mycursor.fetchone()
result = mycursor.fetchone()
print(result[0],result[1],result[2])
print(“Total records selected “, mycursor.rowcount)

O/P --- 2 LINES

b) # Assume All basic setup related to connection and cursor creation is already done
query="select * from emp where salary >50000;"
mycursor.execute(query)
result = mycursor.fetchall()
for i in result:
print(i[0],‟#‟,i[2])
print(“Total records selected “, mycursor.rowcount)

O/P --- 3 LINES

c) # Assume All basic setup related to connection and cursor creation is already done
query="select * from emp where salary >30000;"
mycursor.execute(query)
results = mycursor.fetchone()
print(“Total records selected “, mycursor.rowcount)
results = mycursor.fetchone()
print(“Total records selected “, mycursor.rowcount)
results = mycursor.fetchmany(2)
print(“Total records selected “, mycursor.rowcount)

O/P --- 3 LINES

d) # Assume All basic setup related to connection and cursor creation is already done
query="select * from emp"
mycursor.execute(query)
results = mycursor.fetchone()
results = mycursor.fetchall()
for i in results:
print('Name:' , i[1],'Salary:',i[3])

O/P --- 4 LINES

PRACTICAL TYPE QUESTIONS


1) Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
Database : Company
Table : Employee( Eno integer , Ename Varchar ,Department Varchar , Salary Integer )
Write the following missing statements to complete the code:
import ________________________________________ as mysql # Statement 1
def disp_data():
con=mysql.______________________________________________________________________________________________
______________________________________________ # Statement 2
mycursor=con.___________________________________________ # Statement 3
mycursor.execute(„select * from employee‟)
data=mycursor.__________________________________________________________________________________________
____________________________# Statement4
print(“Total Records Selected”,_____________________________) # Statement5
con.close()

Statement 1 – Use the suitable package ,


Statement 2 – Establish the connection
Statement 3 – Create the cursor Object ,
Statement 4 – extract all the records from the result set
Statement5 – Display the row count

2) Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is tiger
Database : Company
Table : Employee( Eno integer , Ename Varchar ,Department Varchar , Salary Integer )
The given code is used to insert the details to table which are accepted from the user.
Write the following missing statements to complete the code:
import mysql.connector as mysql
def add_data():
con=mysql.connect(host="localhost",user="root", password="tiger", database="school")
mycursor=con.________________________________________________# Statement 1
eno=int(input("Enter the employee number"))
ename=input("Enter the name")
dept=input("Enter the department")
sal=int(input("Enter the salary"))
mycursor.execute(_______________________________________________________________) # Statement 2
con._________________________________________# Statement 3
print(_______________________________________,”Records Inserted Successfully “) # Statement4
con._______________________# Statement5

Statement 1 – Create the cursor Object,


Statement 2 – query to insert the record in to the table
Statement 3 –Command to add record permanently in the table ,
Statement 4 –Display the row count ,
Statement5- Terminate the connection object

3) Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is password
Database : Company
Table : Employee( Eno integer , Ename Varchar ,Department Varchar , Salary Integer )
The given code is used to select employee details those salary more than 25000
Write the following missing statements to complete the code:
import mysql.connector as mysql
def datashow():
con=mysql.connect(host="localhost",user="root", password="tiger", database="company")
mycursor=con._______________________________________# Statement 1
mycursor.execute(__________________________________________________________________) # Statement 2
data=________________________________________________________________________________ # Statement 3
print(“Total records selected”,__________________________________) # Statement4

Statement 1 – Create the cursor Object,


Statement 2 – query to select records of employees those salary more than 25000
Statement 3 – read the first 3 records from the result set ,
Statement 4 –Display the row count

4) Note the following to establish connectivity between Python and MYSQL:


Username is root
Password is password
Database : Company
Table : Employee( Eno integer , Ename Varchar ,Department Varchar , Salary Integer )
The given code is used to display employee details using the department which is input by user
Write the following missing statements to complete the code:
import mysql.connector as mysql
def searchdept():
con=mysql.connect(____________________________________________________________________________________
________________________________________________________) # Statement 1
mycursor=con.__________________________________________# Statement 2
Dept=int(input(“Enter the department for searching”)
mycursor.execute(____________________________________________________________________) # Statement 3
data=__________________________________________________________________________________# Statement 4
print(data)
data=___________________________________________________________________________________# Statement 5
print(data)

Statement 1 – Provide the attributes to establish the connection


Statement 2 – Create the cursor Object
Statement 3 – query to select records of employees according to the department .
Statement 4- read first record from the result set ,
Statement 5 – read rest of the records from result set

You might also like