Download Introduction to Database Systems

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Tandem Computers wikipedia , lookup

Serializability wikipedia , lookup

DBase wikipedia , lookup

Relational algebra wikipedia , lookup

IMDb wikipedia , lookup

Btrieve wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft Access wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Concurrency control wikipedia , lookup

Ingres (database) wikipedia , lookup

Functional Database Model wikipedia , lookup

Database wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

PL/SQL wikipedia , lookup

ContactPoint wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
UniversityCollegeofSoutheastNorway
IntroductiontoDatabase
Systems
Hans-PetterHalvorsen,2016.11.01
http://home.hit.no/~hansha
Preface
Thisdocumentexplainsthebasicconceptsofadatabasesystemandhowtocommunicate
withadatabasesystem.
ThemainfocusinthisdocumentisonrelationaldatabasesandMicrosoftSQLServer.
FormoreinformationaboutDatabases,visitmyBlog:http://home.hit.no/~hansha/
Sometextinthisdocumentisbasedontextfromwww.wikipedia.org.
TableofContents
Preface......................................................................................................................................2
TableofContents.....................................................................................................................iii
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
iii
iv
TableofContents
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
Tutorial: Introduction to Database Systems
v
Tutorial: Introduction to Database Systems
TableofContents
1 DatabaseSystems
Adatabaseisanintegratedcollectionoflogicallyrelatedrecordsorfilesconsolidatedintoa
commonpoolthatprovidesdataforoneormoremultipleuses.
Onewayofclassifyingdatabasesinvolvesthetypeofcontent,forexample:bibliographic,
full-text,numeric,andimage.Otherclassificationmethodsstartfromexaminingdatabase
modelsordatabasearchitectures.
Thedatainadatabaseisorganizedaccordingtoadatabasemodel.Therelationalmodelis
themostcommon.
ADatabaseManagementSystem(DBMS)consistsofsoftwarethatorganizesthestorageof
data.ADBMScontrolsthecreation,maintenance,anduseofthedatabasestorage
structuresoforganizationsandoftheirendusers.Itallowsorganizationstoplacecontrolof
organization-widedatabasedevelopmentinthehandsofDatabaseAdministrators(DBAs)
andotherspecialists.Inlargesystems,aDBMSallowsusersandothersoftwaretostoreand
retrievedatainastructuredway.
Databasemanagementsystemsareusuallycategorizedaccordingtothedatabasemodel
thattheysupport,suchasthenetwork,relationalorobjectmodel.Themodeltendsto
determinethequerylanguagesthatareavailabletoaccessthedatabase.Onecommonly
usedquerylanguagefortherelationaldatabaseisSQL,althoughSQLsyntaxandfunction
canvaryfromoneDBMStoanother.AgreatdealoftheinternalengineeringofaDBMSis
independentofthedatamodel,andisconcernedwithmanagingfactorssuchas
performance,concurrency,integrity,andrecoveryfromhardwarefailures.Intheseareas
therearelargedifferencesbetweenproducts.
1.1 RDBMSComponents
ARelationalDatabaseManagementSystem(DBMS)consistsofthefollowingcomponents:
•
Interfacedrivers-Auserorapplicationprograminitiateseitherschemamodification
orcontentmodification.ThesedriversarebuiltontopofSQL.Theyprovidemethods
topreparestatements,executestatements,fetchresults,etc.Animportantexample
istheODBCdriver. 1
2
•
•
•
•
DatabaseSystems SQLengine-ThiscomponentinterpretsandexecutestheSQLquery.Itcomprises
threemajorcomponents(compiler,optimizer,andexecutionengine). Transactionengine-Transactionsaresequencesofoperationsthatreadorwrite
databaseelements,whicharegroupedtogether. Relationalengine-RelationalobjectssuchasTable,Index,andReferentialintegrity
constraintsareimplementedinthiscomponent. Storageengine-Thiscomponentstoresandretrievesdatarecords.Italsoprovidesa
mechanismtostoremetadataandcontrolinformationsuchasundologs,redologs,
locktables,etc.
1.2 Datawarehouse
Adatawarehousestoresdatafromcurrentandpreviousyears—dataextractedfromthe
variousoperationaldatabasesofanorganization.Itbecomesthecentralsourceofdatathat
hasbeenscreened,edited,standardizedandintegratedsothatitcanbeusedbymanagers
andotherend-userprofessionalsthroughoutanorganization.
1.3 RelationalDatabase
Arelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.
Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegrouped
bytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthe
transaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,such
adatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.
Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,
manufacturingandlogisticalinformation,personneldataandmuchmore.
Strictly,arelationaldatabaseisacollectionofrelations(frequentlycalledtables).
1.4 Real-timedatabases
Tutorial: Introduction to Database Systems
3
DatabaseSystems Areal-timedatabaseisaprocessingsystemdesignedtohandleworkloadswhosestatemay
changeconstantly.Thisdiffersfromtraditionaldatabasescontainingpersistentdata,mostly
unaffectedbytime.Forexample,astockmarketchangesrapidlyanddynamically.Real-time
processingmeansthatatransactionisprocessedfastenoughfortheresulttocomeback
andbeactedonrightaway.Real-timedatabasesareusefulforaccounting,banking,law,
medicalrecords,multi-media,processcontrol,reservationsystems,andscientificdata
analysis.Ascomputersincreaseinpowerandcanstoremoredata,real-timedatabases
becomeintegratedintosocietyandareemployedinmanyapplications
1.5 NoSQLDatabases
ThenextgenerationofdatabasesystemsisknownasNoSQLdatabasesanddocumentorienteddatabases.NoSQLdatabasesareoftenveryfast,donotrequirefixedtable
schemas.
ExamplesofNoSQLsystems:MongoDBandOracleNoSQLDatabase.
1.6 DatabaseManagementSystems
ThereareDatabaseManagementSystems(DBMS),suchas:
•
•
•
•
•
•
•
•
MicrosoftSQLServer
Oracle
Sybase
dBase
MicrosoftAccess
MySQLfromSunMicrosystems(Oracle)
DB2fromIBM
etc.
ThisdocumentwillfocusonMicrosoftAccessandMicrosoftSQLServer.
Tutorial: Introduction to Database Systems
4
DatabaseSystems 1.7 MDAC
TheMicrosoftDataAccessComponents(MDAC)istheframeworkthatmakesitpossibleto
connectandcommunicatewiththedatabase.MDACincludesthefollowingcomponents:
•
•
•
ODBC(OpenDatabaseConnectivity)
OLEDB
ADO(ActiveXDataObjects) MDACalsoinstallsseveraldataprovidersyoucanusetoopenaconnectiontoaspecificdata
source,suchasanMSAccessdatabase.
1.7.1
ODBC
OpenDatabaseConnectivity(ODBC)isanativeinterfacethatisaccessedthrougha
programminglanguagethatcanmakecallsintoanativelibrary.InMDACthisinterfaceis
definedasaDLL.Aseparatemoduleordriverisneededforeachdatabasethatmustbe
accessed. 1.7.2
OLEDB
OLEallowsMDACapplicationsaccesstodifferenttypesofdatastoresinauniformmanner.
Microsofthasusedthistechnologytoseparatetheapplicationfromthedatastorethatit
needstoaccess.Thiswasdonebecausedifferentapplicationsneedaccesstodifferenttypes
andsourcesofdata,anddonotnecessarilyneedtoknowhowtoaccesstechnology-specific
functionality.Thetechnologyisconceptuallydividedintoconsumersandproviders.The
consumersaretheapplicationsthatneedaccesstothedata,andtheprovideristhe
softwarecomponentthatexposesanOLEDBinterfacethroughtheuseoftheComponent
ObjectModel(orCOM).
1.7.3
ADO(ActiveXDataObjects) ActiveXDataObjects(ADO)isahighlevelprogramminginterfacetoOLEDB.Itusesa
hierarchicalobjectmodeltoallowapplicationstoprogrammaticallycreate,retrieve,update
anddeletedatafromsourcessupportedbyOLEDB.ADOconsistsofaseriesofhierarchical
COM-basedobjectsandcollections,anobjectthatactsasacontainerofmanyotherobjects.
AprogrammercandirectlyaccessADOobjectstomanipulatedata,orcansendanSQLquery
tothedatabaseviaseveralADOmechanisms.
Tutorial: Introduction to Database Systems
2 RelationalDatabases
Arelationaldatabasematchesdatausingcommoncharacteristicsfoundwithinthedataset.
Theresultinggroupsofdataareorganizedandaremucheasierforpeopletounderstand.
Forexample,adatasetcontainingallthereal-estatetransactionsinatowncanbegrouped
bytheyearthetransactionoccurred;oritcanbegroupedbythesalepriceofthe
transaction;oritcanbegroupedbythebuyer'slastname;andsoon.
Suchagroupingusestherelationalmodel(atechnicaltermforthisisschema).Hence,such
adatabaseiscalleda"relationaldatabase."
Thesoftwareusedtodothisgroupingiscalledarelationaldatabasemanagementsystem.
Theterm"relationaldatabase"oftenreferstothistypeofsoftware.
Relationaldatabasesarecurrentlythepredominantchoiceinstoringfinancialrecords,
manufacturingandlogisticalinformation,personneldataandmuchmore.
2.1 Tables
Thebasicunitsinadatabasearetablesandtherelationshipbetweenthem.Strictly,a
relationaldatabaseisacollectionofrelations(frequentlycalledtables).
BelowweseehowarelationshipbetweentwotablesaredefinedusingPrimaryKeysand
ForeignKeys.
5
6
RelationalDatabases 2.2 UniqueKeysandPrimaryKey
Inrelationaldatabasedesign,auniquekeyorprimarykeyisacandidatekeytouniquely
identifyeachrowinatable.Auniquekeyorprimarykeycomprisesasinglecolumnorsetof
columns.Notwodistinctrowsinatablecanhavethesamevalue(orcombinationofvalues)
inthosecolumns.Dependingonitsdesign,atablemayhavearbitrarilymanyuniquekeys
butatmostoneprimarykey.
Auniquekeymustuniquelyidentifyallpossiblerowsthatexistinatableandnotonlythe
currentlyexistingrows.ExamplesofuniquekeysareSocialSecuritynumbersorISBNs. Aprimarykeyisaspecialcaseofuniquekeys.Themajordifferenceisthatforuniquekeys
theimplicitNOTNULLconstraintisnotautomaticallyenforced,whileforprimarykeysitis
enforced.Thus,thevaluesinuniquekeycolumnsmayormaynotbeNULL.Another
differenceisthatprimarykeysmustbedefinedusinganothersyntax.
Primarykeysaredefinedwiththefollowingsyntax:
CREATE TABLE table_name
(
id_col INT,
col2
CHARACTER VARYING(20),
...
CONSTRAINT tab_pk PRIMARY KEY(id_col),
...
)
Iftheprimarykeyconsistsonlyofasinglecolumn,thecolumncanbemarkedassuchusing
thefollowingsyntax:
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,thecolumncanbemarkedassuch
usingthefollowingsyntax:
CREATE TABLE table_name
(
Tutorial: Introduction to Database Systems
7
RelationalDatabases id_col INT PRIMARY KEY,
col2
CHARACTER VARYING(20),
...
key_col SMALLINT UNIQUE,
...
)
2.3 ForeignKey
Inthecontextofrelationaldatabases,aforeignkeyisareferentialconstraintbetweentwo
tables.Theforeignkeyidentifiesacolumnorasetofcolumnsinonetablethatreferstoa
columnorsetofcolumnsinanothertable.Thecolumnsinthereferencingtablemustbethe
primarykeyorothercandidatekeyinthereferencedtable.Thevaluesinonerowofthe
referencingcolumnsmustoccurinasinglerowinthereferencedtable.Thus,arowinthe
referencingtablecannotcontainvaluesthatdon'texistinthereferencedtable.Thisway
referencescanbemadetolinkinformationtogetheranditisanessentialpartofdatabase
normalization.Multiplerowsinthereferencingtablemayrefertothesamerowinthe
referencedtable.Mostofthetime,itreflectstheone(mastertable,orreferencedtable)to
many(childtable,orreferencingtable)relationship.
Thereferencingandreferencedtablemaybethesametable,i.e.theforeignkeyrefersback
tothesametable.Suchaforeignkeyisknownasself-referencingorrecursiveforeignkey.
Atablemayhavemultipleforeignkeys,andeachforeignkeycanhaveadifferentreferenced
table.Eachforeignkeyisenforcedindependentlybythedatabasesystem.Therefore,
cascadingrelationshipsbetweentablescanbeestablishedusingforeignkeys.
Improperforeignkey/primarykeyrelationshipsornotenforcingthoserelationshipsare
oftenthesourceofmanydatabaseanddatamodelingproblems.
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,thecolumncanbemarkedassuchusingthe
followingsyntax:
CREATE TABLE table_name
(
id
INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
col3 INTEGER REFERENCES other_table(column_name),
Tutorial: Introduction to Database Systems
8
RelationalDatabases ...
)
2.4 Views
Indatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposed
oftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnot
formpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfrom
datainthedatabase.Changingthedatainatablealtersthedatashowninsubsequent
invocationsoftheview.
Viewscanprovideadvantagesovertables:
•
•
•
•
•
•
Viewscanrepresentasubsetofthedatacontainedinatable Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents Viewscanlimitthedegreeofexposureofatableortablestotheouterworld
Syntax:
CREATE VIEW <ViewName>
AS
…
2.5 Functions
InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthe
functionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQL
statements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalar
functionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational)
tablecomprisingzeroormorerows,eachrowwithoneormorecolumns.
User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement.
Syntax:
CREATE FUNCTION <FunctionName>
(@Parameter1 <datatype>,
@ Parameter2 <datatype>,
…)
Tutorial: Introduction to Database Systems
9
RelationalDatabases RETURNS <datatype>
AS
…
2.6 StoredProcedures
Astoredprocedureisexecutablecodethatisassociatedwith,andgenerallystoredin,the
database.Storedproceduresusuallycollectandcustomizecommonoperations,like
insertingatupleintoarelation,gatheringstatisticalinformationaboutusagepatterns,or
encapsulatingcomplexbusinesslogicandcalculations.Frequentlytheyareusedasan
applicationprogramminginterface(API)forsecurityorsimplicity.
Storedproceduresarenotpartoftherelationaldatabasemodel,butallcommercial
implementationsincludethem.
Storedproceduresarecalledorusedwiththefollowingsyntax:
CALL procedure(…)
or
EXECUTE procedure(…)
Storedprocedurescanreturnresultsets,i.e.theresultsofaSELECTstatement.Suchresult
setscanbeprocessedusingcursorsbyotherstoredproceduresbyassociatingaresultset
locator,orbyapplications.Storedproceduresmayalsocontaindeclaredvariablesfor
processingdataandcursorsthatallowittoloopthroughmultiplerowsinatable.The
standardStructuredQueryLanguageprovidesIF,WHILE,LOOP,REPEAT,CASEstatements,
andmore.Storedprocedurescanreceivevariables,returnresultsormodifyvariablesand
returnthem,dependingonhowandwherethevariableisdeclared.
2.7 Triggers
Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertain
eventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingthe
integrityoftheinformationonthedatabase.Forexample,whenanewrecord(representing
anewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhe
tablesofthetaxes,vacations,andsalaries.
Thesyntaxisasfollows:
CREATE TRIGGER <TriggerName> ON <TableName>
FOR INSERT, UPDATE, DELETE
AS
…
Tutorial: Introduction to Database Systems
3 StructuredQueryLanguage
(SQL)
SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanaging
datainrelationaldatabasemanagementsystems(RDBMS).
ThisdocumentgivesonlyaverybriefoverviewofSQL,formorein-depthoverviewofSQL.
Pleaserefertothetutorial“StructuredQueryLanguage”locatedonmywebsite:
http://home.hit.no/~hansha/?tutorial=sql 3.1 Queries
ThemostcommonoperationinSQListhequery,whichisperformedwiththedeclarative
SELECTstatement.SELECTretrievesdatafromoneormoretables,orexpressions.Standard
SELECTstatementshavenopersistenteffectsonthedatabase.
Queriesallowtheusertodescribedesireddata,leavingthedatabasemanagementsystem
(DBMS)responsibleforplanning,optimizing,andperformingthephysicaloperations
necessarytoproducethatresultasitchooses.
Aqueryincludesalistofcolumnstobeincludedinthefinalresultimmediatelyfollowingthe
SELECTkeyword.Anasterisk("*")canalsobeusedtospecifythatthequeryshouldreturnall
columnsofthequeriedtables.SELECTisthemostcomplexstatementinSQL,withoptional
keywordsandclausesthatinclude:
•
•
•
TheFROMclausewhichindicatesthetable(s)fromwhichdataistoberetrieved.The
FROMclausecanincludeoptionalJOINsubclausestospecifytherulesforjoining
tables. TheWHEREclauseincludesacomparisonpredicate,whichrestrictstherows
returnedbythequery.TheWHEREclauseeliminatesallrowsfromtheresultsetfor
whichthecomparisonpredicatedoesnotevaluatetoTrue. TheGROUPBYclauseisusedtoprojectrowshavingcommonvaluesintoasmaller
setofrows.GROUPBYisoftenusedinconjunctionwithSQLaggregationfunctionsor
10
11
•
•
StructuredQueryLanguage(SQL) toeliminateduplicaterowsfromaresultset.TheWHEREclauseisappliedbeforethe
GROUPBYclause. TheHAVINGclauseincludesapredicateusedtofilterrowsresultingfromtheGROUP
BYclause.BecauseitactsontheresultsoftheGROUPBYclause,aggregation
functionscanbeusedintheHAVINGclausepredicate. TheORDERBYclauseidentifieswhichcolumnsareusedtosorttheresultingdata,
andinwhichdirectiontheyshouldbesorted(optionsareascendingordescending).
WithoutanORDERBYclause,theorderofrowsreturnedbyanSQLqueryis
undefined.
Example:
ThefollowingisanexampleofaSELECTquerythatreturnsalistofexpensivebooks.The
queryretrievesallrowsfromtheBooktableinwhichthepricecolumncontainsavalue
greaterthan100.00.Theresultissortedinascendingorderbytitle.Theasterisk(*)inthe
selectlistindicatesthatallcolumnsoftheBooktableshouldbeincludedintheresultset.
SELECT *
FROM Book
WHERE price > 100.00
ORDER BY title;
Theexamplebelowdemonstratesaqueryofmultipletables,grouping,andaggregation,by
returningalistofbooksandthenumberofauthorsassociatedwitheachbook.
SELECT Book.title,count(*) AS Authors
FROM Book
JOIN Book_author ON Book.isbn = Book_author.isbn
GROUP BY Book.title
[EndofExample]
3.2 DataManipulation
TheDataManipulationLanguage(DML)isthesubsetofSQLusedtoadd,updateanddelete
data.
TheacronymCRUDreferstoallofthemajorfunctionsthatneedtobeimplementedina
relationaldatabaseapplicationtoconsideritcomplete.Eachletterintheacronymcanbe
mappedtoastandardSQLstatement:
Operation
Create
SQL
INSERT Tutorial: Introduction to Database Systems
12
StructuredQueryLanguage(SQL) 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 DataDefinition
TheDataDefinitionLanguage(DDL)managestableandindexstructure.Themostbasic
itemsofDDLaretheCREATE,ALTER,RENAMEandDROPstatements:
•
•
•
CREATEcreatesanobject(atable,forexample)inthedatabase. DROPdeletesanobjectinthedatabase,usuallyirretrievably. ALTERmodifiesthestructureanexistingobjectinvariousways—forexample,adding
acolumntoanexistingtable. Example:
CREATE:
CreateaDatabaseTable:
CREATE TABLE My_table
(
my_field1
INT,
Tutorial: Introduction to Database Systems
13
StructuredQueryLanguage(SQL) my_field2
VARCHAR(50),
my_field3
DATE
NOT NULL,
PRIMARY KEY (my_field1)
)
[EndofExample]
3.4 DataTypes
EachcolumninanSQLtabledeclaresthetype(s)thatcolumnmaycontain.ANSISQL
includesthefollowingdatatypes.
3.4.1
•
•
•
•
CHARACTER(n)orCHAR(n)—fixed-widthn-characterstring,paddedwithspacesas
needed CHARACTERVARYING(n)orVARCHAR(n)—variable-widthstringwithamaximum
sizeofncharacters NATIONALCHARACTER(n)orNCHAR(n)—fixedwidthstringsupportingan
internationalcharacterset NATIONALCHARACTERVARYING(n)orNVARCHAR(n)—variable-widthNCHARstring 3.4.2
•
•
Numbers
INTEGERandSMALLINT FLOAT,REALandDOUBLEPRECISION NUMERIC(precision,scale)orDECIMAL(precision,scale) 3.4.4
•
•
•
•
BitStrings
BIT(n)—anarrayofnbits BITVARYING(n)—anarrayofuptonbits 3.4.3
•
•
•
CharacterStrings
DateandTime
DATE TIME TIMESTAMP INTERVAL
Tutorial: Introduction to Database Systems
4 DatabaseModelling
4.1 ERDiagram
Insoftwareengineering,anEntity-RelationshipModel(ERM)isanabstractandconceptual
representationofdata.Entity-relationshipmodelingisadatabasemodelingmethod,usedto
produceatypeofconceptualschemaorsemanticdatamodelofasystem,oftenarelational
database,anditsrequirementsinatop-downfashion.
Diagramscreatedusingthisprocessarecalledentity-relationshipdiagrams,orERdiagrams
orERDsforshort.
TherearemanyERdiagrammingtools.SomeoftheproprietaryERdiagrammingtoolsare
ERwin,EnterpriseArchitectandMicrosoftVisio. MicrosoftSQLServerhasalsoabuilt-intoolforcreatingDatabaseDiagrams.
14
15
DatabaseModelling 4.2 MicrosoftVisio
MicrosoftVisioisadiagrammingprogramforcreatingdifferentkindsofdiagrams.Visiohave
atemplateforcreatingDatabaseModelDiagrams.
Tutorial: Introduction to Database Systems
16
DatabaseModelling IntheDatabasemenuVisioofferslotsoffunctionalityregardingyourdatabasemodel.
“ReverseEngineering”istheoppositeprocedure,i.e.,extractionofadatabaseschemafrom
anexistingdatabaseintoadatabasemodelinMicrosoftVisio.
Example:DatabaseDiagram
CreatethefollowingtablesinanERDiagramusingMSVisio.
•
•
•
CUSTOMER
o CustomerId(PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId(PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId(PK)
o OrderNumber
o OrderDescription
Tutorial: Introduction to Database Systems
17
•
DatabaseModelling o CustomerId(FK)
ORDER_DETAIL
o OrderDetailId(PK)
o OrderId(FK)
o ProductId(FK)
TheDatabaseDiagrambecomes:
[EndofExample]
4.3 ERwin
ERwinisaprofessionaldatabasemodellingtool.ACommunityeditionisalsoavailablefor
free.TheCommunityeditionislimitedtoworkwithmax25objects.
BelowweseeanexamplecreatedinErwin.
WithErwinandotherprofessionaldatabasemodellingtoolsyoucandirectlyimportthe
databasemodelintothedatabasesystemsuchasSQLServer,MySQL,etc.
Tutorial: Introduction to Database Systems
18
DatabaseModelling Tutorial: Introduction to Database Systems
5 MicrosoftSQLServer
5.1 Introduction
MicrosoftSQLServerisarelationalmodeldatabaseserverproducedbyMicrosoft.Its
primaryquerylanguagesareT-SQLandANSISQL.
ThelatestversionisMicrosoftSQLServer2014.
MicrosoftSQLServerhomepage:www.microsoft.com/sqlserver
TheMicrosoftSQLServercomesindifferentversions,suchas:
•
•
•
•
•
SQLServerDeveloperEdition
SQLServerEnterpriseEdition
SQLServerWebEdition
SQLServerExpressEdition
Etc.
TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
5.2 SQLServerExpress
TheSQLServerExpressEditionisafreely-downloadableand-distributableversion.
However,theExpresseditionhasanumberoftechnicalrestrictionswhichmakeit
undesirableforlarge-scaledeployments,including:
•
•
•
Maximumdatabasesizeof4GBper.The4GBlimitappliesperdatabase(logfiles
excluded);butinsomescenariosuserscanaccessmoredatathroughtheuseof
multipleinterconnecteddatabases. SinglephysicalCPU,multiplecores 1GBofRAM(runsonanysizeRAMsystem,butusesonly1GB)
SQLServerExpressoffersaGUItoolsfordatabasemanagementinaseparatedownloadand
installationpackage,calledSQLServerManagementStudioExpress.
19
20
MicrosoftSQLServer 5.3 SQLServerManagementStudio
SQLServerManagementStudioisaGUItoolincludedwithSQLServerforconfiguring,
managing,andadministeringallcomponentswithinMicrosoftSQLServer.Thetoolincludes
bothscripteditorsandgraphicaltoolsthatworkwithobjectsandfeaturesoftheserver.As
mentionedearlier,versionofSQLServerManagementStudioisalsoavailableforSQLServer
ExpressEdition,forwhichitisknownasSQLServerManagementStudioExpress.
AcentralfeatureofSQLServerManagementStudioistheObjectExplorer,whichallowsthe
usertobrowse,select,andactuponanyoftheobjectswithintheserver.Itcanbeusedto
visuallyobserveandanalyzequeryplansandoptimizethedatabaseperformance,among
others.SQLServerManagementStudiocanalsobeusedtocreateanewdatabase,alterany
existingdatabaseschemabyaddingormodifyingtablesandindexes,oranalyze
performance.ItincludesthequerywindowswhichprovideaGUIbasedinterfacetowrite
andexecutequeries.
5.4 CreateaNewDatabase
ItisquitesimpletocreateanewdatabaseinMicrosoftSQLServer.Justright-clickonthe
“Databases”nodeandselect“NewDatabase…”
Tutorial: Introduction to Database Systems
21
MicrosoftSQLServer Therearelotsofsettingsyoumaysetregardingyourdatabase,buttheonlyinformationyou
mustfillinisthenameofyourdatabase:
Tutorial: Introduction to Database Systems
22
MicrosoftSQLServer 5.5 Backup/Restore
DatabaseBackupandRestore:
Tutorial: Introduction to Database Systems
23
MicrosoftSQLServer Tutorial: Introduction to Database Systems
6 MicrosoftOfficeAccess
6.1 Introduction
MicrosoftOfficeAccess,previouslyknownasMicrosoftAccess,isarelationaldatabase
managementsystemfromMicrosoftthatcombinestherelationalMicrosoftJetDatabase
Enginewithagraphicaluserinterfaceandsoftwaredevelopmenttools.Itisamemberofthe
MicrosoftOfficesuiteofapplicationsandisincludedintheProfessionalandhigherversions
forWindows.AccessstoresdatainitsownformatbasedontheAccessJetDatabaseEngine.
MicrosoftAccessisusedbyprogrammersandnon-programmerstocreatetheirownsimple
databasesolutions.
MicrosoftAccessisafileserver-baseddatabase.Unlikeclient-serverrelationaldatabase
managementsystems(RDBMS),e.g.,MicrosoftSQLServer,MicrosoftAccessdoesnot
implementdatabasetriggers,storedprocedures,ortransactionlogging.Alldatabasetables,
queries,forms,reports,macros,andmodulesarestoredintheAccessJetdatabaseasa
singlefile.ThismakesMicrosoftAccessusefulinsmallapplications,teaching,etc.becauseit
iseasytomovefromonecomputertoanother.
6.2 ExampleDatabase
IwillpresentanexampledatabaseinMicrosoftAccess2007whichwillbeusedinsomeof
theexamplesandexercisesinthisdocument.
Thedatabaseconsistsofthefollowingtables:
•
•
CUSTOMER
o CustomerId(PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
24
25
•
•
MicrosoftOfficeAccess o ProductId(PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId(PK)
o OrderNumber
o OrderDescription
o CustomerId(FK)
ORDER_DETAIL
o OrderDetailId(PK)
o OrderId(FK)
o ProductId(FK)
ODBCConnection:
AdministrativeTools→DataSources(ODBC)
Tutorial: Introduction to Database Systems
26
MicrosoftOfficeAccess Tutorial: Introduction to Database Systems
7 CreatingandUsingTables
TheSQLsyntaxforcreatingaTableisasfollows:
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
27
28
INSERT
VALUES
GO
INSERT
VALUES
GO
CreatingandUsingTables INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress])
('Tor', 'Hansen', 'Vipeveien 15', '77775678', '4455', 'Bergen')
INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress])
('Arne', 'Nilsen', 'Vipeveien 17', '12345778', '4434', 'Porsgrunn')
--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]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
INSERT INTO [ORDER_DETAIL]
GO
([OrderId],[ProductId]) VALUES (1, 1)
([OrderId],[ProductId]) VALUES (1, 2)
([OrderId],[ProductId]) VALUES (1, 3)
([OrderId],[ProductId]) VALUES (2, 1)
([OrderId],[ProductId]) VALUES (2, 2)
([OrderId],[ProductId]) VALUES (3, 3)
([OrderId],[ProductId]) VALUES (3, 1)
([OrderId],[ProductId]) VALUES (3, 2)
([OrderId],[ProductId]) VALUES (3, 3)
ExecutingthefollowingQueriesthengives:
select * from CUSTOMER
select * from PRODUCT
Tutorial: Introduction to Database Systems
29
CreatingandUsingTables select * from [ORDER]
select * from ORDER_DETAIL
[EndofExample]
Tutorial: Introduction to Database Systems
8 CreatingandUsingViews
Indatabasetheory,aviewconsistsofastoredqueryaccessibleasavirtualtablecomposed
oftheresultsetofaquery.Unlikeordinarytablesinarelationaldatabase,aviewdoesnot
formpartofthephysicalschema:itisadynamic,virtualtablecomputedorcollatedfrom
datainthedatabase.Changingthedatainatablealtersthedatashowninsubsequent
invocationsoftheview.
Viewscanprovideadvantagesovertables:
•
•
•
•
•
•
•
Viewscanrepresentasubsetofthedatacontainedinatable Viewscanjoinandsimplifymultipletablesintoasinglevirtualtable Viewscanactasaggregatedtables,wherethedatabaseengineaggregatesdata
(sum,averageetc)andpresentsthecalculatedresultsaspartofthedata Viewscanhidethecomplexityofdata;forexampleaviewcouldappearasSales2000
orSales2001,transparentlypartitioningtheactualunderlyingtable Viewstakeverylittlespacetostore;thedatabasecontainsonlythedefinitionofa
view,notacopyofallthedataitpresents DependingontheSQLengineused,viewscanprovideextrasecurity Viewscanlimitthedegreeofexposureofatableortablestotheouterworld Justasfunctions(inprogramming)canprovideabstraction,sodatabaseuserscancreate
abstractionbyusingviews.Inanotherparallelwithfunctions,databaseuserscanmanipulate
nestedviews,thusoneviewcanaggregatedatafromotherviews. Syntax:
CREATE VIEW <ViewName>
AS
…
30
9 CreatingandusingStored
Procedures
Astoredprocedureisasubroutineavailabletoapplicationsaccessingarelationaldatabase
system.Typicalusesforstoredproceduresincludedatavalidation(integratedintothe
database)oraccesscontrolmechanisms.Furthermore,storedproceduresareusedto
consolidateandcentralizelogicthatwasoriginallyimplementedinapplications.Largeor
complexprocessingthatmightrequiretheexecutionofseveralSQLstatementsismoved
intostoredprocedures,andallapplicationscalltheproceduresonly.
AstoredprocedureisaprecompiledcollectionofSQLstatementsandoptionalcontrol-offlowstatements,similartoamacro.Eachdatabaseanddataprovidersupportsstored
proceduresdifferently.Storedproceduresofferthefollowingbenefitstoyourdatabase
applications:
Performance—StoredProceduresareusuallymoreefficientandfasterthanregularSQL
queriesbecauseSQLstatementsareparsedforsyntacticalaccuracyandprecompiledbythe
DBMSwhenthestoredprocedureiscreated.Also,combiningalargenumberofSQL
statementswithconditionallogicandparametersintoastoredprocedureallowsthe
procedurestoperformqueries,makedecisions,andreturnresultswithoutextratripstothe
databaseserver.
Maintainability—StoredProceduresisolatethelower-leveldatabasestructurefromthe
application.Aslongasthetablenames,columnnames,parameternames,andtypesdonot
changefromwhatisstatedinthestoredprocedure,youdonotneedtomodifythe
procedurewhenchangesaremadetothedatabaseschema.Storedproceduresarealsoa
waytosupportmodularSQLprogrammingbecauseafteryoucreateaprocedure,youand
otheruserscanreusethatprocedurewithoutknowingthedetailsofthetablesinvolved.
Security—Whencreatingtablesinadatabase,theDatabaseAdministratorcansetEXECUTE
permissionsonstoredprocedureswithoutgrantingSELECT,INSERT,UPDATE,andDELETE
permissionstousers.Therefore,thedatainthesetablesisprotectedfromuserswhoarenot
usingthestoredprocedures.
31
32
CreatingandusingStoredProcedures Storedproceduresaresimilartouser-definedfunctions.Themajordifferenceisthat
functionscanbeusedlikeanyotherexpressionwithinSQLstatements,whereasstored
proceduresmustbeinvokedusingtheCALLstatement.
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]
Tutorial: Introduction to Database Systems
10 CreatingandUsing
Triggers
Adatabasetriggerisproceduralcodethatisautomaticallyexecutedinresponsetocertain
eventsonaparticulartableorviewinadatabase.Thetriggerismostlyusedforkeepingthe
integrityoftheinformationonthedatabase.Forexample,whenanewrecord(representing
anewworker)addedtotheemployeestable,newrecordsshouldbecreatedalsointhe
tablesofthetaxes,vacations,andsalaries.
Triggersarecommonlyusedto:
•
•
•
•
•
•
•
•
preventchanges(e.g.preventaninvoicefrombeingchangedafterit'sbeenmailed
out) 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-dataintemporary
tables) cannotperformcommitorrollbackoperationsbecausetheyarepartofthetriggering
SQLstatement cancancelarequestedoperation cancausemutatingtableerrors,iftheyarepoorlywritten.
33
34
CreatingandusingStoredProcedures MicrosoftSQLServersupportstriggerseitherafterorinsteadofaninsert,update,ordelete
operation.
Syntax:
CREATE TRIGGER <TriggerName> ON <TableName>
FOR INSERT, UPDATE, DELETE
AS
…
Tutorial: Introduction to Database Systems
11 CreatingandUsing
Functions
InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthe
functionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQL
statements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalar
functionreturnsonlyasinglevalue(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
…
35
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no