Académique Documents
Professionnel Documents
Culture Documents
Management
Systems
SujaySJamkhandi
SymbiosisInstituteofComputerStudiesandResearch
DatabaseManagementSystems
Database:
Sharedcollectionoflogicallyrelateddata(andadescriptionofthisdata),
designedtomeettheinformationneedsofanorganization.
Logicallyrelateddatacomprisesentities,attributesandrelationshipsofan
organization'sinfo.
Systemcatalogue(metadata)providesdescriptionofdatatoenableprogram
dataindependence.
DBMS(DatabaseManagementSystem)
Asoftwaresystemthatenablesuserstodefine,createandmaintainthe
databaseandthatprovidescontrolledaccesstothisdatabase.
ComponentsofDBMSEnvironment
Hardware:CanrangefromaPCtoanetworkofcomputers.
Software:DBMS,operatingsystem,networksoftware(ifnecessary)andalsothe
applicationprograms.
Data:Usedbytheorganizationandadescriptionofthisdatacalledtheschema.
Procedures:Instructionsandrulesthatshouldbeappliedtothedesignanduseofthe
databaseandDBMS.
Degree:Itisthetotalnoofattributes.
TypesofKeys:
PrimaryKey:Theprimarykeyhascertaincharacteristics.
o Unique
o Notchanging
o NotEmpty
SymbiosisInstituteofComputerstudiesandResearch
Page2
DatabaseManagementSystems
CandidateKey:Anentitywhichcansubstitute/replacetheprimarykeyi.e.it
actsasaprimarykeyintheabsenceofanactualprimarykey.
CompositePrimaryKey:Acombinationof2ormorethan2attributeswhich
togethercombinetoformaprimarykey.
Foreignkey:Akeywhichestablishesarelationbetween2entities.Aprimary
keywhichispresentinonetableandispresentinanothertableiscalleda
foreignkey.
SuperKey:Itisoneoftheprimarykeywhichismetamorphosized
AlternateKey:Theentitiesremainingaftertheselectingtheprimary,secondary
andtheforeignkeysarecalledasalternatekeys.
Secondarykey:Itissimilartoaforeignkey.
AdvantagesofDBMS:
Controlofdataredundancyandconsistency.
Moreinformationfromthesameamountofdata.
Sharingofdata.
Improveddataintegrity.
Improvedsecurity.
Improveddataaccessibilityandresponsiveness.
Higherimpactofafailure.
Increasedproductivity.
Improvedmaintenancethroughdataindependence.
Increasedconcurrency.
Improvedbackupandrecoveryservices.
DisadvantagesofDBMS:
Complexity
Size
CostofDBMS
Additionalhardwarecosts
Costofconversion
Performance
SymbiosisInstituteofComputerstudiesandResearch
Page3
DatabaseManagementSystems
ThreeLevelSchemaArchitecture:
Aschemaisadescriptionofthedatainterfacetothedatabase(i.e.howthedatais
organised).
1.Externalschema(view):whattheapplicationprogramsandusersee.
2.Conceptualschema:descriptionofthelogicalstructureofalldatainthedatabase.
3.Physicalschema:descriptionofphysicalaspects(selectionoffiles,devices,storage
algorithmsetc).
Entity:
Entitycanbeanaccount,activity,orcontactaboutwhichdatacanbestored.
TheycanbeclassifiedintoStrongandWeakentity.
StrongPrimarykeyiswelldefined.Theentityhassufficientattributesto
formaprimarykey
WeakPrimarykeyisnotclearlydefined.Theentityhasinsufficient
attributestoformaprimarykey.
Attribute:
Anattributeisapropertyofagivenentity.
Theycanbeclassifiedinto3units
Composite
Unit/Simple
Derived
Null
Singlevalued
Multivalued
Composite:Anattributewhichcanbebrokendownintosimplecomponents.
Eg:name
Unit/Simple:Anattributewhichcannotbefurtherdecomposed.
Eg:nationality
Derived:Anattributewhichisobtainedfromanotherattribute.
Eg:NetSalary
Null:Anattributewhichhasnovalue.
Singlevalued:Anattributewhichcanhaveasingledataentry
Eg:Nationality
SymbiosisInstituteofComputerstudiesandResearch
Page4
DatabaseManagementSystems
Multivalued:Anattributewhichcanhavemultipledataentries.
Eg:Contactno
Index:
Indexisdifferentphysicalfilewhichhelpsinsearchingandretrievingdata
Everytablegeneratesoneindexbydefault
Theendusercangenerateindexesdependingonhis/herrequirements.
Whenasearchismadeacrosstheentiretableitistermedastablescan.
Whenasearchismadeacrosstheentiretableusingtheindexkeyitistermedas
indexscan
Wecancreatemanyindexesbutthenoofindexeshastobeideallylessusing
onlythosefieldswhicharefrequentlyusedforasearch.
Theindexesgeneratedbytheenduserarealsomaintainedbythesystem.
Indexescanbeunique/commonbasedontherequirement.
Domain:Domainisasetofrangeofpermissiblevalues,itisimposedusingdatatype
andsizeforanattribute
Eg:namechar(30);
birthDateDate;
salaryfloat(11,2);salary>0andsalary<5,00,000
prnvarchar(11);
DifferencebetweencharandVarchar
charistermedasafixedlengthvariable
charallowsonlycharactervaluestobestored
Eg:namechar(10)="SICSR";Thisallocates10spacesinthememory,fivewith
value(SICSR)and5withblankspace.
Varcharistermedasvariablelengthvariable
Varcharallowsnumericaswellascharactervaluestobestored.
Eg:namevarchar(10)="SICSR"Thisallocatesonly5spacesinmemorywithvalue
(SICSR).
varchar2isthemostrecentdatatype,itbehavessimilartovarcharinmemory
allocationbutitsrangeisgreaterthanvarchar.
Constraints:Limitationorasetofrestriction.
SymbiosisInstituteofComputerstudiesandResearch
Page5
DatabaseManagementSystems
Objective:Validationofdata.
Ithelpstoidentifyredundancyinschemaandhelpstoreduceit.
Ithelpsinqueryprocessingandoptimizationofthequery.
Helpsindatabasedesignandtheapplicationdevelopment.
Classification:
Entitykeyconstraint:
o databaseconstraint
o primarykeyconstraint
o uniquekeyconstraint
o notnullconstraint
Referentialkeyconstraint:
o databaseconstraint
o foreignkeyconstraint
Businessconstraint:
o applicationdependent
o checkconstraint
o defaultconstraint
o domainconstraint
Constraintscanalsobeclassifiedbytheirmethodofenforcement.
Tablelevelconstraint
Columnlevelconstraint
o Tablelevelallowsconstraintstobeimposedonmorethanonecolumn
wherecolumnleveldoesnot.
o Functionallynodifferencebetweentablelevelandcolumnlevel
constraint.
o Primarykeyconstraint:
o Primaryenforcesthecolumntobeunique,notnullandnotempty
Columnlevelconstraint:
Eg:createtablestudent
(
prnvarchar(10)CONSTRAINTprn_pkprimarykey,
namechar(30),
mobileint(10)
);
SymbiosisInstituteofComputerstudiesandResearch
Page6
DatabaseManagementSystems
Tablelevelconstraint:
Eg:createtablestudent
(
prnvarchar(10),
namechar(30),
mobileint(10),
prnCONSTRAINTprn_pkprimarykey
);
Eg:createtablestudent
(
prnvarchar(10),
namechar(30),
mobileint(10),
(prn,name)CONSTRAINTprn_pkprimarykey
);
Theconstraintname(ex:prn_pk)helpstomanipulatetheconstraintslike
Disableconstraint
Modifyconstraint
Dropconstraint
Everytableshouldhaveoneprimarykey.
Theprimarykeycanbeonsinglecolumnoronmultiplecolumn(Max32
columns).
Foreverydatabasedefaultindexisgeneratedontheprimarykey.
Uniquekeyconstraint:
Shouldbeunique.
Itallowsnullvaluesandspaces.
Itallowsmultiplenullvaluessinceeverynullisconsideredasadifferentvalue.
Nullcanbespecifiedby'null'keywordor''.
Spaceisconsideredasanemptystringandallowsonce.
SymbiosisInstituteofComputerstudiesandResearch
Page7
DatabaseManagementSystems
Eg:createtablestudent
(prnvarchar(10)CONSTRAINTprn_pkprimarykey,
namechar(30),
mobileint(10)CONSTRAINTmob_colunique
);
Tablelevelconstraint:
Eg:createtablestudent
(
prnvarchar(10),
namechar(30),
mobileint(10),
prnCONSTRAINTprn_pkprimarykey,
mobileCONSTRAINTmob_ukunique
);
NotNULL:
Cannotbeimposedattablelevel
Itspecifiestheattributeorcolumnshouldhaveavaluealways.
Columnlevel:
Eg:createtablestudent
(
prnvarchar(10)CONSTRAINTprn_pkprimarykey,
namechar(30)notnull,
mobileint(10)CONSTRAINTmob_colunique
);
SymbiosisInstituteofComputerstudiesandResearch
Page8
DatabaseManagementSystems
Referentialkeyconstraint:
Itshouldbeaprimarykeyinothertable.
Eg:createtableemp
(
empnovarchar(10)CONSTRAINTemp_pkprimarykey,
namechar(30),
basic_salfloat(11,2)notnull,
deptnoint(5)REFERENCESdeptno(dept)CONSTRAINTdept_fk
)
Dept:parenttable
Empisconsideredaschildtable
Parenttablehastobegeneratedwiththeprimarykeyfirstonlythenitallows
usingkeyasforeignkey.
Wecandeleterecordsfromchildtablei.e.employeetablebutdeletionfromdept
tablewillbestopped.
Toovercomethis
o Ondeletecascade:Itallowsdeletefromtheparenttableanddeletesall
thereferences(completerecords)fromchildtable.
ex:createtableemp
(
empnovarchar(10)CONSTRAINTemp_pkprimarykey,
namechar(30),
basic_salfloat(11,2)notnull,
deptnoint(5)REFERENCESdeptno(dept)CONSTRAINTdept_fkondeletecascade
)
o Ondeletesetnull:Itallowsdeletefromtheparenttableandset
referencingvaluetonullinchildtable.
SymbiosisInstituteofComputerstudiesandResearch
Page9
DatabaseManagementSystems
ex:createtableemp
(
empnovarchar(10)CONSTRAINTemp_pkprimarykey,
namechar(30),
basic_salfloat(11,2)notnull,
deptnoint(5)REFERENCESdeptno(dept)CONSTRAINTdept_fkondeletesetnull
)
o Onupdatecascade:Allchildtablegetsreflectedwhenthereisanychange
inparenttablevalues.
Checkconstraint:
Arebusinessconstraints,theyhelpintheapplicationdevelopment
ex:createtableemp
(
empnovarchar(10)CONSTRAINTemp_pkprimarykeycheck(empno='E'),
namechar(30)check(name=upper(name)),
basic_salfloat(11,2)notnullcheck(basic_sal>500),
deptnoint(5)REFERENCESdeptno(dept)CONSTRAINTdept_fkondeletecascade,
citychar(20)check(cityIN('PUNE','MUMBAI'))
)
Defaultconstraint:
Itensuresthatifuserleavestheattributeemptythenitinsertsthedefaultvalue.
eg:createtableemp
(empnovarchar(10)CONSTRAINTemp_pkprimarykeydefaultE100,
namechar(30)check(name=upper(name)),
basic_salfloat(11,2)notnulldefault1000
)
SymbiosisInstituteofComputerstudiesandResearch
Page10
DatabaseManagementSystems
Note:Fewdatabasesuse'.'operatorinsteadof()
DatabaseModels:
Thedataarestoredindifferentforms:
1.ManualFilesystem.
2.HierarchicalDatabaseModel.
***AlldatabasesarestoredintheformofLinkedLists.
IndexesarestoredintheformofBinaryTrees.
Itistheforemostmodel.Datapossessatreestructurewhichhadlevelsof
linkagesintheformofRootnodeanditsLeafnodes.Therecordsaretermedas
setofrecord"types".Dataaccesswasthroughthekeyattributesanditwasvery
difficulttoaccessthroughotherattributes.
PrimarykeywastermedasKeyattribute.
Thetreestructurewasinflexibleandrigid.Itmeansoncethetreestructureis
established,itwasdifficulttodefinenewlinkagesorleafnode.Itdoesnotallow
defininglinkageslaterallyordiagonallyinthetreebutonlyvertically.
Nonewleafnodescanbeaddedoranynodecannotberemoved.
HierarchicalModel:
Asetofrecord"types".
Asetoflinksconnectingallrecordtypesinonedatastructurediagram(Tree).
Atmostonelinkbetweentworecordtypes,hencelinksneednotbenamed.
Foreveryrecord,thereisonlyoneparentrecordatthenextlevelupinthetree.
eg:Everycountryhasexactlyonestate.
Noconnectionsbetweenoccurrencesofsamerecordtype.
CANNOTgobetweenrecordsatthesamelevelunlesstheysharethesame
parent.
DatamustpossessaTreestructure.
Dataaccessiseasyviathekeyattribute,butdifficultforotherattributes.
Treestructureisinflexible.
CANNOTdefinenewlinkagesbetweenrecordsoncethetreeisestablished.
SymbiosisInstituteofComputerstudiesandResearch
Page11
DatabaseManagementSystems
Networkmodelsystem.
Objectiveofnetworkmodelistoseparatedatastructurefromphysicalstorage,
eliminateunnecessaryduplicationofdatawithassociatederrors&costs.
Usesconceptofadatadefinitionlanguage,anddatamanipulationlanguage.
Usesconceptofm:nlinkagesorrelationships.(manytomany)
Anownerrecordcanhavemanymemberrecords.
Amemberrecordcanhaveseveralowners.
NetworkDBMSincludemethodsforbuildingandredefininglinkages.
Linksbetweenrecordsofsametypearenotallowed.
Whilearecordcanbeownedbyseveralrecordsofdifferenttypes,itcannotbe
ownedbymorethanonerecordofsametype(APatientcanhaveonlyone
Doctor,onlyoneward.)
ANetworkmodelhasgreaterflexibilitythanHierarchicalmodelforhandling
complexspatialrelationships.
AdvantagesandDisadvantagesofdifferentdatamodels:
1.Hierarchicalmodel:
Advantages(comparedtoflatfiles)
Fasterdataretrieval.
Dataintegrityeasiertomanage.
Drawbacks:
Usersmustknowandunderstanddatastructure.
Redundantdatamayberequiredtoworkaroundthe"oneparent"restriction.
2.NetworkDatamodel:
SimilartoHierarchicalexceptthatchildrecordtypesmayhavemultipleparent
recordtypes.
Relationships(called"sets")arenamed.
Dataaccessinvolves"walkingthesets".
Advantages:
Fastdataaccess
Canstartaccesswithanyrecordtype.
Modelsmorecomplexdatastructures.
Easiertodevelopcomplexqueries.
SymbiosisInstituteofComputerstudiesandResearch
Page12
DatabaseManagementSystems
Drawbacks:
Datastructuredifficulttomodify.
Changestodatastructureoftenaffecttheapplications.
Usermustunderstandcomplexdatastructure.
CODD'sRULESforRDBMS:
TheyareconsideredasBibleforRDBMS.
1.InformationAccessRule:
Alldatashouldbepresentedtotheenduserinatablestructurei.e.Rowcolumn
structure.
2.GuaranteedaccessRule:
Alldatashouldbeaccessiblewithoutambiguity(conclusion).Thiscanbe
achievedthroughthecombinationoftablename,columnnameandthePrimary
key.
3.SystematictreatmentofNULLvalues:
Afieldshouldbeallowedtoremainempty.ThisinvolvesthesupportofNULL
valuewhichisdistinctfromanemptystringoranumberwithavalueof0.
"PRIMARYKEYSandNotNullconstraintsCANNOTBENULL".
4.DynamicOnlinecatalogue:
Itisbasedontherelationalmodel.Itprovidesaccesstothestructure(database
table).
Itstoresalldetailsrelatedtothestructurelikeupdatingdate,owner,memory
areawherethestructure(databasetable)isbeingstored.
ItisstoredintheformoftablesknownasSystemtables.
ItisalsoknownasMetadatadataaboutdata.
5.ComprehensiveDataSublanguage:
Thedatabasemustsupportatleastoneclearlydefinedlanguagethatincludes
thefunctionalityordatadefinition,datamanipulation,dataintegrityanddataase
transactioncontrol.
AllcommercialdatabasesusedifferentformofstandardSQL.(StructuredQuery
Language)astheirsupportcomprehensivelanguage.
SymbiosisInstituteofComputerstudiesandResearch
Page13
DatabaseManagementSystems
ex:Access,SQLServer2005,Sybase,Oracle.
OpenSource:DB2,Postgress,MYSQL,Ingress.
**ThesedatabaselanguagessupportSQL(StructuredQueryLanguage).
SQLhassomesublanguages:
DDL(DataDefinitionLanguage)
DML(DataManiplulationLanguage)
DCL(DataControlLanguage)
TCL(TransactionControlLanguage)
6.ViewupdatingRule:
Viewisthemirrorimage/snapshotofthebasetable.Itdoesnotoccupyany
spaceinthememory.
Viewcanbepresentedtotheendusersindifferentlogicalcombinationsfroma
tableormultiplebasetables.
Thisrulestatesthatinsert,updateordeleteoperationsshouldbesupportedfor
aretrievablesetsofrowsandnotforasinglerow.
Itenhancesthefasteraccessofthedatafromthebasetableasitworksforthat
sessiononly.
7.HighLevelinsert,updateanddelete:
Datacanberetrievedfromarelationaldatabaseingroupsorsetsofconstructed
multiplerows,singletableormanybasetables.
Thisrulestatesthattheinsert,updateanddeleteoperationsneednotsupport
patchcoding.Theseareonlysinglelinecommands.
8.Physicaldataindependence:
Theenduserisisolatedfromthephysicalmethodofstoringandretrievingdata
fromthedatabase.
Changescanbemadetothearchitecturei.e.,hardware,diskstoragemethod,
topology,protocolswithouttheenduserknowingit.
SymbiosisInstituteofComputerstudiesandResearch
Page14
DatabaseManagementSystems
View
Logical
Physical
HardwareLayer/NetworkLayer
Thephysicallayerremainsseparatedfromthedataaswellastheenduser.The
userdoesnotknowthedetailsofanyphysicalarchitectureandthenetwork
architecture.Theuserarenotaffectedhowthemachinesareconnectedandhow
thedataisretrieved.
9.LogicalDataIndependence:
Howtheuserviewsthedatashouldnotchangeevenifthelogicalstructurei.e.
thetablestructurechanges.
Ideallythisisdifficulttoachievesincetheapplicationformsdependdirectly
uponthedatabasetable.
Butthelogicaldataindependenceisnotideallypossible.Becauseifthelogical
structureofthedatabasegetschanged,itaffectsthefrontendapplicationalso.It
affectsthewaydataisretrieved,updatedorthewayreportsaregenerated.
10.Integrityindependence:
ThedatabaselanguageSQLshouldsupportconstraintsontheuserinputthat
helpstomaintainthedatabaseintegrity.
Mostvendorsimplementatleast2minimumconstraints.
o Primarykeyconstraint:Columnshouldbenotnull,uniqueandnotempty.
o Foreignkeyconstraint:shouldbetheprimarykeyoftheothertableto
whichitrefersto.
11.DistributionIndependence:
Endusershouldbetotallyunawareofwhetherornotadatabaseisdistributed
i.e.adatabaseexistsindifferentlocationinpartsoriscompletelylocatedinone
physicallocation.
Thisruleisdifficulttoimplementsincetransactionmanagementrequiresmore
timetobringthedatabaseinaconsistentshape.
SymbiosisInstituteofComputerstudiesandResearch
Page15
DatabaseManagementSystems
12.NonsubversionRule:Thereshouldbenowaytomodifythetablestructureother
thanSQL.
SQL:Structuredquerylanguage.
1.DDL:DataDefinitionLanguage[relatedtotablestructureonly]
Create:creatingthestructureofthetable
Alter:alteringthetablestructure[size,column,datatype]
Rename:changethenameofthetable
Drop:deletestheentiretableandreleasethememoryallocated
Thesecommandsareautocommitinnature.
2.DML:DataManipulationLanguage[dealsonlywithtablevalues]
Select
Insert
Update
Delete
userhastospecifytheautocommit
3.DCL:DataControlLanguage
Commit:makingthechangespermanenttothedatabase.
Rollback:undoorcanceltillthelasttablestate[consistentor
committed]
4.TCL:TransactionControlLanguage
Grant:Tograntpermissiontoanenduser
Revoke:Tochange/takebackthepermissions
Syntax:
SELECT
select<fieldlist>from<tablename>
where<condition>
groupby<fieldlist>
having<condition>
orderby<fieldlist>ASC/DSC
SymbiosisInstituteofComputerstudiesandResearch
Page16
DatabaseManagementSystems
Queryfunctions
Characterfunctions:
upper()
lower()
initcap()
Aggregatefunctions[youhavetousehavingorgroupbyclausewiththese
functions]
Avg()
min()
max()
count()
sum()
stddev()
variable()
Numericfunctions
abs()
sin()
least()
ceil()
floor()
Datefunctions
currentDate()currentdate
Now()currenttime
Generalfunctions
if()
ifp()
SymbiosisInstituteofComputerstudiesandResearch
Page17
DatabaseManagementSystems
nullif()
decode()
nvl()
nvl2()
RelationalOperator:
>>=
<<=
!=
=
LogicalOperator:
AND
OR
NOT
Functions
Characterfunctions:
1.upper/ucaseconvertsthegivenstringorthecolumntouppercase
ex:selectupper(name)fromstudent;
selectupper('sicsr');
2.lower/lcaseconvertsthegivenstringorthecolumntolowercase
ex:selectlower(name)fromstudent;
selectlower('SICSR');
3.instrgivesthepositionofthefirstoccurenceofsubstring
syntax:instr(<string>,<substring>)
ex:selectinstr('SICSR','C')=>3
selectinstr('SICSRSICSR','SR')=>4
SymbiosisInstituteofComputerstudiesandResearch
Page18
DatabaseManagementSystems
4.substringreturnssubstringfromagivenargument.
syntax:substring(<string>,<startingposition>,<length>)
ex:selectsubstring('SICSR',3)=>CSR
selectsubstring('SICSR',1,3)=>SIC
5.lengthreturnslengthofthestring
syntax:length(<string>)
ex:selectlength('SICSR')=>5
selectlength(name)fromstudent
6.replaceThisfunctionreplacesalloccurrencesof<fromstring>with<to
string>ingiven<string>.
syntax:replace(<string>,<fromstring>,<tostring>)
ex:replace('WELCOMETOSICSR','CSR','BM')=>WELCOMETOSIBM
7.repeatthisfunctionrepeatsthegivenstringforspecifiednumberoftimes
syntax:repeat(<string>,<nooftimes>)
ex:repeat('SICSR',3)=>SICSRSICSRSICSR
8.strcmpcomparestwostringsstr1andstr2and
Returns0ifthereareexactlysame.
Returns1iftheyarenotsameandstr1isgreaterinlengththanstr2.
Returns1iftheyarenotsameandstr2isgreaterin
lengththanstr1.
syntax:strcmp('<string1>','<string2>')
ex:strcmp('SICSR','sicsr')=>0
strcmp('SICSR','SIBM')=>1
strcmp('SIBM','SICSR')=>1
9.reversereversesthegivenstring
syntax:reverse('<string>')
ex:reverse('SICSR')=>RSCIS
SymbiosisInstituteofComputerstudiesandResearch
Page19
DatabaseManagementSystems
10.trim/ltrim/rtrim
syntax:trim('<string>')
ex:trim('SICSR')=>'SICSR'
ltrim('SICSR')=>'SICSR'
rtrim('SICSR')=>'SICSR'
11.left/right/mid
syntax:left(<string>,<length>)
right(<string>,<length>)
mid(<string>,<from>,<to>)
ex:left('SICSR',2)=>SI
right('SICSR',2)=>SR
mid('SICSR',2)=>ICSR
mid('SICSR',2,2)=>IC
12.rpad/lpad
syntax:rpad(<string>,<length>,<symbol>)
ex:rpad('SICSR',10,'*')=>SICSR*****
lpad('SICSR',10,'*')=>*****SICSR
13.locate/position
syntax:locate(<substring>,<string>)
ex:locate('C','SICSR')=>3
14.concat
syntax:concat('<string1>','<string2>')
ex:concat('WELCOMETO','SICSR')=>WELCOMETOSICSR
SymbiosisInstituteofComputerstudiesandResearch
Page20
DatabaseManagementSystems
Numericfunctions:
1.abs
ex:abs(4)=>4
2.ceil
ex:ceil(2.2)=>3
3.floor
ex:floor(2.7)=>2
4.sqrt
ex:sqrt(4)=>2
5.pow/power
ex:pow(4,2)=>16
6.round
ex:round(2.56743,2)=>2.57
7.truncate
ex:truncate(2.56743,2)=>2.56
Aggregatefunctions
ThegroupbyandhavingclauseintheselectstatementCANBEUSEDonlywith
aggregatefunctions.
Aggregatefunctionsalwaysworkonagroup.
Theyignorenullvalues.
1.count
ex:count(*)givesthecountofrowsinatable
count(<expression>)givesthecountofrowsforthat
particularcolumninthetable.
count(distinct(<expression>))givesthecountofdistinctrowsforthat
particularcolumninthetable.
SymbiosisInstituteofComputerstudiesandResearch
Page21
DatabaseManagementSystems
2.min
ex:min(date)returnsthemininumdate
min(fees)returnsminimumfees
min(name)returnsminimumasciivaluestring.
3.max
ex:max(date)returnsthemaximumdate
max(fees)returnsmaximumfees
max(name)returnsmaximumasciivaluestring.
4.avg
syntax:avg(<column>)returnstheaverageofthespecifiedfield.
avg(fees)returnstheaverageoffeescolumn.
avg(name)returns0.
5.sum
ex:sum(fees)returnsthesumofthefeescolumn
sum(date)returnthesumofdatecolumn
sum(name)returns0.
Controlflowfunctions
1) Case: SyntaxCASE<value>when[<comparevalue>]THEN<result>when
[<comparevalue>]THEN<result>else[<result>]end
Ex:CASE1when1thenone
when2thentwo
elsemoreEND
2) IF
Syntax:IF(<expr1>,<expr2>,<expr3>)
Ex:selectif(1>2,2,3)3
Ifexpr1istruethenexpr2willbetheresultelseexpr3willbethe
result
SymbiosisInstituteofComputerstudiesandResearch
Page22
DatabaseManagementSystems
3) IFNULL
Syntax:Ifnull(expr1,expr2)
Ex:ifnull(null,10)10
Ifexpr1isnotnullthenexpr1willbereturnedelseexpr2willbe
returned
4) NULLIF
Syntax:NULLIF(expr1,expr2)
Ex:selectNULLIF(1,1,)NULL
selectNULLIF(1,0)1
Ifexpr1==expr2thennullwillbereturnedelse1willbereturned
DateFunctions
1) CURDATEreturnsthecurrentdate
Ex:selectcurdate();2008091
2) Extractextractsapartofthedate
Ex:selectextract(yearfrom20080901)2008
3) Date_add:addtwodates
Ex:selectdate_add(2000123123:59:59,interval1second)
2001010100:00:00
4) Date_sub:subtract2dates
Ex:selectdate_sub(2005010100:00:00,interval1:1daysecond)
2004123022:58:59
5) Month():returnsmonthfromthedatepassed:
Ex:selectmonth(20080901)09
Transactionmanagement:
Itisdefinedascollectionofmanyreadandwrites.
Itisalsodefinedasaunitofprograminstructionthataccesses
andupdatesvariousdatavalues.
Itisalsodefinedasasetofstatementsbetweentwocommitsor
tworollbacks.
Read(select)andwrite(insert,update,delete)
Atransactionmustalwaysseeaconsistentdatabase.
Ifthetransactionisabortedthenthedatabasemustberestoredto
itspriorconsistentstate.
SymbiosisInstituteofComputerstudiesandResearch
Page23
DatabaseManagementSystems
Duringtransactionexecutionthedatabasemaybeinan
INCONSISTENTstatebutafterthetransactionitscommitted,it
shouldalwaysendwithaconsistentstate.
Lifecycleoftransaction(statetransitiondiagram):
1.Active(start)itistheinitialstatewhichthetransactionstayswhilebeingprocessed.
2.PartiallycompletedorpartiallycommittedAftertheinitialstateatransaction
proceedstoitsnormalexecution.
3.CompletedorcommittedAfterthetransactionendsinanormalwayitis
completedorcommitted.Thisisalsotermedasasuccessfultransaction.
4.FailedstateAftertheinitialstateatransactioncouldendinafailedstate,eitherby
systemerrororfewlogicalerrorsandcannotcompleteitsnormalexecution.
5.Aborted(cancelled)Afailedtransactionisnormallyabortedandaborted
transactionhastwooptions:
Itiskilled.
Rollbackandrestartedfromthefirst(initial)step.
Propertiesofatransaction:
EverytransactionideallyshouldfollowtheACIDpropertiestoensureintegrityof
thedatabase.
A(Atomicity):Eitheralloperationofthetransactionareproperlyreflectedinthe
databaseornoneare.
C(Consistency):Executionofatransactionmustbepreservethe
consistencyofthedatabase.
o Consistencystatesthatpriortoatransactionthedatabaseisina
consistentstateandafterthetransactioncompletethesamestablestate
shouldbeachieved.
I(Isolation)Althoughmultipletransactionmayexecuteconcurrentlyeach
transactionmustbeunawareoftheotherconcurrentlyexecutingtransaction.
o Theintermediateresultsmustbehiddenfromtherestofthetransaction
toensureconsistency.
D(durability)Afteratransactioncompletessuccessfullythechangesithas
madetothedatabasemustpersisteveniftherearemajororminorfailures.
o Ex:fundtransfertransaction.
SymbiosisInstituteofComputerstudiesandResearch
Page24
DatabaseManagementSystems
PriortotransactionT1AAccount2000,BAccount4000
T1
Begin
1.ReadA;
2.A=A1000;
3.WriteA;
4.ReadB;
5.B=B+1000;
6.WriteB;
End
commit
Atomicity:
EitherallstepsofT1areexecutedornoneare.
Incaseoffailureafterstep3thedatabaseendsinaninconsistentstateasA=>
1000andB=>4000,Sinceexpectedoutputwas
A=>1000B=>5000.
Atomicityensuresrollbacki.e.noneofthehalfcompletedstepsareexecuted.
Trackthefailureatstep6andpostcommit.
Consistency:
PriortothetransactionA=>2000andB=>4000total=>6000
PostT1expectedoutputA=>1000B=>5000andTotal=>6000
Iftheexpectedoutputisnotachievedthenthetransactionisaninconsistent
state.
ACIDprotocolsaysrollback.
Isolation:
Ifothertransaction(T2,T3,....,Tn)aretrackingthesamedatabasevaluesofA's
accountandB'saccount,theyshouldnotbeawareofT1'supdate.
SymbiosisInstituteofComputerstudiesandResearch
Page25
DatabaseManagementSystems
Durability:
Inanykindoffailurethevaluesofthedatabaseshouldnotbelost.
Incaseoffailuresthesystemshouldbeabletotracebackbybackupand
recoverymechanism.
Schedule:
Ascheduleisasetoftransactionwhichconsistsofmanyinstructionswithasaid
order.
Itisalsodefinedasacollectionofmanytransactions.
Scheduleisclassifiedintoserialandnonserialschedule.
Serialschedule:onetransactioniscompletedandthenothertransactiontaken
upconsecutively.
Nonserialschedule:onetransactionisinterleavedwiththerestoftransaction
intheschedule.
Concurrency:
When transactions are interleaved with one another during execution the
processistermedasconcurrencyandthetransactionistermedasconcurrent
transaction.
Concurrencyincreasesoptimaluseofresourcesandthroughputofthesystem
andultimatelytheefficiencyofthesystem.
SerialSchedule[x=90,y=90,n=2,m=3]
ScheduleA
ScheduleB
T1
Readitem(x);(90)
x=xn;(88)
Writeitem(x);(88)
Readitem(y);(90)
y=y+n;(92)
Writeitem(y);
(92)
T2
Readitem(x);(90)
x=x+m;(93)
Writeitem(x);(93)
T1
Readitem(x);(93)
T2
Readitem(x);(88)
x=x+m;(91)
Writeitem(x);
(91)
x=xn;(91)
Writeitem(x);
(91)
Readitem(y);(90)
y=y+n(92)
Writeitem(y);
(92)
X=91andy=92
X=91andy=92
SymbiosisInstituteofComputerstudiesandResearch
Page26
DatabaseManagementSystems
NonSerialSchedule[x=90,y=90,n=2,m=3]
ScheduleC
T1
Readitem(x);(90)
x=xn;(88)
T2
Readitem(x);(90)
x=x+m;(93)
Writeitem(x);
(93)
Readitem(y);
(90)
y=y+n;(92)
Writeitem(y);
(92)
X=93andY=92
ScheduleD
T2
T1
Readitem(x);(90)
x=xn;(88)
Writeitem(x);
(88)
x=x+m;(91)
Writeitem(x);
(93)
Writeitem(x);
(91)
Readitem(y)(90)
y=y+n;(92)
Writeitem(y);
(92)
Readitem(x);(88)
X=91andy=92
Serializability:
TheoutputsofScheduleAandBareequalandaccurate.
Bothwereserialschedules.
TheoutputofScheduleCandDvary.
TheoutputofscheduleDisequivalentScheduleAandB.HencescheduleDis
valid.
Realtimetherecouldbemanypermutationsavailableforthenonserial
schedules,eachoutputdifferingfromtheearlier,leadingthedatabaseintoan
inconsistentandunstablestate.
Hencethatpermutationofthenonserialscheduleshouldbeexecutedwhichis
equivalenttotheserialschedule.
ThisistermedasSerializability.
Objectiveofserializibilityistofindthatnonserialschedulewhichallowsthe
transactiontoexecuteconcurrentlywithoutinterferingwitheachotherandto
produceadatabasestatewhichissimilartotheonegeneratedbytheserial
schedule.
SymbiosisInstituteofComputerstudiesandResearch
Page27
DatabaseManagementSystems
Propertiesofserializibility:
Everytransactionpreservesdatabaseconsistency.
Serialschedulepreservesdatabaseconsistency.
Henceconcurrentscheduleareserializableifequivalenttoserialschedule.
Differentformsofschedulinggiverisetoconflictserializibilityandview
serializibility.
Potentionalproblemisinconcurrentnonserialtransaction:
Lostupdateproblem/updateanomaly:
Time
T1
T2
t1
BeginT2
t2
BeginT1
Readbal(x)
t3
Readbal(x)
Balx=balx+100
t4
Balx=balx10
Writebal(x)
t5
Writebal(x)
commit
t6
commit
Uncommitteddependency/dirtyread:
Balx
100
100
100
200
90
90
Time
t1
t2
t3
t4
t5
t6
t7
t8
Balx
100
100
100
200
200
100
190
190
T3
BeginT3
Readbal(x)
Balx=balx10
Writebal(x)
commit
T4
BeginT4
Readbal(x)
Balx=balx+100
Writebal(x)
Rollback
SymbiosisInstituteofComputerstudiesandResearch
Page28
DatabaseManagementSystems
InconsistentAnalysis:
Time
t1
t2
t3
t4
t5
t6
t7
t8
t9
t10
t11
t12
T1
BeginT1
readbal(x)
balx=balx10
write(balx)
read(balz)
balz=balz+10
write(balz)
commit
T2
beginT2
sum=0
read(balz)
sum=sum+balx
read(baly)
sum=sum+(baly)
readbal(z)
sum=sum+bal(z)
commit
bal(x)
100
100
100
100
90
90
90
bal(y)
50
50
50
50
50
50
50
50
50
35
185
bal(z)
25
25
25
25
25
25
25
35
Sum
0
0
0
100
150
150
Sumisaprocessedvalue.
Itisnotadatabaseentry.
Thevalueiscalculatingtheadditionofx,y,z
PriortothetransactionT1andT2x100,y50,z25
Hencesumshouldhavebeen175.
PosttransactionT1andT2,x90,y50,z35.
Eveninthiscasethesumshouldhavebeen175.
Buttrackingtheprocessingsumendsinaninconsistentstatewithvalueof185.
Typesofserializibility
1) Conflictserializibility:
a. ConsidertransactionT1andT2processingonsomedatabasevalues.The
conflictoccursonlyifthesamedatabasevaluesisaccessedbyboththe
transactionsatthesametimestampsandatleastoneoftheinstancein
eitherofthetransactionsisarightinstance.
Noconflict
Conflict
Conflict
Conflict
T1
ReadQ
WriteQ
ReadQ
WriteQ
T2
ReadQ
ReadQ
WriteQ
WriteQ
Theconflictenforcesatemporalorderbetweentheinstructions.IfTG1andT2
areconsecutiveintheschedule,theywouldnotconflictandresultswould
remainequivalenteveniftheywereinterchanged.
SymbiosisInstituteofComputerstudiesandResearch
Page29
DatabaseManagementSystems
Henceifaschedulewithconflictinginstructionsistransformedtoitsequivalent
nonserialschedulethenitistermedasconflictequivalenttransactionorconflict
serializable
2) Viewserializibility
a. ConsiderschedulesAandBwiththesamesetoftransactionsonthesame
setofdatabasevalues.
Viewserializibilitystatesthatthefollowingconditionsshouldbemet.
IfscheduleAreadsinitialvaluesofQ(databasevalueQ)then
scheduleBshouldalsoreadinitialvalueofQ.
ForeverydatabasevalueQ,ifscheduleAexecutesreadwhichwas
anupdatedvaluebyanintermediatetransactionTn,thenschedule
BshouldalsoreadthatvaluewasprocessedbytransactionTn.
ForeachdatabasevalueQifscheduleAperformsfinalwritevalue
thenawriteshouldalsobeprocessedbyB.
Everyconflictserializablescheduleisaviewserializableschedule
butreverseisnevertrue.
RecoverableSchedules:AscheduleforeachpairoftransactionsT1andT2.IfT1reads
adatabasevaluewrittenbyT2thencommitofT2precedesthecommitofT1
Concurrencymanagementandconcurrencytechniques:
Concurrencytechniquescanbeachievedintwomethods.
i.
ii.
Pessimistic/conservativeapproach
a. Thisapproachcausesthetransactiontobedelayed.Incaseofaconflict
withtheothertransactionandthedelayedtransactionareexecutedatthe
sametimestampinthefuture.
b. Itcanbeachievedbylocking,timestampingandmultiversiontime
stampingmethods.
OptimisticApproach
a. Thisapproachisbasedontheassumptionthatconflictsarerare.They
alsoallowtransactiontoproceedunsynchronizedandcheckforthe
conflictsonlyattheendofthetransaction.
Locking
Itistheprocedureusedtocontrolconcurrentaccesstothedatabasevalues.
When1transactionisaccessingadatabasevaluealockmaydenyaccesstoother
concurrenttransactionsinordertopreventincorrectresults
Typesoflocking
o Shared/Readlock
Ifthetransactiondemandsasharedlockondatabasevaluesitcan
readdatabasevaluesbutcannotupdateordelete.
SymbiosisInstituteofComputerstudiesandResearch
Page30
DatabaseManagementSystems
o Exclusive/Writelock
Whenatransactionhasanexclusivelockonthedatabasevaluesit
canread,update,deletedatabasevalues.
Conditionforlocking:
Alockisgeneratedonlyifadatabasevalueisnotalreadylockedbyanother
transaction
Sharedlockscanbeheldsimultaneouslyon1databasevaluebymany
transactions.
Ifatransactionholdsanexclusivelockondatabasevaluenoothertransaction
canread/updatethatvalue.
Ifadatabasevalueiscurrentlylocked,thetransactionmanagerdeterminesifthe
newrequestoflockiscompatiblewiththeexistingone.i.e.ifasharedlockis
requestedonadatabasevaluewhichisalreadyexistingwithasharedlock,the
requestisgenerated.Otherwisethetransactionwaitstilltheexistinglockis
released.
Atransactioncontinuestoholdalockuntilitexplicitlyreleasesiteitherduring
executionorwhenitterminatesbycommitorabort.Note:TheupdatedValueis
visibletootherusersonlyafterthelockisreleased.
TwoPhaselocking:
Toguaranteeserializibilitytwophaselockingisthebestprotocolusedinreal
time.
Atransactionfollowsa2PLprotocolifallthelockingoperationsprecedesthe
firstunlockoperationinthetransaction
A2PLfollowsacycleof2phases
o Phase1(Growthphase)
Thetransactionmayobtainnewlocksbutmaynotreleasethe
locks.
o Phase2(Shrinkphase)
Thetransactionmayreleasethenewlockbutcannotobtainnew
lock.
Thereisnorequirementthatalllocksbeobtainedsimultaneously.
Generallyatransactionacquires2locks,doessomeprocessingandgoesonto
acquireadditionallocksasandwhenrequired.
Thetransactionsneverreleaseanylocksuntilitreachesastagewherenolocks
arerequired.
2PLspecificprotocols.
o Atransactionmustacquirealockonthedatabasevaluebeforeprocessing
thatvalue.
o Thelockmaybeofread/writebasedonthetypeofaccessrequired.
SymbiosisInstituteofComputerstudiesandResearch
Page31
DatabaseManagementSystems
o Onceatransactionreleasesalock,itcanneveracquireanynewlocks.
Strict2PL.
o Thisprotocolstatesthatthelockingshouldbein2phasesandallthe
exclusivelocksheldbythetransactionsshouldbekeptlockeduntilthe
transactioncommends.
o Thisprotocolensuresthatanydatawrittenbyanuncommitted
transactionislockedinanexclusivemodepreventingothertransactionto
readtheupdates.
o Ithelpsinavoidingcascadingrollbacks.
Rigorous2PL.
o Itstatesthatalllocksareheldtilltheentiretransactioncompletes.
TimeStamps:
Witheverytransactionaunique,fixed,timestampisassociatedbeforethe
transactionbeginsexecution.
ThetimestampsoftransactiondeterminetheSerializabilityorder.
Everydatabasevalueisassociatedwith2timestamps.
o Thereadtimestamp:Thelargesttimestampofanytransactionthat
executedthereadsuccessfully.
o TheWritetimestamp:denoteslargertimestampsofanytransactionthat
executedthewritesuccessfully.
IfT1andT2aretransactionswhichbeginexecution,theirtimestampsaretsand
tqrespectively.TheniftransactionT1istriggeredbeforetransactionT2,the
systemtracksthetransactionasT1(ts)older>T2(tq)newer.
RecoverySystem:
1)Transactionfailures*:Thereare2typesoferrorsthatmaycauseatransactionto
fail.
Logical:thetransactiondoesnotcontinuenormalexecutioncozoffewproblemslike
badinputoutput,datanotfound,overflowetc.
Systemerrors:Thesystementersaundesirablestatelikedeadlocksduetowhich
thetransactionscannotcontinuetheirnormalexecution.
SymbiosisInstituteofComputerstudiesandResearch
Page32
DatabaseManagementSystems
Logbasedrecoverysystem:
1)Log:
Itisacollectionofrecordsstoringalltheupdatesinthedatabase.
Itisusedinrecoveringdatabasemoduleswhichwillhelpincaseofafailureto
recoverthelostdata.
Thelogisfilestoredonthesecondarymemory
Everydatabasegenerallyhasmorethan1logfile.
Anupdatelogrecorddescribesasingledatabasewritewhichhasthefollowing
fields.
o Transactionidentifieritisauniqueidentifierofthetransactionthat
performstherightoperation
o Dataitemidentifieritisauniqueidentifierofthedatabasevalue
whichiswrittenorupdated.Typicallyitisthelocationonthedata
returnonthedisk
o Oldvaluevalueofthedataitempriortothewrite.
o Newvaluevalueofthedataitemafterthewrite.
Differenttypesoflogbasedrecoverytechniques:
1)DeferredLBT:
Itensuresatransactionatomicitybyrecordingalldatabasemodificationinthelog.
Itdefferstheexecutionofallthewriteoperationofatransactionuntilthe
transactionpartiallycommits
Whenatransactionpartiallycommitstheinfoofthelogassociatedwiththe
transactionisusedinexecutingthedefferedwrite.
Ifthesystemcrashesbeforethetransactioncompletesorifthetransactionaborts
thentheinfoonthelogisignored.
Recoveryproceduretrackingwithatransaction:
t1
t2
read(a);
read(c);
a=a50;
writea;
writec;
c=c100;
readb;
b=b+50;
writeb;
SymbiosisInstituteofComputerstudiesandResearch
Page33
DatabaseManagementSystems
*Priortot1,t2
a=1000;
b=2000;
c=700;
logrecords:
<t1start>
<t1,a,950>
<t1,b,2050>
<commit>
<t2start>
<t2,c,600>
<commit>
Assumingthatthecrashoccursjustafterthelogrecord:
Writeboft1whichhasbeenreturnedtothetablestorage
Thelogatthetimeofcrashappearsas<t1start><t1,a,950><t1,b,2050>
Whenthesystemcomesbackandresumesnoredoactionsneedtobetaken.
Sincenocommitappearsintheloghencethevalueofaandbremainas1000and
2000respectively.
Thelogrecordsofincompletetransactionlikeoft1canbedeletedfromthelog
Assumingthecrashcomesjustafterthecrashrecordforthestepwritecoft2:
Thelogatthetimeofcrashreads<t1start><t1,a,950><t1,b,2050><t1,commit><t2
start><t1,c,600>
Aftertheexecutiona=950,b=20250,c=700.
Thisissobecauset2doesnotreadacommitasbeforetheincompletetransactions
canbedeletedfromthelog
SymbiosisInstituteofComputerstudiesandResearch
Page34
DatabaseManagementSystems
Assumingthecrashoccursjustafterthelogrecordt2commit:
Whenthesystemcomesback2commitrecordsareinthelogonefort1andanother
fort2.
Hencethesystemmustperformoperationredot1andt2intheorderinwhichthey
appearinthelogaspertheircommitsequences
Therecordsappearasa=950,b=2050,c=600inthedatabase.
*Sincethetransactionaredoneonceinttheviewandsecondtimeagainonthe
databasebypullingthetransactionfromthelogitisalsotermedasredolog
mechanism.
*Theredooperationmustbeidempotenti.e.executingitmanytimesmustbe
equivalenttoexecutingitonce.
2)ImmediateLBT:
Theimmediatelogsallowdatabasemodificationstobedoneonthedatabasewhile
thetransactionisstillinanactivestate.
Thedatabasemodificationswrittenbytheactivetransactionsarealluncommitted
modifications.
AssumingthecrashoccursafterwriteBoft1.
Whenthesystemcomesbackandresumesitfindtherecord<T1start>inthelog
butnocorresponding<T1commit>.
Hencethetransactionisundone.
Thevaluesofaandbarerestoredbackto1000and2000.
Assumingthecrashoccursafterwritecoft2.
Whenthesystemresumes2recoveryactionsaretaken
o undot2sincecommitisnotthereonlystartt2isfound
o redot1sincebothstartandcommitoft1areencounteredinthelog
Assumingthecrashoccursaftert2commit:
Whenthesystemresumespostfailurebotht1andT2areredonesincecommitsof
botht1andt2areencounteredinthelog
Hencea=950,b=2050,c=600.
SymbiosisInstituteofComputerstudiesandResearch
Page35
DatabaseManagementSystems
Checkpoints:
Whenasystemfailureoccursthedatabasealwaysconsultsthelogto
determinethestatusofthetransactions.
Fromthestatusitdecideswhetherthetransactionsneedtoberedoneor
undone
Forthisthedatabasehastosearchtheentirelog.
2majordifficultieswiththisarethesearchistimeconsumingandmostofthe
transactionsaccordingtothealgorithmthatneedtoberedonehavealready
writtentheirupdatesintothedatabase
Althoughtheredoingdoesntcauseanyharmitcausestherecoverytotake
longertime.
Toovercomethesedifficultiescheckpointareused.
Thepresenceofacheckpointrecordinthelogallowsthesystemto
streamlineitsrecoveryprocedure
Consideratransactiont1thatcommitspriortocheckpointforthis
transaction<t1commit>appearsinthelogbeforethecheckpointentry.
Anymodificationmadebyt1hasbeenwrittenbeforethecheckpoint,hence
thereisnoneedtoperform<redot1>afterthesystemresumesincaseof
failures.
Afterafailureoccurstherecoverymechanismreadsthelogtodeterminethe
mostrecenttransactionsthatstartedexecutingbeforethemostrecent
checkpointtookplace.
Itfindssuchtransactionsbysearchingthelogbackwardsfromendoffileof
log.
Itsearchestillitfindsthefirstcheckpointrecordthenitcontinuesthesearch
backwardstillitfindsa<tistart>.Thisrecordidentifiesthebeginningofa
transaction.
Shadowpaging:
Thedatabaseispartitionedintonooffixedlengthblockswhicharetermedas
pages.
Thesepagesneednotbestoredinaparticularorderonthediskforfinding
thenthpageofthedatabaseforanygiventransactionapagetableis
generated.
Thepagetablehasmanyentries,oneentryapproxforeachdatabasepage.
Eachentrycontainsapointertoapageonthedisk
o Eg:firstentrycontainsapointertothefirstpageofthedatabase.
Thekeyideabehindshadowpagingistomaintain2pagetablesduringthe
lifeofatransaction.thecurrentpagetableandtheshadowpagetable
Whenatransactionstartsboththepagetablesareidentical
SymbiosisInstituteofComputerstudiesandResearch
Page36
DatabaseManagementSystems
Theshadowpagetableisneverchangedoverthedurationofthetransaction
Thecurrentpagetableischangewheneveratransactionperformsawrite
operation
Theshadowpagehelpsinrecovery.Itisstoredonanonvolatilestorageso
whenafailureoccursthedatabasestatepriortotheexecutionofthe
transactioncanberecoveredfromtheshadowtableintheeventoffailure.
Whenthetransactioncommitsthesystemwritesthecurrentpagetableto
thenonvolatilestorage.
Thecurrentpagetablecanthenactasanewshadowpagetableandthenlet
thenexttransactionstobeginexecution.
LogSwitch:
Thedatabasecompilerrecordsallthetransactionsinalogfile.
Thelogfilehasaspecificsize
Thelogfileisstoredonthesecondarymemory
Therearemultiplecopiesofthelogfilegeneratedandstoredacrossthedisc.
Theyaretermedastheloggroups
Whenthesizeof1logfilegetscompletelyfilledthedatabasecompilerswitches
itscontroltothenextlogfileandcontinuesrecordingthetransaction.
Thislogswitchhelpsthedatabaseintwoways
o Thetransactionsarerecordedconsistentlywithoutbreak
o Abackupcanbegeneratedonanysecondarydevicefromthefirstfilled
log.ThebackupgenerationprocessistermedastheARCHIVERprocess.
Alltheseprocessesarebackgroundprocesses.
Deadlocks:
Theyaredefinedasasituationwhereeverytransactioniswaitingforanother
concurrenttransactiontoreleasetheirlocksonthedatabasevalues.
Thistriggersabreakinthetransactionsandthesystemcouldhangupandcrash.
Methodsforhandlingdeadlocks:
1. Ignorethedeadlock,letthesystempretendthatnodeadlockoccursandthe
situationisleftunhandled.
2. Ensurethatasystemneverentersadeadlockstate.
3. Allowasystemtoenteradeadlockandthenrecoverfromit.
SymbiosisInstituteofComputerstudiesandResearch
Page37
DatabaseManagementSystems
Preventivemeasures:
Itstatesthatpreventioncanbeexecutedby2approaches
o Itensuresthatnocyclicwaitscanoccurbyorderingtherequestforlogs
orensuringthatallthelocksareacquiredtogether.
o Thesecondapproachistoperformatransactionrollbackinsteadof
waitingforalog
Thefirstapproachrequiresthateachtransactionlocksallits
databasevaluesbeforeitbeginsexecution.Eitherallvaluesare
lockedin1stepornonearelockedatall
Disadvantageitisdifficulttopredictwhichdatabasevaluewould
belockedbyatransactionbeforeitbeginsexecution.
Thedatabasevalueutilizationmaybeverylowastheywillbe
lockedbutunusedforalongtime
Theotherapproachforpreventingdeadlockstatesthatan
orderingofalldatabasevaluesisdoneandallthetransactions
shouldlockthedatabasevaluesonlyinsequencewhichis
consistentintheorder
Preemptiontechnique
WhenatransactionT1requiresalockwhichT2holds,thelockgrantedtoT1
maybepreemptedbyrollingbackofT2
Tocontrolpreemptionauniquefixedtimestampisallocatedtoeach
transaction.Thesystemusesthesetimestampstodecideifatransactionshould
waitorrollback.
Deadlockdetectionandrecovery
Analgorithmthatexaminesthestateofsystemregularlyneedstobeinvokedto
checkifadeadlockoccurs.Ifadeadlockoccursthesystemmustrecoverfromit.
Themostcommonmethodistorollback1ormoretransactionstobreakthe
deadlock.
Itinvolves3steps.
o Selectionofvictimgivenasetofdeadlocktransactionsthesystem
determineswhichtransactiontorollbackandbreakthedeadlock.
Generallythetransactionthatwillincurminimumcostisrolledback.
o RollbackOnceitisdecidedwhichtransactionistoberolledbackthe
systemmustthendeterminehowfarthattransactionmustberolled
backeithertotalorpartial.
o StarvationInasystemwheretheselectionofavictimisbasedoncost
factoritmayhappenthatthesametransactionisalwayspickedupasa
victim.Asaresultthistransactionnevercompletesitslifecycle.Hence
SymbiosisInstituteofComputerstudiesandResearch
Page38
DatabaseManagementSystems
thesystemmustensurethatatransactionispickedasavictimonlyfora
finitenooftimes.
Causesofdeadlock:
1. Mutualexclusiononly1transactioncanlockadatabasevalueatagiven
time
2. Holdandwaitatransactionwhichhaslockedadatabasevalueadis
waitingtoacquireadditionaldatabasevaluewhicharebeingheldby
otherconcurrenttransaction
3. Nopreemptionadatabasevaluecanbereleasedvoluntarilybya
transactionholdingitafterithascompleteditsprocessingorincaseit
getsaborted.
CircularwaitthereexistsasetoftransactionsT1,T2,T3suchthatT1iswaitingfora
databasevaluewhichislockedbyT2,T2iswaitingforadatabasevaluewhichislocked
byT3andT3inturniswaitingforadatabasevaluelockedbyT1.
NORMALISATION
Sampleexamples>
{patid,name,DofAdmittance,Docid,Docname,BillNo,BillAmt}
Patient
Doctor
Bill
{ISBN,authorid,name,price,TotalPages,publicationid,publicationName,
authprAddress,PublicationAddress}
Book
Author
Publication
{prn,FName,LName,MobNo,LAddress,Courseid,Fee,CourseName,CourseHead,
Pattern}
Student
Course
SymbiosisInstituteofComputerstudiesandResearch
Page39
DatabaseManagementSystems
{memberNo,MemberName,MemberAddr,IssueDate,ReturnDate,BookNo,BookName,
FineAmt}
Book
Member
Transaction
{supplierId,supplierName,ItemId,ItemName,Cost,SupplierAddr,SupplierPhone}
Supplier
Product
Normalisation
Normalisationisaprocesstoeliminateredundantdataandensuredata
dependency
Itreducestheamountofspaceadatabaseconsumeandensuresthatthedatais
logicallystore
1NF:
eliminateduplicatecolumnsfromtable
createseparatetablesforeachgroupofrelateddataandidentifyeachrowwith
auniquecolumnorsetofcolumnswhicharetheprimarykeys
2NF:
Shouldmeettherequirementof1NF
Removessubsetsofdatasi.e.removeduplicaterowsandplacethemin
separatetables.
CreateassociationbetweenthenewtablesusingtheprotocolsofERD
3NF:
Meettherequirementsof2NF
Removecolumnsthatarenotdependentontheprimarykey[transitive
dependency]
Example:
Allnonkeyattributeshoulddependsonprimarykey
Ifnotthenremovethatattributeandputitintonewtable
o ex:{empNo,empName,salary,deptNo,deptName}
SymbiosisInstituteofComputerstudiesandResearch
Page40
DatabaseManagementSystems
InthisexampleempName,salaryanddeptNoattributeiscompletelydependson
primarykeyempNo
ButdeptNameisdependsondeptNowhichinterndependsonprimarykey
empNo
ThereforecreatetwotableemployeeandDepartment
Employee{empNo,empName,salary,deptNo}
Department{deptNo,deptName}
4NF:
Meettherequirementof3NF
Removemultivaluedattributesandplacetheminaseparatetable
Associatingitwiththeparenttable
Ex:allmultivaluedattributeshouldberemovedfrom1sttableandcreatenewtable
withthatmultivalueattributeasprimarykey
{empNo,empName,phone}
Phoneattributecanhavemultiplevaluetherefore
Createtwotablesemployeeandphone
Employee{empNo,empName}
Phone{phone,empNo}
5NF:
Removetheoccurrenceofspuriousjoinswhichleadsthedatainanincorrectstate
SymbiosisInstituteofComputerstudiesandResearch
Page41
DatabaseManagementSystems
IllustrationofNormalization
Title
Php
Author1 Author2
L.Welling LamaThomson
ISBN
0637
Subject
php
Pages
867
Publication
TMH
0948
MySQL
900
SAMS
1NFillustration
Title
Php
MySQL
Php
Author1
L.Welling
L.Welling
LamaThomson
ISBN
0637
0948
0637
Subject
php
MySQL
php
Pages
867
900
867
Publication
TMH
SAMS
TMH
MySQL LamaThomson
0948
MySQL
900
SAMS
2NFillustration
Book
ISBN
Title
Pages
Publisher
Pub_id
Name
Author
Author_id Name
Book_Author
ISBN
Author_ID
Book_Publisher
ISBN
Pub_id
SymbiosisInstituteofComputerstudiesandResearch
Page42