PROGRAM 21 STATIONERY AND CONSUMER
To create two tables for stationery and consumer and execute the given commands
using SQL.
TABLE: STATIONERY
S_ID StationeryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
TABLE: CONSUMER
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bangalore PL01
i) To display the details of those Consumers whose Address is Delhi
ii) To display the details of Stationery whose Price is in the range of 8to 15(Both
valuesincluded)
iii) To display the ConsumerName , Address from table Consumer and Company and
Pricefrom table Stationery with their correspondingmatching S_ID
iv) To increase the Price of all Stationery by 2.
v) To display distinct Company from STATIONERY.
90
CREATE TABLE STATIONERY (S_ID char(5) NOT NULL PRIMARY KEY,
StationeryName char(25), Company char(5), Price int);
INSERT INTO STATIONERY VALUES(“DP01” , “Dot Pen”, “ABC”, 10);
INSERT INTO STATIONERY VALUES(“PL02” , “Pencil”, “XYZ”, 6)
CREATE TABLE CONSUMER (C_ID int , ConsumerName char(25), Address
char(25), S_ID char(5));
INSERT INTO CONSUMER VALUES(1, “Good Learner”, “Delhi”, “PL01”);
INSERT INTO CONSUMER VALUES(6,”Write Well”,”Mumbai”,”GP02”);
91
OUTPUT:
i) Select * from consumer where address=”delhi”;
c_id consumername address S_id
1 Good Learner Delhi PL01
12 Topper Delhi DP02
15 Write &Draw Delhi PL02
ii) select * from stationery where price between 8 and 15;
S_id stationery company price
Dp01 Dot Pen ABC 10
GP02 Gel Pen ABC 15
iii) select consumername, address, company, price from
stationery,consumer where stationery.s_id=consumer.s_id;
consumername address company Price
Good Learner Delhi CAM 5
Write Well Mumbai ABC 15
Topper Delhi ABC 10
Write & Draw Delhi XYZ 6
Motivation Bangalore CAM 5
92
iv) update stationery set price=price+2;
v) select * from stationery;
S_id stationary company
Price
DP01 Dot pen ABC 12
PL02 Pencil XYZ 8
ER05 Eraser XYZ 9
PL01 Pencil CAM 7
GP02 Gel pen ABC 17
vi) select distinct(company) from stationery;
Company
ABC
XYZ
CAM
93
PROGRAM 22
ITEM AND TRADERS
To create two tables for item and traders and execute the given
commands using SQL.
TABLE:ITEM
Code IName Qty Price Company TCode
1001 DIGITAL PAD 121 120 1100 XENTIA T01
1006 LED SCREEN 40 70 3800 SANTORA T02
1004 CAR GPS SYSTEM 50 2150 GEOKNOW T01
1003 DIGITAL CAMERA 160 8000 DIGICLICK T02
1005 PEN DRIVE 32GB 600 1200 STOREHOME T03
TABLE:TRADERS
TCode TName City
T01 ELECTRONICS SALES MUMBAI
T03 BUSY STORE CORP DELHI
T02 DISP HOUSE INC CHENNAI
i) To display the details of all the items in ascending order of item names (i.eIName)
ii) To display item name and price of all those items, whose price is in the range of
10000 and 22000 (both values inclusive)
iii) To display the number of items , which are traded by each trader.
The expected output of this query should be
T01 2
T02 2
T03 1
iv) To display the Price , item name(i.e IName) and quantity(i.e Qty) ofthose
items which have quantity more than 150.
94
v) To display the names of those traders, who are either from
DELHI or from MUMBAI.
CREATE TABLE ITEM(Code int , IName char(25) , Qty int , Price int , Company
char(25),TCode char(5));
INSERT INTO ITEM VALUES(1001,”DIGITAL PAD 121”,120, 11000,”XENTIA”,
“T01”);
INSERT INTO ITEM VALUES(1006,”LED SCREEN 40”,70, 38000,”SANTORA”,
“T02”);
CREATE TABLE TRADERS(TCode char(5) , TName char(25), City char(20));
INSERT INTO TRADERS VALUES(“T01”,”ELECTRONICS SALES”,”MUMBAI”);
INSERT INTO TRADERS VALUES( “T03”,”BUSY STORE CORP”,”DELHI”);
95
OUTPUT:
i) select * from ITEM order by IName;
Code IName Qty Price Company TCode
1004 CAR GPS SYSTEM 50 2150 GEOKNOW T01
1003 DIGITAL CAMERA 160 8000 DIGICLICK T02
12X
1001 DIGITAL PAD 121 120 11000 XENTIA T01
1006 LED SCREEN 70 38000 SANTORA T02
1005 PEN DRIVE 32GB 600 1200 STORE HOME T03
ii) select IName , Price from ITEM where Price between 10000 and 22000;
IName Price
DIGITAL PAD 121 11000
iii) select TCode , count(*) from ITEM group by TCode;
Tcode Count(*)
T01 2
T02 2
T03 1
iv) select Price , IName , Qty from ITEM where Qty>150;
Price IName Qty
8000 DIGITAL CAMERA 12X 160
1200 PEN DRIVE 32GB 600
v) select TName from TRADERS where City in (“DELHI”,”MUMBAI”);
TName
ELECTRONICS SALES
BUSY STORE CORP
96
PROGRAM 23
DOCTOR AND SALARY
To create two tables for doctor and salary and execute the givencommands
using SQL.
TABLE:DOCTOR
ID NAME DEPT SEX EXPERIENC
E
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15
TABLE: SALARY
ID BASIC ALLOWANCE CONSULTATION
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300
i) Display NAME of all doctors who are in “MEDICINE” having
more than 10 years’ experience from table DOCTOR
ii) Display the average salary of all doctors working in “ENT” department
using the table DOCTOR and SALARY.
(Salary=BASIC+ALLOWANCE)
iii) Display minimum ALLOWANCE of female doctors.
97
iv) Display DOCTOR.ID , NAME from the table DOCTOR and
BASIC ,ALLOWANCE from the table SALARY with their
corresponding matching ID.
v) To display distinct department from the table doctor.
CREATE TABLE DOCTOR(ID int NOT NULL PRIMARY KEY, NAME char(25) ,
DEPT char(25) , SEX char , EXPERIENCE int);
INSERT INTO DOCTOR VALUES(101,”John”, “ENT”,’M’,12);
INSERT INTO DOCTOR VALUES(104,”Smith”, “ORTHOPEDIC”,’M’,5);
CREATE TABLE SALARY(ID int, BASIC int, ALLOWANCE int, CONSULTATION
int);
INSERT INTO SALARY VALUES(101, 12000,1000,300);
INSERT INTO SALARY VALUES(104, 23000,2300,500);
RESULT: Thus the given program is executed successfully.
98
OUTPUT:
i) select NAME from DOCTOR where
DEPT=”MEDICINE” and EXPERIENCE >10;
NAME
Bill
ii) select avg(BASIC+ALLOWANCE) “avg salary” from
DOCTOR , SALARYwhere DOCTOR.ID=SALARY.ID
and DEPT=”ENT”;
Avg salary
13000.00
iii) select min(ALLOWANCE) from SALARY, DOCTORwhere
SEX=’F’and DOCTOR.ID=SALARY.ID;
min(ALLOWANCE)
1700
iv) select DOCTOR.ID, NAME, BASIC
,ALLOWANCE from DOCTOR, SALARY where
DOCTOR.ID=SALARY.ID;
ID NAME BASIC ALLOWANCE
101 John 12000 1000
104 Smith 23000 2300
107 George 32000 4000
109 K George 42000 1700
114 Lara 12000 5200
130 Morphy 21700 2600
v) select distinct(DEPT) from DOCTOR;
DEPT
ENT
ORTHOPEDIC
CARDIOLOGY
SKIN
MEDICINE
99
PROGRAM 24
MYSQL QUERIES
Consider the following DEPT and EMPLOYEE tables .
Write SQL queries for the following :
TABLE : DEPT
DCODE DEPARTMENT LOCATION
DO1 INFRASTRUCTURE DELHI
DO2 MARKETING DELHI
DO3 MEDIA MUMBAI
DO4 FINANCE KOLKATA
DO5 HUMAN RESOURCE MUMBAI
TABLE: EMPLOYEE
WNO NAME DOJ DOB GENDER DCODE SALARY
1001 GEORGE K 2013-09-02 1991-09-01 MALE DO1 76000
1002 RYMA SEN 2012-12-11 1990-12-15 FEMALE DO3 64000
1003 MOHITESH 2013-02-03 1987-09-04 MALE DO5 56000
1007 ANIL JHA 2014-01-17 1984-10-19 MALE DO4 78000
1004 MANILA 2012-12-09 1986-11-14 FEMALE DO1 43000
SAHITA
1005 R SAHAY 2013-11-18 1987-03-31 MALE DO1 69000
1006 JAYA PRIYA 2014-06-09 1985-06-23 FEMALE DO5 65000
1. To display WNO ,NAME ,GENDER from the table
EMPLOYEE in ascending order of worker number.
2. To display the name of all male employees
3. To display WNO,NAME of those workers from the table
EMPLOYEE who are born between ‘1987-01-01’ and
‘1991-12-01’ .
4. To display the count of female employees who have joined after ‘ 1986-
01-01’
5. To display maximum , minimum WNO from the table employee
100
6. To display total number of employees in each department
7. To display department code , sum of salary for each department
having count greater than 1
8. Add a new column BONUS of type float
9. To set BONUS as 10 % of salary for all employees.
10. To display employee name , department name ,location of all
employees having salary >60000.
101
OUTPUT:
1.SELECT WNO, NAME, GENDER FROM EMPLOYEE ORDER BY WNO
ASC;
2. SELECT NAME FROM EMPLOYEE WHERE GENDER= ‘MALE’;
3. SELECT WNO,NAME FROM EMPLOYEE where DOB between ‘1987-01-
01’ and ‘1991-12-
01’;
102
4. SELECT COUNT(*) FROM EMPLOYEE WHERE GENDER=’FEMALE’
AND DOJ >’1986-01-01’;
5. SELECT MAX(SALARY) , MIN(SALARY) FROM EMPLOYEE;
6. SELECT COUNT(*) FROM EMPLOYEE GROUP BY DCODE;
7. SELECT DCODE,SUM(SALARY) FROM EMPLOYEE
GROUP BY DCODE HAVING COUNT(DCODE)>1;
103
8. ALTER TABLE EMPLOYEE ADD BONUS FLOAT;
9. UPDATE EMPLOYEE SET BONUS=10/100*SALARY;
10. SELECT NAME,DEPARTMENT,LOCATION
FROM EMPLOYEE E, DEPT DWHERE
E.DCODE=D.DCODE AND SALARY>60000;
104
PROGRAM 25
INTERFACE SQL WITH PYTHON
PROGRAM DEFINITION
To create a table, insert the records in tothe table and to display them.
VARIABLES:
con – variable name for connector object
cur – variable name for Cursor instance
Eno – Variable for storing the Employee number
Name - Variable for storing the Employee name
salary - Variable for storing the Employee salary
query – variable for storing the sql query
ch – variable for storing the confirmation message from the user
data – variable to store the resultant set
i – It is the iterative variable
105
PROGRAM CODE:
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="srimathi"
,database="employee")
cur=con.cursor()
cur.execute("Create table EMPL(Eno int,Ename varchar(10),Esal float)")
print("table created successfully:")
while True:
Eno=int(input("Enter Employee Number :"))
Name=input("Enter Employee Name:")
salary=float(input("Enter Employee Salary"))
query="Insert into empl values({},'{}',{})".format(Eno,Name,salary)
cur.execute(query)
con.commit()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
if ch=="n":
break
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
print("Total number of rows retrieved=",cur.rowcount)
106
OUTPUT
107
PROGRAM 26
INTERFACE SQL WITH PYTHON
PROGRAM DEFINITION
To update the table using empno and to display the updated records
VARIABLES:
con – variable name for connector object
cur – variable name for Cursor instance
Eno – Variable for storing the Employee number
Name - Variable for storing the Employee name
salary - Variable for storing the Employee salary
query – variable for storing the sql query
ch – variable for storing the confirmation message from the user
data – variable to store the resultant set
i – It is the iterative variable
108
PROGRAM CODE
#Integrate SQL with Python by importing the MYSQL module to search an
employee using empno Update the record and display the updated records.
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="srimathi"
,database="employee")
cur=con.cursor()
print("BEFORE UPDATION")
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
query="Update empl set Ename='Sumita' where Eno=3"
cur.execute(query)
con.commit()
print("Rows updated successfully")
print("Displaying the records after updating...")
cur.execute("select * from empl ")
data=cur.fetchall()
for i in data:
print(i)
109
OUTPUT
BEFORE UPDATION
(1, 'Radha', 43000.0)
(2, 'Arjun', 78650.0)
(3, 'Rakshitha', 23000.0)
Rows updated successfully
Displaying the records after updating...
(1, 'Radha', 43000.0)
(2, 'Arjun', 78650.0)
(3, 'Sumita', 23000.0)
110
PROGRAM 27
INTERFACE SQL WITH PYTHON
PROGRAM DEFINITION
To search for an employee using empno and delete the record.
VARIABLES:
con – variable name for connector object
cur – variable name for Cursor instance
Eno – Variable for storing the Employee number
Name - Variable for storing the Employee name
salary - Variable for storing the Employee salary
query – variable for storing the sql query
ch – variable for storing the confirmation message from the user
data – variable to store the resultant set
i – It is the iterative variable
111
PROGRAM CODE
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="srimathi"
,database="employee ")
cur=con.cursor()
query="DELETE FROM EMPL WHERE ENO=3 "
cur.execute(query)
con.commit()
print("Row deleted successfully")
print("Displaying the records after delete”)
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
112
OUTPUT
Row deleted successfully
Displaying the records after delete...
(1, 'Radha', 43000.0)
(2, 'Arjun', 78650.0)
113
PROGRAM 28
INTERFACE SQL WITH PYTHON
PROGRAM DEFINITION
Integrate SQL with Python by importing the MYSQL module to search and
delete the record.
VARIABLES:
con – variable name for connector object
cur – variable name for Cursor instance
Eno – Variable for storing the Employee number
Name - Variable for storing the Employee name
salary - Variable for storing the Employee salary
query – variable for storing the sql query
ch – variable for storing the confirmation message from the user
data – variable to store the resultant set
i – It is the iterative variable
114
PROGRAM CODE:
import mysql.connector as sqltor
#con =sqltor.connect(host = "localhost", user = "root",passwd="devi",
database="srimathi")
con=sqltor.connect(host="localhost",user="root",passwd="srimathi",database="
learnsql")
if con.is_connected() == False:
print("Error connecting to mysql")
else:
print("Connection is created successfully")
cur = con.cursor()
def createdb():
query="create database if not exists srimathi"
cur.execute(query)
print("database created successfully")
def changedb():
query="use srimathi"
cur.execute(query)
print("Database changed successfully")
def createtable():
query=’’’create table if not exists emp(eno integer,enamevarchar(20),sal
decimal(10,2))’’’
cur.execute(query)
print("Table created successfully")
query1 = ‘’’create table if not exists attn(eno integer,leaveavailable
integer,leavetaken integer)’’’
115
cur.execute(query1)
print("Attendance table created successfully")
def insert():
num = int(input("Enter the employee number:"))
name= input("Enter the name:")
sal =float(input("Enter salary:"))
query="insert into emp values({},'{}',{})".format(num,name,sal)
cur.execute(query)
con.commit()
print("Rows inserted successfully")
def insertattn():
num = int(input("Enter the employee number:"))
la= int(input("Enter the no of days leave available:"))
lt=int(input("Enter no of days leave taken:"))
query="insert into attn values({},{},{})".format(num,la,lt)
cur.execute(query)
con.commit()
print("Rows inserted successfully")
def search():
x=int(input("Enter the employee number to be searched"))
query="select * from emp where eno ={}".format(x)
cur.execute(query)
data = cur.fetchall()
for i in data:
print("Number:",i[0])
116
print("Name:",i[1])
print("salary:",i[2])
def delete():
x=int(input("Enter the employee number to be deleted"))
query ="delete from emp where eno ={}".format(x)
cur.execute(query)
con.commit() print("deleted succesfully")
def bonus():
query = "select * from emp"
cur.execute(query)
data =cur.fetchall()
for i in data:
y =float(i[2]) # because 3rd column is
salarybonusamt = 0.3*y
print("EmployeeNumber:",i[0])
print("Employee Name:",i[1])
print("Salary:",i[2])
print("Bonus::::",bonusamt)
def altertable():
query ="alter table emp add(desig varchar(20),hra float, pf float)"
cur.execute(query)
print("Table altered successfully columns added")
def update():
x=int(input("Enter the employee number for which data to be updated"))
d =input("Enter the designation")
117
h = float(input("Enter the amount:"))
p= float(input("Enter the pf amt:"))
q1 = "update emp set desig='{}' where eno = {}".format(d,x)
q2= "update emp set hra={} where eno = {}".format(h,x)
q3="update emp set pf={} where eno = {}".format(p,x)
cur.execute(q1)
cur.execute(q2)
cur.execute(q3)
con.commit()
print("Table updated successfully")
def display():
query ="select * from emp"
cur.execute(query)
data =cur.fetchall()
for i in data:
print(i)
def join():
query = "select emp.eno,ename,sal,leaveavailable,leavetaken fromemp,attn
where emp.eno=attn.eno"
cur.execute(query)
data=cur.fetchall()
for i in data:
print(i)
def netsal():
#grosssal = sal + hra
#lossofpay = if leavetaken > leaveavailable , excessleave = leavetaken
118
- leaveavailable
#lossamt =excessleave*(grosssal/30)
#netsal = sal + hra - pf - lossamt
q1="select * from emp,attn where emp.eno = attn.eno"
cur.execute(q1)
data = cur.fetchall()
for i in data:
gross=float(i[2])+i[ 4]
print(i)
if i[8]>i[7]:
ex=i[8]-i[7]
lossamt=ex*(gross/30)
net=gross-lossamt-i[5]
else:
net = gross-i[5]
print("********PAYSLIP**********")
print("Number:",i[0])
print("Name:",i[1])
print("NetSalary:",net)
print("****************************")
while True:
print("1.Creating a database")
print("2.Change the database")
print("3.Creating a table")
print("4.Inserting records in employee table:")
print("5. Inserting records in attendance table:")
119
print("6. Searching a record")
print("7. Bonus calculation")
print("8. Alter table")
print("9.Update")
print("10.Delete")
print("11.Display")
print("12.Join two tables")
print("13.Net Salary Calculation")
print("14. Exit")
ch = int(input("Enter a choice"))
if ch == 1:
createdb()
elif ch==2:
changedb()
elif ch ==3:
createtable()
elif ch ==4:
insert()
elif ch ==5:
insertattn()
elif ch == 6:
search()
elif ch == 7:
bonus()
elif ch == 8:
altertable()
elif ch == 9:
update()
120
elif ch==10:
delete()
elif ch==11:
display()
elif ch ==12:
join()
elif ch ==13:
netsal()
elif ch == 14:
break
121
INPUT AND OUTPUT
122