Introduction to Database Systems - halvorsen.blog · 2 Database Systems Tutorial: Introduction to...

42
https://www.halvorsen.blog https://www.halvorsen.blog/documents/technology/database/ Introduction to Database Systems Hans-Petter Halvorsen

Transcript of Introduction to Database Systems - halvorsen.blog · 2 Database Systems Tutorial: Introduction to...

https://www.halvorsen.blog

https://www.halvorsen.blog/documents/technology/database/

IntroductiontoDatabaseSystems

Hans-PetterHalvorsen

IntroductiontoDatabaseSystems

Hans-PetterHalvorsen

Copyright©2017

E-Mail:[email protected]

Web:https://www.halvorsen.blog

https://www.halvorsen.blog

PrefaceThisdocumentexplainsthebasicconceptsofadatabasesystemandhowtocommunicatewithadatabasesystem.

ThemainfocusinthisdocumentisonrelationaldatabasesandMicrosoftSQLServer.

FormoreinformationaboutDatabases,visitmyBlog:

https://www.halvorsen.blog

Sometextinthisdocumentisbasedontextfromwww.wikipedia.org.

iv

TableofContentsPreface......................................................................................................................................3

TableofContents.....................................................................................................................iv

1 DatabaseSystems...............................................................................................................1

1.1 RDBMSComponents....................................................................................................1

1.2 Datawarehouse...........................................................................................................2

1.3 RelationalDatabase......................................................................................................2

1.4 Real-timedatabases.....................................................................................................2

1.5 NoSQLDatabases..........................................................................................................3

1.6 DatabaseManagementSystems..................................................................................3

1.7 MDAC............................................................................................................................4

1.7.1 ODBC......................................................................................................................4

1.7.2 OLEDB...................................................................................................................4

1.7.3 ADO(ActiveXDataObjects)...................................................................................4

2 RelationalDatabases...........................................................................................................5

2.1 Tables...........................................................................................................................5

2.2 UniqueKeysandPrimaryKey.......................................................................................6

2.3 ForeignKey...................................................................................................................7

2.4 Views............................................................................................................................8

2.5 Functions......................................................................................................................8

2.6 StoredProcedures........................................................................................................9

2.7 Triggers.........................................................................................................................9

3 StructuredQueryLanguage(SQL).....................................................................................10

v TableofContents

Tutorial: Introduction to Database Systems

3.1 Queries.......................................................................................................................10

3.2 DataManipulation......................................................................................................11

3.3 DataDefinition...........................................................................................................12

3.4 DataTypes..................................................................................................................13

3.4.1 CharacterStrings..................................................................................................13

3.4.2 BitStrings.............................................................................................................13

3.4.3 Numbers..............................................................................................................13

3.4.4 DateandTime......................................................................................................13

4 DatabaseModelling..........................................................................................................14

4.1 ERDiagram.................................................................................................................14

4.2 MicrosoftVisio............................................................................................................15

4.3 ERwin..........................................................................................................................17

5 MicrosoftSQLServer.........................................................................................................19

5.1 Introduction................................................................................................................19

5.2 SQLServerExpress.....................................................................................................19

5.3 SQLServerManagementStudio.................................................................................20

5.4 CreateaNewDatabase..............................................................................................20

5.5 Backup/Restore..........................................................................................................22

6 MicrosoftOfficeAccess.....................................................................................................24

6.1 Introduction................................................................................................................24

6.2 ExampleDatabase......................................................................................................24

7 CreatingandUsingTables.................................................................................................27

8 CreatingandUsingViews..................................................................................................30

9 CreatingandusingStoredProcedures..............................................................................31

10 CreatingandUsingTriggers............................................................................................33

11 CreatingandUsingFunctions..........................................................................................35

vi TableofContents

Tutorial: Introduction to Database Systems

1

1 DatabaseSystemsAdatabaseisanintegratedcollectionoflogicallyrelatedrecordsorfilesconsolidatedintoacommonpoolthatprovidesdataforoneormoremultipleuses.

Onewayofclassifyingdatabasesinvolvesthetypeofcontent,forexample:bibliographic,full-text,numeric,andimage.Otherclassificationmethodsstartfromexaminingdatabasemodelsordatabasearchitectures.

Thedatainadatabaseisorganizedaccordingtoadatabasemodel.Therelationalmodelisthemostcommon.

ADatabaseManagementSystem(DBMS)consistsofsoftwarethatorganizesthestorageofdata.ADBMScontrolsthecreation,maintenance,anduseofthedatabasestoragestructuresoforganizationsandoftheirendusers.Itallowsorganizationstoplacecontroloforganization-widedatabasedevelopmentinthehandsofDatabaseAdministrators(DBAs)andotherspecialists.Inlargesystems,aDBMSallowsusersandothersoftwaretostoreandretrievedatainastructuredway.

Databasemanagementsystemsareusuallycategorizedaccordingtothedatabasemodelthattheysupport,suchasthenetwork,relationalorobjectmodel.Themodeltendstodeterminethequerylanguagesthatareavailabletoaccessthedatabase.OnecommonlyusedquerylanguagefortherelationaldatabaseisSQL,althoughSQLsyntaxandfunctioncanvaryfromoneDBMStoanother.AgreatdealoftheinternalengineeringofaDBMSisindependentofthedatamodel,andisconcernedwithmanagingfactorssuchasperformance,concurrency,integrity,andrecoveryfromhardwarefailures.Intheseareastherearelargedifferencesbetweenproducts.

1.1 RDBMSComponentsARelationalDatabaseManagementSystem(DBMS)consistsofthefollowingcomponents:

• Interfacedrivers-Auserorapplicationprograminitiateseitherschemamodificationorcontentmodification.ThesedriversarebuiltontopofSQL.Theyprovidemethodstopreparestatements,executestatements,fetchresults,etc.AnimportantexampleistheODBCdriver.

2 DatabaseSystems

Tutorial: Introduction to Database Systems

• SQLengine-ThiscomponentinterpretsandexecutestheSQLquery.Itcomprisesthreemajorcomponents(compiler,optimizer,andexecutionengine).

• Transactionengine-Transactionsaresequencesofoperationsthatreadorwritedatabaseelements,whicharegroupedtogether.

• Relationalengine-RelationalobjectssuchasTable,Index,andReferentialintegrityconstraintsareimplementedinthiscomponent.

• Storageengine-Thiscomponentstoresandretrievesdatarecords.Italsoprovidesamechanismtostoremetadataandcontrolinformationsuchasundologs,redologs,locktables,etc.

1.2 DatawarehouseAdatawarehousestoresdatafromcurrentandpreviousyears—dataextractedfromthevariousoperationaldatabasesofanorganization.Itbecomesthecentralsourceofdatathathasbeenscreened,edited,standardizedandintegratedsothatitcanbeusedbymanagersandotherend-userprofessionalsthroughoutanorganization.

1.3 RelationalDatabaseArelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.

Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegroupedbytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthetransaction;oritcanbegroupedbythebuyer'slastname;andsoon.

Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,suchadatabaseiscalleda"relationaldatabase."

Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.Theterm"relationaldatabase"oftenreferstothistypeofsoftware.

Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,manufacturingandlogisticalinformation,personneldataandmuchmore.

Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).

1.4 Real-timedatabases

3 DatabaseSystems

Tutorial: Introduction to Database Systems

Areal-timedatabaseisaprocessingsystemdesignedtohandleworkloadswhosestatemaychangeconstantly.Thisdiffersfromtraditionaldatabasescontainingpersistentdata,mostlyunaffectedbytime.Forexample,astockmarketchangesrapidlyanddynamically.Real-timeprocessingmeansthatatransactionisprocessedfastenoughfortheresulttocomebackandbeactedonrightaway.Real-timedatabasesareusefulforaccounting,banking,law,medicalrecords,multi-media,processcontrol,reservationsystems,andscientificdataanalysis.Ascomputersincreaseinpowerandcanstoremoredata,real-timedatabasesbecomeintegratedintosocietyandareemployedinmanyapplications

1.5 NoSQLDatabasesThenextgenerationofdatabasesystemsisknownasNoSQLdatabasesanddocument-orienteddatabases.NoSQLdatabasesareoftenveryfast,donotrequirefixedtableschemas.

ExamplesofNoSQLsystems:MongoDBandOracleNoSQLDatabase.

1.6 DatabaseManagementSystemsThereareDatabaseManagementSystems(DBMS),suchas:

• MicrosoftSQLServer• Oracle• Sybase• dBase• MicrosoftAccess• MySQLfromSunMicrosystems(Oracle)• DB2fromIBM• etc.

ThisdocumentwillfocusonMicrosoftAccessandMicrosoftSQLServer.

4 DatabaseSystems

Tutorial: Introduction to Database Systems

1.7 MDACTheMicrosoftDataAccessComponents(MDAC)istheframeworkthatmakesitpossibletoconnectandcommunicatewiththedatabase.MDACincludesthefollowingcomponents:

• ODBC(OpenDatabaseConnectivity)• OLEDB• ADO(ActiveXDataObjects)

MDACalsoinstallsseveraldataprovidersyoucanusetoopenaconnectiontoaspecificdatasource,suchasanMSAccessdatabase.

1.7.1 ODBC

OpenDatabaseConnectivity(ODBC)isanativeinterfacethatisaccessedthroughaprogramminglanguagethatcanmakecallsintoanativelibrary.InMDACthisinterfaceisdefinedasaDLL.Aseparatemoduleordriverisneededforeachdatabasethatmustbeaccessed.

1.7.2 OLEDB

OLEallowsMDACapplicationsaccesstodifferenttypesofdatastoresinauniformmanner.Microsofthasusedthistechnologytoseparatetheapplicationfromthedatastorethatitneedstoaccess.Thiswasdonebecausedifferentapplicationsneedaccesstodifferenttypesandsourcesofdata,anddonotnecessarilyneedtoknowhowtoaccesstechnology-specificfunctionality.Thetechnologyisconceptuallydividedintoconsumersandproviders.Theconsumersaretheapplicationsthatneedaccesstothedata,andtheprovideristhesoftwarecomponentthatexposesanOLEDBinterfacethroughtheuseoftheComponentObjectModel(orCOM).

1.7.3 ADO(ActiveXDataObjects)

ActiveXDataObjects(ADO)isahighlevelprogramminginterfacetoOLEDB.Itusesahierarchicalobjectmodeltoallowapplicationstoprogrammaticallycreate,retrieve,updateanddeletedatafromsourcessupportedbyOLEDB.ADOconsistsofaseriesofhierarchicalCOM-basedobjectsandcollections,anobjectthatactsasacontainerofmanyotherobjects.AprogrammercandirectlyaccessADOobjectstomanipulatedata,orcansendanSQLquerytothedatabaseviaseveralADOmechanisms.

5

2 RelationalDatabasesArelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.

Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegroupedbytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthetransaction;oritcanbegroupedbythebuyer'slastname;andsoon.

Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,suchadatabaseiscalleda"relationaldatabase."

Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.Theterm"relationaldatabase"oftenreferstothistypeofsoftware.

Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,manufacturingandlogisticalinformation,personneldataandmuchmore.

2.1 TablesThebasicunitsinadatabasearetablesandtherelationshipbetweenthem.Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).

BelowweseehowarelationshipbetweentwotablesaredefinedusingPrimaryKeysandForeignKeys.

6 RelationalDatabases

Tutorial: Introduction to Database Systems

2.2 UniqueKeysandPrimaryKeyInrelationaldatabasedesign,auniquekeyorprimarykeyisacandidatekeytouniquelyidentifyeachrowinatable.Auniquekeyorprimarykeycomprisesasinglecolumnorsetofcolumns.Notwodistinctrowsinatablecanhavethesamevalue(orcombinationofvalues)inthosecolumns.Dependingonitsdesign,atablemayhavearbitrarilymanyuniquekeysbutatmostoneprimarykey.

Auniquekeymustuniquelyidentifyallpossiblerowsthatexistinatableandnotonlythecurrentlyexistingrows.ExamplesofuniquekeysareSocialSecuritynumbersorISBNs.

Aprimarykeyisaspecialcaseofuniquekeys.ThemajordifferenceisthatforuniquekeystheimplicitNOTNULLconstraintisnotautomaticallyenforced,whileforprimarykeysitisenforced.Thus,thevaluesinuniquekeycolumnsmayormaynotbeNULL.Anotherdifferenceisthatprimarykeysmustbedefinedusinganothersyntax.

Primarykeysaredefinedwiththefollowingsyntax:

CREATE TABLE table_name ( id_col INT, col2 CHARACTER VARYING(20), ... CONSTRAINT tab_pk PRIMARY KEY(id_col), ... )

Iftheprimarykeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusingthefollowingsyntax:

CREATE TABLE table_name ( id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... )

Thedefinitionofuniquekeysissyntacticallyverysimilartoprimarykeys.

Likewise,uniquekeyscanbedefinedaspartoftheCREATETABLESQLstatement.

CREATE TABLE table_name ( id_col INT, col2 CHARACTER VARYING(20), key_col SMALLINT, ... CONSTRAINT key_unique UNIQUE(key_col), ... )

Oriftheuniquekeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusingthefollowingsyntax:

CREATE TABLE table_name (

7 RelationalDatabases

Tutorial: Introduction to Database Systems

id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... key_col SMALLINT UNIQUE, ... )

2.3 ForeignKeyInthecontextofrelationaldatabases,aforeignkeyisareferentialconstraintbetweentwotables.Theforeignkeyidentifiesacolumnorasetofcolumnsinonetablethatreferstoacolumnorsetofcolumnsinanothertable.Thecolumnsinthereferencingtablemustbetheprimarykeyorothercandidatekeyinthereferencedtable.Thevaluesinonerowofthereferencingcolumnsmustoccurinasinglerowinthereferencedtable.Thus,arowinthereferencingtablecannotcontainvaluesthatdon'texistinthereferencedtable.Thiswayreferencescanbemadetolinkinformationtogetheranditisanessentialpartofdatabasenormalization.Multiplerowsinthereferencingtablemayrefertothesamerowinthereferencedtable.Mostofthetime,itreflectstheone(mastertable,orreferencedtable)tomany(childtable,orreferencingtable)relationship.

Thereferencingandreferencedtablemaybethesametable,i.e.theforeignkeyrefersbacktothesametable.Suchaforeignkeyisknownasself-referencingorrecursiveforeignkey.

Atablemayhavemultipleforeignkeys,andeachforeignkeycanhaveadifferentreferencedtable.Eachforeignkeyisenforcedindependentlybythedatabasesystem.Therefore,cascadingrelationshipsbetweentablescanbeestablishedusingforeignkeys.

Improperforeignkey/primarykeyrelationshipsornotenforcingthoserelationshipsareoftenthesourceofmanydatabaseanddatamodelingproblems.

ForeignkeyscanbedefinedaspartoftheCREATETABLESQLstatement.

CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20), col3 INTEGER, ... CONSTRAINT col3_fk FOREIGN KEY(col3) REFERENCES other_table(key_col), ... )

Iftheforeignkeyisasinglecolumnonly,thecolumncanbemarkedassuchusingthefollowingsyntax:

CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20), col3 INTEGER REFERENCES other_table(column_name),

8 RelationalDatabases

Tutorial: Introduction to Database Systems

... )

2.4 ViewsIndatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposedoftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnotformpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfromdatainthedatabase.Changingthedatainatablealtersthedatashowninsubsequentinvocationsoftheview.

Viewscanprovideadvantagesovertables:

• Viewscanrepresentasubsetofthedatacontainedinatable • Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable • Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata

(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata • Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000

orSales2001,transparentlypartitioningtheactualunderlyingtable • Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa

view,notacopyofallthedataitpresents • Viewscanlimitthedegreeofexposureofatableortablestotheouterworld

Syntax:

CREATE VIEW <ViewName> AS …

2.5 FunctionsInSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthefunctionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQLstatements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalarfunctionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.

User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.

Syntax:

CREATE FUNCTION <FunctionName> (@Parameter1 <datatype>, @ Parameter2 <datatype>, …)

9 RelationalDatabases

Tutorial: Introduction to Database Systems

RETURNS <datatype> AS …

2.6 StoredProceduresAstoredprocedureisexecutablecodethatisassociatedwith,andgenerallystoredin,thedatabase.Storedproceduresusuallycollectandcustomizecommonoperations,likeinsertingatupleintoarelation,gatheringstatisticalinformationaboutusagepatterns,orencapsulatingcomplexbusinesslogicandcalculations.Frequentlytheyareusedasanapplicationprogramminginterface(API)forsecurityorsimplicity.

Storedproceduresarenotpartoftherelationaldatabasemodel,butallcommercialimplementationsincludethem.

Storedproceduresarecalledorusedwiththefollowingsyntax:

CALL procedure(…)

or

EXECUTE procedure(…)

Storedprocedurescanreturnresultsets,i.e.theresultsofaSELECTstatement.Suchresultsetscanbeprocessedusingcursorsbyotherstoredproceduresbyassociatingaresultsetlocator,orbyapplications.Storedproceduresmayalsocontaindeclaredvariablesforprocessingdataandcursorsthatallowittoloopthroughmultiplerowsinatable.ThestandardStructuredQueryLanguageprovidesIF,WHILE,LOOP,REPEAT,CASEstatements,andmore.Storedprocedurescanreceivevariables,returnresultsormodifyvariablesandreturnthem,dependingonhowandwherethevariableisdeclared.

2.7 TriggersAdatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingtheintegrityoftheinformationonthedatabase.Forexample,whenanewrecord(representinganewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhetablesofthetaxes,vacations,andsalaries.

Thesyntaxisasfollows:

CREATE TRIGGER <TriggerName> ON <TableName> FOR INSERT, UPDATE, DELETE AS …

10

3 StructuredQueryLanguage(SQL)

SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanagingdatainrelationaldatabasemanagementsystems(RDBMS).

ThisdocumentgivesonlyaverybriefoverviewofSQL,formorein-depthoverviewofSQL.Pleaserefertothetutorial“StructuredQueryLanguage”locatedonmywebsite:

https://www.halvorsen.blog

3.1 QueriesThemostcommonoperationinSQListhequery,whichisperformedwiththedeclarativeSELECTstatement.SELECTretrievesdatafromoneormoretables,orexpressions.StandardSELECTstatementshavenopersistenteffectsonthedatabase.

Queriesallowtheusertodescribedesireddata,leavingthedatabasemanagementsystem(DBMS)responsibleforplanning,optimizing,andperformingthephysicaloperationsnecessarytoproducethatresultasitchooses.

AqueryincludesalistofcolumnstobeincludedinthefinalresultimmediatelyfollowingtheSELECTkeyword.Anasterisk("*")canalsobeusedtospecifythatthequeryshouldreturnallcolumnsofthequeriedtables.SELECTisthemostcomplexstatementinSQL,withoptionalkeywordsandclausesthatinclude:

• TheFROMclausewhichindicatesthetable(s)fromwhichdataistoberetrieved.TheFROMclausecanincludeoptionalJOINsubclausestospecifytherulesforjoiningtables.

• TheWHEREclauseincludesacomparisonpredicate,whichrestrictstherowsreturnedbythequery.TheWHEREclauseeliminatesallrowsfromtheresultsetforwhichthecomparisonpredicatedoesnotevaluatetoTrue.

• TheGROUPBYclauseisusedtoprojectrowshavingcommonvaluesintoasmallersetofrows.GROUPBYisoftenusedinconjunctionwithSQLaggregationfunctionsor

11 StructuredQueryLanguage(SQL)

Tutorial: Introduction to Database Systems

toeliminateduplicaterowsfromaresultset.TheWHEREclauseisappliedbeforetheGROUPBYclause.

• TheHAVINGclauseincludesapredicateusedtofilterrowsresultingfromtheGROUPBYclause.BecauseitactsontheresultsoftheGROUPBYclause,aggregationfunctionscanbeusedintheHAVINGclausepredicate.

• TheORDERBYclauseidentifieswhichcolumnsareusedtosorttheresultingdata,andinwhichdirectiontheyshouldbesorted(optionsareascendingordescending).WithoutanORDERBYclause,theorderofrowsreturnedbyanSQLqueryisundefined.

Example:

ThefollowingisanexampleofaSELECTquerythatreturnsalistofexpensivebooks.ThequeryretrievesallrowsfromtheBooktableinwhichthepricecolumncontainsavaluegreaterthan100.00.Theresultissortedinascendingorderbytitle.Theasterisk(*)intheselectlistindicatesthatallcolumnsoftheBooktableshouldbeincludedintheresultset.

SELECT * FROM Book WHERE price > 100.00 ORDER BY title;

Theexamplebelowdemonstratesaqueryofmultipletables,grouping,andaggregation,byreturningalistofbooksandthenumberofauthorsassociatedwitheachbook.

SELECT Book.title,count(*) AS Authors FROM Book JOIN Book_author ON Book.isbn = Book_author.isbn GROUP BY Book.title

[EndofExample]

3.2 DataManipulationTheDataManipulationLanguage(DML)isthesubsetofSQLusedtoadd,updateanddeletedata.

TheacronymCRUDreferstoallofthemajorfunctionsthatneedtobeimplementedinarelationaldatabaseapplicationtoconsideritcomplete.EachletterintheacronymcanbemappedtoastandardSQLstatement:

Operation SQL

Create INSERT

12 StructuredQueryLanguage(SQL)

Tutorial: Introduction to Database Systems

Read(Retrieve) SELECT

Update UPDATE

Delete(Destroy) DELETE

Example:

INSERT:

INSERTaddsrowstoanexistingtable,e.g.,:

INSERT INTO My_table field1, field2, field3) VALUES ('test', 'N', NULL)

UPDATE:

UPDATEmodifiesasetofexistingtablerows,e.g.,:

UPDATE My_table SET field1 = 'updated value' WHERE field2 = 'N'

DELETE:

DELETEremovesexistingrowsfromatable,e.g.,:

DELETE FROM My_table WHERE field2 = 'N'

[EndofExample]

3.3 DataDefinitionTheDataDefinitionLanguage(DDL)managestableandindexstructure.ThemostbasicitemsofDDLaretheCREATE,ALTER,RENAMEandDROPstatements:

• CREATEcreatesanobject(atable,forexample)inthedatabase. • DROPdeletesanobjectinthedatabase,usuallyirretrievably. • ALTERmodifiesthestructureanexistingobjectinvariousways—forexample,adding

acolumntoanexistingtable.

Example:

CREATE:

CreateaDatabaseTable:

CREATE TABLE My_table ( my_field1 INT,

13 StructuredQueryLanguage(SQL)

Tutorial: Introduction to Database Systems

my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1) )

[EndofExample]

3.4 DataTypesEachcolumninanSQLtabledeclaresthetype(s)thatcolumnmaycontain.ANSISQLincludesthefollowingdatatypes.

3.4.1 CharacterStrings

• CHARACTER(n)orCHAR(n)—fixed-widthn-characterstring,paddedwithspacesasneeded

• CHARACTERVARYING(n)orVARCHAR(n)—variable-widthstringwithamaximumsizeofncharacters

• NATIONALCHARACTER(n)orNCHAR(n)—fixedwidthstringsupportinganinternationalcharacterset

• NATIONALCHARACTERVARYING(n)orNVARCHAR(n)—variable-widthNCHARstring

3.4.2 BitStrings

• BIT(n)—anarrayofnbits • BITVARYING(n)—anarrayofuptonbits

3.4.3 Numbers

• INTEGERandSMALLINT • FLOAT,REALandDOUBLEPRECISION • NUMERIC(precision,scale)orDECIMAL(precision,scale)

3.4.4 DateandTime

• DATE • TIME • TIMESTAMP • INTERVAL

14

4 DatabaseModelling

4.1 ERDiagramInsoftwareengineering,anEntity-RelationshipModel(ERM)isanabstractandconceptualrepresentationofdata.Entity-relationshipmodelingisadatabasemodelingmethod,usedtoproduceatypeofconceptualschemaorsemanticdatamodelofasystem,oftenarelationaldatabase,anditsrequirementsinatop-downfashion.

Diagramscreatedusingthisprocessarecalledentity-relationshipdiagrams,orERdiagramsorERDsforshort.

TherearemanyERdiagrammingtools.SomeoftheproprietaryERdiagrammingtoolsareERwin,EnterpriseArchitectandMicrosoftVisio.

MicrosoftSQLServerhasalsoabuilt-intoolforcreatingDatabaseDiagrams.

15 DatabaseModelling

Tutorial: Introduction to Database Systems

4.2 MicrosoftVisioMicrosoftVisioisadiagrammingprogramforcreatingdifferentkindsofdiagrams.VisiohaveatemplateforcreatingDatabaseModelDiagrams.

16 DatabaseModelling

Tutorial: Introduction to Database Systems

IntheDatabasemenuVisioofferslotsoffunctionalityregardingyourdatabasemodel.

“ReverseEngineering”istheoppositeprocedure,i.e.,extractionofadatabaseschemafromanexistingdatabaseintoadatabasemodelinMicrosoftVisio.

Example:DatabaseDiagram

CreatethefollowingtablesinanERDiagramusingMSVisio.

• CUSTOMERo CustomerId(PK)o FirstNameo LastNameo Addresso Phoneo PostCodeo PostAddress

• PRODUCTo ProductId(PK)o ProductNameo ProductDescriptiono Priceo ProductCode

• ORDERo OrderId(PK)o OrderNumbero OrderDescription

17 DatabaseModelling

Tutorial: Introduction to Database Systems

o CustomerId(FK)• ORDER_DETAIL

o OrderDetailId(PK)o OrderId(FK)o ProductId(FK)

TheDatabaseDiagrambecomes:

[EndofExample]

4.3 ERwinERwinisaprofessionaldatabasemodellingtool.ACommunityeditionisalsoavailableforfree.TheCommunityeditionislimitedtoworkwithmax25objects.

BelowweseeanexamplecreatedinErwin.

WithErwinandotherprofessionaldatabasemodellingtoolsyoucandirectlyimportthedatabasemodelintothedatabasesystemsuchasSQLServer,MySQL,etc.

18 DatabaseModelling

Tutorial: Introduction to Database Systems

19

5 MicrosoftSQLServer

5.1 IntroductionMicrosoftSQLServerisarelationalmodeldatabaseserverproducedbyMicrosoft.ItsprimaryquerylanguagesareT-SQLandANSISQL.

ThelatestversionisMicrosoftSQLServer2014.

MicrosoftSQLServerhomepage:www.microsoft.com/sqlserver

TheMicrosoftSQLServercomesindifferentversions,suchas:

• SQLServerDeveloperEdition• SQLServerEnterpriseEdition• SQLServerWebEdition• SQLServerExpressEdition• Etc.

TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.

5.2 SQLServerExpressTheSQLServerExpressEditionisafreely-downloadableand-distributableversion.

However,theExpresseditionhasanumberoftechnicalrestrictionswhichmakeitundesirableforlarge-scaledeployments,including:

• Maximumdatabasesizeof4GBper.The4GBlimitappliesperdatabase(logfilesexcluded);butinsomescenariosuserscanaccessmoredatathroughtheuseofmultipleinterconnecteddatabases.

• SinglephysicalCPU,multiplecores • 1GBofRAM(runsonanysizeRAMsystem,butusesonly1GB)

SQLServerExpressoffersaGUItoolsfordatabasemanagementinaseparatedownloadandinstallationpackage,calledSQLServerManagementStudioExpress.

20 MicrosoftSQLServer

Tutorial: Introduction to Database Systems

5.3 SQLServerManagementStudioSQLServerManagementStudioisaGUItoolincludedwithSQLServerforconfiguring,managing,andadministeringallcomponentswithinMicrosoftSQLServer.Thetoolincludesbothscripteditorsandgraphicaltoolsthatworkwithobjectsandfeaturesoftheserver.Asmentionedearlier,versionofSQLServerManagementStudioisalsoavailableforSQLServerExpressEdition,forwhichitisknownasSQLServerManagementStudioExpress.

AcentralfeatureofSQLServerManagementStudioistheObjectExplorer,whichallowstheusertobrowse,select,andactuponanyoftheobjectswithintheserver.Itcanbeusedtovisuallyobserveandanalyzequeryplansandoptimizethedatabaseperformance,amongothers.SQLServerManagementStudiocanalsobeusedtocreateanewdatabase,alteranyexistingdatabaseschemabyaddingormodifyingtablesandindexes,oranalyzeperformance.ItincludesthequerywindowswhichprovideaGUIbasedinterfacetowriteandexecutequeries.

5.4 CreateaNewDatabaseItisquitesimpletocreateanewdatabaseinMicrosoftSQLServer.Justright-clickonthe“Databases”nodeandselect“NewDatabase…”

21 MicrosoftSQLServer

Tutorial: Introduction to Database Systems

Therearelotsofsettingsyoumaysetregardingyourdatabase,buttheonlyinformationyoumustfillinisthenameofyourdatabase:

22 MicrosoftSQLServer

Tutorial: Introduction to Database Systems

5.5 Backup/RestoreDatabaseBackupandRestore:

23 MicrosoftSQLServer

Tutorial: Introduction to Database Systems

24

6 MicrosoftOfficeAccess

6.1 IntroductionMicrosoftOfficeAccess,previouslyknownasMicrosoftAccess,isarelationaldatabasemanagementsystemfromMicrosoftthatcombinestherelationalMicrosoftJetDatabaseEnginewithagraphicaluserinterfaceandsoftwaredevelopmenttools.ItisamemberoftheMicrosoftOfficesuiteofapplicationsandisincludedintheProfessionalandhigherversionsforWindows.AccessstoresdatainitsownformatbasedontheAccessJetDatabaseEngine.

MicrosoftAccessisusedbyprogrammersandnon-programmerstocreatetheirownsimpledatabasesolutions.

MicrosoftAccessisafileserver-baseddatabase.Unlikeclient-serverrelationaldatabasemanagementsystems(RDBMS),e.g.,MicrosoftSQLServer,MicrosoftAccessdoesnotimplementdatabasetriggers,storedprocedures,ortransactionlogging.Alldatabasetables,queries,forms,reports,macros,andmodulesarestoredintheAccessJetdatabaseasasinglefile.ThismakesMicrosoftAccessusefulinsmallapplications,teaching,etc.becauseitiseasytomovefromonecomputertoanother.

6.2 ExampleDatabaseIwillpresentanexampledatabaseinMicrosoftAccess2007whichwillbeusedinsomeoftheexamplesandexercisesinthisdocument.

Thedatabaseconsistsofthefollowingtables:

• CUSTOMERo CustomerId(PK)o FirstNameo LastNameo Addresso Phoneo PostCodeo PostAddress

• PRODUCT

25 MicrosoftOfficeAccess

Tutorial: Introduction to Database Systems

o ProductId(PK)o ProductNameo ProductDescriptiono Priceo ProductCode

• ORDERo OrderId(PK)o OrderNumbero OrderDescriptiono CustomerId(FK)

• ORDER_DETAILo OrderDetailId(PK)o OrderId(FK)o ProductId(FK)

ODBCConnection:

AdministrativeTools→DataSources(ODBC)

26 MicrosoftOfficeAccess

Tutorial: Introduction to Database Systems

27

7 CreatingandUsingTablesTheSQLsyntaxforcreatingaTableisasfollows:

CREATE TABLE <TableName> ( <ColumnName> <datatype> … )

TheSQLsyntaxforinsertingDataintoaTableisasfollows:

INSERT INTO <TableName> (<Column1>, <Column2>, …) VALUES(<Data for Column1>, <Data for Column2>, …)

Example:InsertDataintoTables

Wewillinsertsomedataintoourtables:

ThefollowingSQLQueryinsertssomeexampledataintothesetables:

--CUSTOMER INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Per', 'Nilsen', 'Vipeveien 12', '12345678', '1234', 'Porsgrunn') GO

28 CreatingandUsingTables

Tutorial: Introduction to Database Systems

INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Tor', 'Hansen', 'Vipeveien 15', '77775678', '4455', 'Bergen') GO INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Arne', 'Nilsen', 'Vipeveien 17', '12345778', '4434', 'Porsgrunn') GO --PRODUCT INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product A', 'This is product A', 1000, 'A-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product B', 'This is product B', 1000, 'B-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product C', 'This is product C', 1000, 'C-1234') GO --ORDER INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10001', 'This is Order 10001', 1) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10002', 'This is Order 10002', 2) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10003', 'This is Order 10003', 3) GO --ORDER_DETAIL INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3) GO

ExecutingthefollowingQueriesthengives:

select * from CUSTOMER

select * from PRODUCT

29 CreatingandUsingTables

Tutorial: Introduction to Database Systems

select * from [ORDER]

select * from ORDER_DETAIL

[EndofExample]

30

8 CreatingandUsingViewsIndatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposedoftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnotformpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfromdatainthedatabase.Changingthedatainatablealtersthedatashowninsubsequentinvocationsoftheview.

Viewscanprovideadvantagesovertables:

• Viewscanrepresentasubsetofthedatacontainedinatable • Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable • Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata

(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata • Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000

orSales2001,transparentlypartitioningtheactualunderlyingtable • Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa

view,notacopyofallthedataitpresents • DependingontheSQLengineused,viewscanprovideextrasecurity • Viewscanlimitthedegreeofexposureofatableortablestotheouterworld

Justasfunctions(inprogramming)canprovideabstraction,sodatabaseuserscancreateabstractionbyusingviews.Inanotherparallelwithfunctions,databaseuserscanmanipulatenestedviews,thusoneviewcanaggregatedatafromotherviews.

Syntax:

CREATE VIEW <ViewName> AS …

31

9 CreatingandusingStoredProcedures

Astoredprocedureisasubroutineavailabletoapplicationsaccessingarelationaldatabasesystem.Typicalusesforstoredproceduresincludedatavalidation(integratedintothedatabase)oraccesscontrolmechanisms.Furthermore,storedproceduresareusedtoconsolidateandcentralizelogicthatwasoriginallyimplementedinapplications.LargeorcomplexprocessingthatmightrequiretheexecutionofseveralSQLstatementsismovedintostoredprocedures,andallapplicationscalltheproceduresonly.

AstoredprocedureisaprecompiledcollectionofSQLstatementsandoptionalcontrol-of-flowstatements,similartoamacro.Eachdatabaseanddataprovidersupportsstoredproceduresdifferently.Storedproceduresofferthefollowingbenefitstoyourdatabaseapplications:

Performance—StoredProceduresareusuallymoreefficientandfasterthanregularSQLqueriesbecauseSQLstatementsareparsedforsyntacticalaccuracyandprecompiledbytheDBMSwhenthestoredprocedureiscreated.Also,combiningalargenumberofSQLstatementswithconditionallogicandparametersintoastoredprocedureallowstheprocedurestoperformqueries,makedecisions,andreturnresultswithoutextratripstothedatabaseserver.

Maintainability—StoredProceduresisolatethelower-leveldatabasestructurefromtheapplication.Aslongasthetablenames,columnnames,parameternames,andtypesdonotchangefromwhatisstatedinthestoredprocedure,youdonotneedtomodifytheprocedurewhenchangesaremadetothedatabaseschema.StoredproceduresarealsoawaytosupportmodularSQLprogrammingbecauseafteryoucreateaprocedure,youandotheruserscanreusethatprocedurewithoutknowingthedetailsofthetablesinvolved.

Security—Whencreatingtablesinadatabase,theDatabaseAdministratorcansetEXECUTEpermissionsonstoredprocedureswithoutgrantingSELECT,INSERT,UPDATE,andDELETEpermissionstousers.Therefore,thedatainthesetablesisprotectedfromuserswhoarenotusingthestoredprocedures.

32 CreatingandusingStoredProcedures

Tutorial: Introduction to Database Systems

Storedproceduresaresimilartouser-definedfunctions.ThemajordifferenceisthatfunctionscanbeusedlikeanyotherexpressionwithinSQLstatements,whereasstoredproceduresmustbeinvokedusingtheCALLstatement.

ThesyntaxforcreatingaStoredProcedureisasfollows:

CREATE PROCEDURE <ProcedureName> @<Parameter1> <datatype> …

Example:

CreateaStoredProcedure:

ThisProceduregetsCustomerDatabasedonaspecificOrderNumber.

IF EXISTS (SELECT name FROM sysobjects WHERE name = 'sp_CustomerOrders' AND type = 'P') DROP PROCEDURE sp_CustomerOrders GO CREATE PROCEDURE sp_CustomerOrders @OrderNumber varchar(50) AS /*------------------------------------------------------------------------- Last Updated Date: 2009.11.03 Last Updated By: [email protected] Description: Get Customer Information from a specific Order Number -------------------------------------------------------------------------*/ SET NOCOUNT ON declare @CustomerId int select @CustomerId = CustomerId from [ORDER] where OrderNumber = @OrderNumber select CustomerId, FirstName, LastName, [Address], Phone from CUSTOMER where CustomerId=@CustomerId SET NOCOUNT OFF Og

UsingaStoredProcedure:

UsingtheStoredprocedurelikethis

exec sp_CustomerOrders '10002'

Thisgivesthefollowingresult:

[EndofExample]

33

10 CreatingandUsingTriggers

Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingtheintegrityoftheinformationonthedatabase.Forexample,whenanewrecord(representinganewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhetablesofthetaxes,vacations,andsalaries.

Triggersarecommonlyusedto:

• preventchanges(e.g.preventaninvoicefrombeingchangedafterit'sbeenmailedout)

• logchanges(e.g.keepacopyoftheolddata) • auditchanges(e.g.keepalogoftheusersandrolesinvolvedinchanges) • enhancechanges(e.g.ensurethateverychangetoarecordistime-stampedbythe

server'sclock,nottheclient's) • enforcebusinessrules(e.g.requirethateveryinvoicehaveatleastonelineitem) • executebusinessrules(e.g.notifyamanagereverytimeanemployee'sbankaccount

numberchanges) • replicatedata(e.g.storearecordofeverychange,tobeshippedtoanotherdatabase

later) • enhanceperformance(e.g.updatetheaccountbalanceaftereverydetailtransaction,

forfasterqueries)

Themajorfeaturesofdatabasetriggers,andtheireffects,are:

• donotacceptparametersorarguments(butmaystoreaffected-dataintemporarytables)

• cannotperformcommitorrollbackoperationsbecausetheyarepartofthetriggeringSQLstatement

• cancancelarequestedoperation • cancausemutatingtableerrors,iftheyarepoorlywritten.

34 CreatingandusingStoredProcedures

Tutorial: Introduction to Database Systems

MicrosoftSQLServersupportstriggerseitherafterorinsteadofaninsert,update,ordeleteoperation.

Syntax:

CREATE TRIGGER <TriggerName> ON <TableName> FOR INSERT, UPDATE, DELETE AS …

35

11 CreatingandUsingFunctions

InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthefunctionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQLstatements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalarfunctionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.

StoredProceduresvs.Functions:

• Onlyfunctionscanreturnavalue(usingtheRETURNkeyword). • StoredprocedurescanuseRETURNkeywordbutwithoutanyvaluebeingpassed[1] • FunctionscouldbeusedinSELECTstatements,providedtheydon’tdoanydata

manipulationandalsoshouldnothaveanyOUTorINOUTparameters. • Functionsmustreturnavalue,butforstoredproceduresthisisnotcompulsory. • AfunctioncanhaveonlyINparameters,whilestoredproceduresmayhaveOUTorIN

OUTparameters. • Afunctionisasubprogramwrittentoperformcertaincomputationsandreturna

singlevalue. • Astoredprocedureisasubprogramwrittentoperformasetofactions,andcan

returnmultiplevaluesusingtheOUTparameterorreturnnovalueatall.

User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.

Syntax:

CREATE FUNCTION <FunctionName> (@Parameter1 <datatype>, @ Parameter2 <datatype>, …) RETURNS <datatype> AS …

IntroductiontoDatabaseSystems

Hans-PetterHalvorsen

Copyright©2017

E-Mail:[email protected]

Web:https://www.halvorsen.blog

https://www.halvorsen.blog