Bca
Bca
PNRNo
DOJ
No_of_seats
Address
ContactNo
BusNo
SeatNo
SCHEMA
Reservation(PNRNo:String,DOJ:Date,NoofSeats:integer,Address:String,ContactNo:String,,BusN
o:String,SeatNo:Integer)
[3]
Cancellation
PNRNo
DOJ
SeatNo
ContactNo
Status
SCHEMA
[4]
CONCEPT DESIGNWITHE-RMODEL
[5]
VivaQuestions:
1. DefineDBMS?
2. Definetheterms
i)Entityii)Entitysetiii)weakentitysetiv)strongentityset?3.Whatis ER-diagram?
4. Whatarethedifferenttypesofentities?
5. Listvarioustypesofattributes?
[6]
EXPERIMENT –
2RELATIONALMODE
L
AIM:ToRepresentalltheentities(Strong,Weak)intabularfashion.Representrelationships inatabularfashion.
1. Bus:Bus(BusNo:String,Source:String,Destination:String,CoachType:String)
Mysql>createtableBus(BusNovarchar(10),sourcevarchar(20),Destinationvarchar(20),coachTypevarchar(10),primaryk
ey(BusNo));
Mysql>descBus;
Ticket:
Ticket(TicketNo:string,DOJ:date,Address:string,ContactNo:string,BusNo:String,SeatNo:Integer,Source:String,Destination:Stri
ng)
[7]
ColumnName Datatype Constraints TypeofAttributes
TicketNo Varchar(20) Primary Key Single-valued
Mysql>descTicket;
Passenger:
Passenger(PassportID:String,TicketNo:string,Name:String,ContactNo:string,Age:integer,Sex:character,Address:Str
ing);
Type
ColumnName Datatype Constraints
ofAttribut
es
PassportID Varchar(15) Primary Key Single-valued
[8]
TicketNo Varchar(20) ForeignKey Single-valued
[9]
Name Varchar(20) Composite
ContactNo Varchar(20) Multi-valued
Age Integer Single-valued
Sex character Simple
Address Varchar(20) Composite
Mysql>Createtablepassenger(passportIDvarchar(15),TicketNo
varchar(15),Namevarchar(15),ContactNovarchar(20),Age integer, sex char(2),address varchar(20), primary
key(passportID,TicketNo),foreignkey(TicketNo)references Ticket(TicketNo));
Mysql>descpassenger;
Reservation:
Reservation(PNRNo:String,DOJ:Date,NoofSeats:integer,Address:String,ContactNo:String,
,BusNo:String,SeatNo:Integer)
[10]
BusNo Varchar(10) Foreign Single-valued
Key
SeatNo Integer Simple
Mysql>Create table Resevation(PNRNo varchar(20),DOJ date,NoofSeates integer,Address
varchar(20),ContactNovarchar(20),BusNo varchar(20),SeatNo integer, primary key(PNRNo,BusNo),foreign
key(BusNo) referencesBus(BusNo));
Mysql>descreservation;
Cancellation:
Cancellation(PNRNo:String,DOJ:Date,SeatNo:integer,ContactNo:String,Status:String)
Mysql>desccancellation;
[11]
VivaQuestions:
1Whatisrelationschemaandarelation?2.W
hatisRelationand Relationship?
3. DefineInstanceandSchema?
4. WhatisthedifferencebetweenERandRelationalModel?5.Wh
atis thedegreeofrelation?
[12]
EXPERIMENT–
3NORMALIZATIO
N
Normalizationisaprocessofconvertingarelationtobestandardformbydecompositionalarger
relationintosmallerefficientrelation thatdepictsagooddatabasedesign.
1NF: A Relation scheme is said to be in 1NF if the attribute values in the relation are atomic.i.e., Mutli –
valuedattributes arenotpermitted.
2NF: A Relation scheme is said to be in 2NF,iff and every Non-key attribute is fully functionally dependent
onprimaryKey.
3NF:ARelationschemeissaidtobein 3NF,iffanddoesnothavetransitivitydependencies.ARelationissaidtobe
3NFifeverydeterminantis akeyforeach&everyfunctionaldependency.
BCNF: A Relation scheme is said to be BCNF if the following statements are true for eacg FD P->Q in set F
ofFDs that holds for each FD. P->Q in set F of FD’s that holds over R. Here P is the subset of attributes of R &
QisasingleattributeofR.
ThegivenFDisatrival
Pisasuperkey.
[13]
Normalizedtables are:-
Mysql>createtableBus2(BusNovarchar(20) primarykey,Sourcevarchar(20),Destinationvarchar(20));
Mysql>Createtablepassenger4(PPNvarchar(15)Primarykey,Namevarchar(20),Age
integer,Sexchar,Addressvarchar(20));
Mysql>CreatetablePassengerTicket(PPNvarchar(15)Primarykey,TicketNointeger);
Mysql>CreatetableReservation2(PNRNOintegerPrimarykey,JourneyDateDateTime,NoofSeatsint,Addressvarchar(2
0),ContactNoInteger);
Mysql>CreatetableTicket2(TicketNo
IntegerPrimarykey,JourneyDateDateTime,AgeInt(4),Sexchar(2),Sourcevarchar(20),Destinationvarchar(20),DeptTi
mevarchar(2));
VivaQuestions:
1.Define
Redundancy?2.Whatisdec
omposition?3.What
isNormalization?
4.What is fully functional
dependency?5.ListthedifferenttypesofNor
malforms?
[14]
EXPERIMENT –
4PRACTICINGDDLCOMMAND
S
AIM:CreatingTablesandaltering theTables
Mysql>Createtablepassenger2(passportIdIntegerPrimaryKey,Namevarchar(10)NotNull,
AgeIntegerNotNull,Sexchar,Addressvarchar(20)Not Null);
Mysql>descpassenger2;
USINGALTERCOMMAND
AddingExtracolumntoExistingTable
Mysql>Altertablepassenger3addcolumnTicketNovarchar(10);
[15]
Mysql>AlterTablepassenger3addForeignkey(TicketNo)referencesTicket(TicketNo);
Mysql>AlterTablepassenger3 ModifycolumnNamevarchar(20);
[16]
Mysql>Altertablepassengerdropforeignkeyfk1;
Mysql>Altertablepassenger2DropcolumnTicketNo;
VivaQuestions:
1. WhatisDDL?
2. Whatarethedifferenttypesofcommands
usedinDDLlanguage?3.Differencebetweendropandtruncate?
DBMS?5.DefineDatabase?
[17]
EXPERIMENT –
5PRACTICINGDMLCOMMAND
S
AIM:CreateaDMLCommandsareusedtomanagedatawithintheschemeobjects.
DMLCommands:
INSERTCOMMANDONBUS2&PASSENGER2RELATIONS
mysql>select*fromBus2;Emptyset(0.00sec)
mysql>insertintoBus2values(1234,'Hyderabad','Tirupathi');Que
ryOK,1rowaffected(0.03sec)
values(2345,'Hyderabad','Banglore');QueryOK,1rowaffected(0.
01sec)
values(23,'Hyderabad','Kolkata');QueryOK,1rowaffected(0.03
sec)
mysql>insertintoBus2values(45,'Tirupathi','Banglore');QueryO
K,1rowaffected(0.03sec)
mysql>insertintoBus2values(34,'Hyderabad','Chennai');QueryO
K,1rowaffected(0.03sec)
[18]
mysql>select *fromBus2;
[19]
mysql>select*fromPassenger2;E
mptyset(0.00sec)
mysql>insertintoPassenger2values(145,'Ramesh',45,'M','abc123');Q
ueryOK,1rowaffected(0.05sec)
mysql>insertintoPassenger2values(278,'Geetha',36,'F','abc124');Q
ueryOK,1rowaffected(0.02sec)
mysql>insertintoPassenger2values(4590,'Ram',30,'M','abc12');Q
ueryOK,1rowaffected(0.03sec)
mysql>insertintoPassenger2values(6789,'Ravi',50,'M','abc14');Q
ueryOK,1rowaffected(0.03sec)
mysql>insertintoPassenger2values(5622,'Seetha',32,'F','abc55');Quer
yOK,1rowaffected(0.03sec)
mysql>select*fromPassenger2;
[20]
UPDATECOMMANDONBUS2RELATION
UPDATESelectedRows&MultipleRows
mysql>UpdateBus2SETSource='Secundrabad'whereBusNo=1234;QueryOK,1rowaffected
(0.05sec)Rowsmatched:1Changed:1Warnings:0
[21]
DELETECOMMANDONBUS2RELATION
DELETESSelectedRowsand MultipleRows
select*from Bus2;
[22]
mysql>DeletefromBus2whereSource=’Secundrabad’;QueryOK,1rowaffected (0.05sec)mysql>
select*from Bus2;
VivaQuestions:
1. WhatisDML?
2. WhatistheuseofDMLinDBMS?3.W
hataretheDMLCommands?
4. WhatistheuseofAlter
commandinDBMS?5.Defineview?
[23]
EXPERIMENT– 6
Querying(usingANY,ALL,IN,Exists,
NOTEXISTS,UNION,INTERSECT,Constraintsetc.)Aim:PracticethefollowingQueries:
1. DisplayuniquePNR_NOofallpassengers
2. Displayallthenamesofmalepassengers.
3. Displaytheticketnumbersandnamesofallthepassengers.
4. Findtheticketnumbersofthepassengerswhosenamestartwith‘r’andendswith‘h’.
5. Findthenamesof Passengerswhoseageisbetween30 and45.
6. Displayallthe passengersnamesbeginningwith‘A’.
7. DisplaythesortedlistofPassengersnames
[24]
mysql>insertintopassenger2values(82302,'Smith',23,'M','Hyderabad');QueryO
K,1rowaffected(0.02sec)
mysql>insertintopassenger2values(82303,'Neha',23,'F','Hyderabad');Q
ueryOK,1rowaffected(0.01sec)
mysql>insertintopassenger2values(82304,'Neha',35,'F','Hyderabad');Qu
eryOK,1rowaffected(0.03sec)
mysql>insertintopassenger2values(82306,'Ramu',40,'M','Hyderabad');QueryO
K,1rowaffected(0.02sec)
mysql>insertintopassenger2values(82308,'Aakash',40,'M','Hyderabad');Quer
yOK,1rowaffected(0.02sec)
mysql>insertintopassenger2values(82402,'Aravind',42,'M','Hyderabad');Quer
yOK,1rowaffected(0.02sec)
values(82403,'Avinash',42,'M','Hyderabad');QueryOK,1rowaffected(0.02sec)
values(82502,'Ramesh',23,'M','Hyderabad');QueryOK,1rowaffected(0.02sec)
mysql>insertintopassenger2values(82602,'Rajesh',23,'M','Hyderabad');Query
OK,1rowaffected(0.02sec)
[25]
RESERVATION2
mysql>insertintoreservation2values(10201,'2012-02-
2010:20:25',05,'HYD',9654235242);QueryOK,1rowaffected(0.03sec)
mysql>insertintoreservation2values(10202,'2012-02-
2210:22:25',05,'HYD',9654232451);QueryOK,1rowaffected(0.02sec)
54587960);QueryOK,1rowaffected(0.01sec)
mysql>insertintoreservation2values(10204,'2013-03-
2211:30:25',05,'CHENNAI',9845761254);QueryOK,1rowaffected(0.02sec)
1. DisplayuniquePNR_NOofallreservationMysql>SelectDI
STINCTPNR_NOfromReservation;
PNR_No
10201
10202
10203
10204
[26]
2. Displayallthenamesof malepassengers.
mysql>Selectp.namefrompassenger2p
where
p.passportidIN(selectp2.passportidfrompassenger2p2wh
ere p2.sex='M');
[27]
[28]
3. Displaythe ticketnumbers andnamesofallthepassengers.
mysql>selectt.ticketno,p.namefrompassengertickett,passenger2pwheret.passportid=p.passportid;
[29]
4. Findthe ticketnumbersofthe passengerswhosenamestartwith‘r’andendswith‘h’.
MySQL>SELECTNameFROMPassengerWHEREnameLIKE‘R%H’
Name
Rajesh
Ramesh
Ramesh
[30]
5. FindthenamesofPassengerswhoseageisbetween30and45.
[31]
6. Displayallthepassengersnamesbeginningwith‘A’.
MySQL>SELECT*FROMPASSENGERWHERENAMELIKE‘A%’;
Name
Akash
Arivind
Avinash
[32]
7. Displaythesorted listofPassengersnames
MySQL>SELECT NAMEFROMPASSENGERORDERBYNAME;
VivaQuestions:
1.WhataretheDifferenttypesofset
operators?2.Whataretheaggregateoperators?
3.WhatisthedifferencebetweenANYandORoperators?4.W
hatis NULLValues?
5. WhatistheuseofEXISTSoperator?
[33]
EXPERIMENT– 7
QueryingAggregateFunctions(GROUPBY,HAVINGandCreationandDroppingofViews)
Aim:ToPracticeQueriesusingAggregatefunctionsforthefollowing
1. WriteaQuerytodisplaytheinformationpresentinthepassengerandcancellationtables
2. Displaythenumberofdaysinaweek onwhichthe AP123 busisavailable
3. FindnumberofticketsbookedforeachPNR_NousingGROUPBYCLAUSE
4. FindthedistinctPNRNumbersthatarepresent.
1. WriteaQuerytodisplaytheinformationpresentinthepassengerandcancellationtables
MYSQL>CREATETABLECANCELLATION2(PNRNOINTPRIMARYKEY,JOURNEYDATEDATETIME,NOO
FSEATS INT,ADDRESS VARCHAR(20),CONTACTNO INT,STATUS
VARCHAR(10),FOREIGNKEY(PNRNO)REFERENCESRESERVATION2(PNRNO));
[34]
MySQL>SELECT*FROMRESERVATIONUNIONSE
LECT*FROM CANCELLATION;
MySQL>SELECT MIN(AGE)asMINAGEFROMPASSENGER;
[35]
3. FindnumberofticketsbookedforeachPNR_NousingGROUPBYCLAUSE
4 FindthedistinctPNRNumbersthatarepresent.
MySQL>SELECTDISTINCTPNR_NOFROMRESERVATION2;
[36]
5 Mysql>selectsum(Noofseats)fromCancellation2;
6 Findthetotalnumberofcancelledseats.
MySQL>selectsum(noofseats)ascanceled_seatsfromcancellation2;
[37]
CreationandDropingofViews
mysql>createtablestudents(sidintprimarykey,namevarchar(15),loginvarchar(15),ageint,gpar
eal);mysql>createtableEnrolled(sidint,cidint,gradevarchar(5),primarykey(sid,cid),foreignke
y(sid)referencesstudents(sid));
mysql>createviewBStudents(name,sid,course)ASSELECTs.name,s.sid
,E.cidfromstudentss,enrolledEwheres.sid=e.sidANDE.grade='B';
Syntax:Dropviewviewname;
Mysql>DropviewBstudents;Mysql>DropviewGoodstudents;
VivaQuestions:
1. WhatisNestedquery?
2. What is the use of Group By
Clause?3.DefineJoin?Listdifferenttypesofj
oins?
4.Whatisdifferencebetweenleftouterjoinandrightouterjoin?5.WhatisC
o-relatednestedquery?
[38]
EXPERIMENT-8
Triggers
Aim:Creationofinserttrigger,deletetriggerandupdatetrigger.
MySQL>INSERTINTOBUSVALUES('AP123','HYD','CHENNAI','40');
[39]
CREATE TRIGGER BEFORE_BUS_UPDATE BEFORE UPDATE ON
BUSFOREACHROWBEGIN
INSERTINTOBUS_AUDIT1
SETaction='update',source=OLD.source,changedon=NOW();END$$
UPDATE:
MySQL>UPDATEBUSSETSOURCE='KERALA'WHEREBUSNO='AP123'$$
[40]
SNo Source Changedon Action
1 Banglore 2014:03:2312:51:00 Insert
2 Kerela 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete
INSERT:
BUSFOREACHROWBEGIN
INSERTINTOBUS_AUDIT1
SETaction='Insert',source=NEW.source,changedon=NOW();END$$MYSQL>INSERTI
NTOBUSVALUES('AP789','VIZAG','HYDERABAD',30)$$
[41]
CREATETRIGGERBEFORE_BUS_DELETEBEFOREDELETEONBUSFOREA
CHROWBEGIN
DELETEFROMBUS_AUDIT1
SETaction='Insert',source=NEW.source,changedon=NOW();END$$DE
LETEFROMBUSWHERESOURCE=’HYDERABAD’$$
Examples
CREATETRIGGERupdcheck1BEFOREUPDATEONpassengerticketFOREACHROWBEGIN
IFNEW.TicketNO>60THEN
SETNew.TicketNo=New.TicketNo;ELSESE
TNew.TicketNo=0;ENDIF;
END;
[42]
VivaQuestions:
1. DefineTrigger?
2. Whatarethetypesoftriggers?
3. Whatistheadvantageoftriggerindatabase4.D
efineActive databases?
5.Whenwe applytrigger?
[43]
Experiment-9
Procedures
Aim:CreationofstoredProceduresandExecutionofProceduresandModificationofProcedures.
Ex1:
CREATEPROCEDUREBUS_PROC1()BEGINSE
LECT*FROMBUS;
END$$
CALLBUS_PROC1()$$
Ex2:
CREATEPROCEDURESAMPLE2()BEGIND
ECLAREXINT(3);SETX=10;
SELECTX;
END$$
Mysql>CALLSAMPLE2()$$
[44]
Ex3:CREATEPROCEDURESIMPLE_PROC(OUTPARAM1INT)BEGINSELEC
TCOUNT(*)INTOPARAM1FROMBUS;
END$$
Mysql>CALLSIMPLE_PROC(@a)$$Mysql>select@a;
[45]
VivaQuestions:
1. WhatdoyoumeanbyProcedure?
2. Whatisstoredproceduresusedindatabases?3.
Whatis storedprocedure?
4. Whataretheadvantageofusing stored procedure?
5. Listdifferenttypesofkeys indbms?
[46]
EXPERIMENT-
10USAGECURSO
RS
Aim: Declare a cursor that defines a result set. Open the cursor to establish the result
set.Fetch the data into local variables as needed from the cursor, one row at a time. Close
thecursorwhendone.
Cursors
In MySQL, a cursor allows row-by-row processing of the resultsets.Acursor
is used for the result set and returned fromaquery.By usingacursor,you can
iterate,orby step through theresultsofaqueryandperform certain operations on
each row. The cursor allows you to iteratethrough the result set
andthenperformthe additionalprocessing only ontherowsthatrequire it.
Therearesomestepswehavetofollow,givenbelow:
□ Declareacursor
□ Openacursorstatement
□ Fetchthecursor
□ Closethecursor
1 .DeclarationofCursor:TodeclareacursoryoumustusetheDECLAREstateme
nt.Withthehelpofthevariables,conditionsandhandlers we need to declare a
cursor before we can use it. first of all we willgive the cursor a name, this is
how we will refer to it later in the procedure.We can have more than one
cursor in a single procedure so its necessary togive it a name that will in some
way tell us what its doing. We then need tospecify the select statement we
want to associate with the cursor. The
SQLstatementcanbeanyvalidSQLstatementanditispossibletouseadynamicwher
eclauseusingvariableorparametersaswehaveseenpreviously.
[47]
Syntax:DECLAREcursor_nameCURSORFORselect_statement;
2 .Openacursorstatement:Foropenacursorwemustusetheopenstatement
.Ifwewanttofetchrowsfromityoumustopenthecursor.
Syntax:OPENcursor_name;
3 .Cursorfetchstatement:Whenwehavetoretrievethenextrowfromthecurs
orandmovethecursor
tonextrowthenyouneedtofetchthecursor.
Synatx:FETCHcursor_nameINTOvar_name;
Ifanyrowexists,thentheabovestatementfetchesthenextrowandcursorpointermovesah
eadtothe nextrow.
4 .Cursorclosestatement:By thisstatementclosedtheopencursor.
Syntax:CLOSE_name;
By
thisstatementwecanclosethepreviouslyopenedcursor.Ifitisnotclosedexplicitl
y
thenacursorisclosedattheendofcompoundstatementinwhichthatwasdeclared.
Delimiter$$
[48]
VivaQuestions:
1. HowCursorusedinDatabase?
2. HowmanytypesofCursorsinMySql?3.H
owtoopenandclosetheCursor?
4.Differentiate Procedure and
Cursor?5.Canyou
passaparametertoaCursor?
[49]
ADDITIONALPROGRAMMS
EMPLOYEESTABLE
mysql>createtableEmployees(ssnvarchar(15),namevarchar(20),lotint,PRIMARYKEY(ssn));my
sql>insertintoEmployeesvalues('123-22-3666','Attishoo',48);
mysql>insertintoEmployeesvalues('321-31-
5368','Smiley',22);mysql>insertintoEmployeesvalues('131-24-3650','Smethurst',35);
[50]
DEPARTMENTTABLE
mysql> create table Departments(did int,dname varchar(10),budget real,
PRIMARYKEY(did));
values(05,'CSE',500000);mysql>insertintoDepartmentsval
Departmentsvalues(03,'ME',300000);mysql>insertintoDep
artmentsvalues(01,'CE',100000);
[51]
Sailors ,Reserves ,BoatsTables
Mysql>CreatetableSailors(SidintegerPRIMARYKEY,snamevarchar(15),ratingint,agereal);Mys
ql>CreatetableReserves(Sidint,Bidint,DayDate);
Mysql>CreatetableBoats(Bidint,Bnamevarchar(15),Colorvarchar(15);
[52]
mysql>selectS.snamefromsailorsS,reservesRwhereS.sid=R.sidANDR.bid=103;
mysql>selectsnamefromsailorss,ReservesRwhereS.sid=R.sidANDbid=103;mysql>selectR.sidfr
omBoatsB,ReservesRwhereB.bid=R.bidANDB.color='red';
mysql>selectS.snamefromsailorsS,reservesR,BoatsBwhereS.sid=R.sidANDR.bid=B.bidAN
DB.color='red';
mysql>selectB.colorfromSailorsS,ReservesR,BoatsBwhereS.sid=R.sidANDR.bid=B.bidA
NDS.sname='Lubber';
[53]
mysql>selectS.sname,S.rating+1ASratingfromSailorsS,ReservesR1,ReservesR2whereS.sid=R1
.sidANDS.sid=R2.sidANDR1.day=R2.dayANDR1.bid<>R2.bid;
mysql>selectS1.snameASname1,S2.snameASname2fromsailorsS1,sailorsS2where2*S1.rat
ing=S2.rating-1;
[54]
N,INTERSECT,ANDEXCEPT
1).Findthe namesofsailorswhohavereservedaredoragreenboat.
OR
[54]
2).Findthenamesofsailorswhohavereservedbotharedandagreenboat.SELECTS.SNA
ME
FROMSAILORSS,RESERVESR,BOATSB
INTERSECTSELECTS2.SNAME
FROMSAILORSS2,RESERVESR2,BOATSB2
WHERES2.SID=R2.SIDANDR2.BID=B2.BIDANDB2.COLOR='green';
NESTEDQUERIES
1) FindtheNamesofsailorswhohavereservedboat103
2) FindthenamesofSailorswhohavereservedaredBoat
[53]
3) FindthenamesofSailorswhohaveNOTreservedaredBoat
CorrelatedNestedQueries:
1)FindthenamesofSailorswhohavereservedaredBoat
SetComparisonOperators:
1) FindsailorswhoseratingisbetterthansomesailorcalledHoratio
[54]
2) Findthesailorswiththehighestrating.
mysql>SELECTS.sidFORMSailorsWHERES.rating>=ALL(SELECTS2.ratingFROMSailorsS2
);
TheGROUPBYandHAVINGClauses:
1) Findtheageoftheyoungestsailorforeachratinglevel.
2) Findtheageoftheyoungestsailorwhoiseligibletovoteforeachratinglevelwithatleasttwosuc
hsailors
[55]
3) Foreachredboat,findthenumberofreservationsforthisboat
4) Findtheaverageageofsailorsforeachratinglevelthathasatleasttwosailors
[56]