SQL:DataDefinitionLanguageCSC343Winter2018MICHAEL L IUT(MICHAEL.L [email protected])DEPARTMENT OF MATH EMAT ICA L ANDCOMPUTAT IONA L SC IENCE SUN IV E RS IT Y OF TORONTO M ISS ISSAUGA
DatabaseSchemasinSQLSQLisprimarilyaquerylanguage,forgetting informationfromadatabase.◦ DML:DataManipulation Language
ButSQLalso includes adata-definitioncomponent fordescribing databaseschemas.◦ DDL:DataDefinition Language
2
Creating(Declaring)aRelationSimply:◦ CREATE TABLE <table_name> (
<list ofelements>);
Deleting arelation:◦ DROPTABLE <table_name>;
3
ElementsofTableDeclarationsMostbasicelement: anattribute anditstype.CommonTypes:◦ INTorINTEGER (synonyms).◦ Also:SMALLINT,MEDIUMINT,andBIGINT
◦ REALorFLOATorDOUBLE(synonyms).◦ CHAR(n)=fixed-length stringofncharacters.◦ VARCHAR(n)=variable-length stringofuptoncharacters.
Additional datatypefoundhere:https://dev.mysql.com/doc/refman/5.7/en/data-types.html
4
Example:CreateTable
CREATE TABLE Sells (
bar CHAR(20),
beer VARCHAR(20),
price REAL
);
5
SQLValues
Integersandrealsarerepresented asyouwouldexpect.
Stringsaretoo,excepttheyrequiresingle quotes.◦ Twosinglequotes =realquote
e.g.‘Joe’’s Bar’.
AnyvaluecanbeNULL◦ Unless attribute hasNOTNULLconstraint
e.g.priceREALnotnull,
6
DatesandTimesDATEandTIMEaretypes inSQL◦ MySQLevenhasDATETIME
◦ Rangingfrom1000-01-0100:00:00 to9999-12-3123:59:59
Theformofadatevalue is:DATE‘yyyy-mm-dd’
e.g.DATE‘2007-09-30’isSeptember 30th,2007.
7
TimesandValues
Theformofatimevalue is:◦ TIME‘hh:mm:ss’– withanoptionaldecimalpointforafractionofasecond.
e.g.TIME‘15:30:02.5’=twoandahalfseconds after3:30pm.
8
DeclaringKeys
Anattributeorlistofattributesmaybedeclared PRIMARYKEYorUNIQUE.
Eithersaysthatnotwotuples oftherelationmayagree inalltheattribute(s) onthe list.
9
Example
Beers(name,manf)Bars(name,addr,license)Drinkers(name,addr,phone)Likes(drinker,beer)Sells(bar,beer,price)Frequents(drinker,bar)
Underline=key (tuplescannothavethesamevalueinallkeyattributes)
10
DeclaringSingle-AttributeKeys
PlacePRIMARYKEYorUNIQUEKEYafterthetype inthedeclaration oftheattribute.
Example:
CREATE TABLE Beers (
nameCHAR(20)UNIQUE,
manf CHAR(20)
);
11
DeclaringMulti-AttributeKeysAkeydeclaration canalsobeanotherelement inthe listofelements ofaCREATE TABLE statement.
Thisformisessential ifthekeyconsists ofmorethanoneattribute.◦ Couldbeusedforone-attributekeys.
12
Example
ThebarandbeertogetherarethekeyforSells:
CREATE TABLE Sells (
bar CHAR(20),beer VARCHAR(20),price REAL,PRIMARYKEY(bar,beer)
);
13
PrimaryKeyvs.Unique
1. TherecanbeonlyonePRIMARYKEYforarelation,butseveralUNIQUEattributes.
2. NoattributeofaPRIMARYKEYcaneverbeNULLinanytuple.Butattributes declaredUNIQUEmayhaveNULL’s,andtheremaybeseveraltupleswithNULL.
14
TypesofConstraints1. Keys
2. Foreign-key (referential-integrity) constraint
3. Domain constraint◦ Constrainvaluesofaparticularattribute.
4. Tuple-based constraint◦ Relationshipamongcomponents.
5. Assertions:anySQLBooleanexpressions
15
ForeignKeys
Valuesappearing inattributes ofonerelationmustappeartogether incertainattributes ofanotherrelation.
Example: inSells(bar,beer,price),wemightexpectthatabeervaluealsoappears inBeers.name
16
ExpressingForeignKeys
UsekeywordREFERENCES, either:1. Afteranattribute(forone-attribute keys).2. Asanelement oftheschema:
FOREIGNKEY(<listofattributes>)
REFERENCES <relation> (<attributes>)
Referencedattributesmustbedeclared PRIMARYKEYorUNIQUE.
17
Example:withAttribute
CREATE TABLE Beers(name CHAR(20) PRIMARYKEY,
manf CHAR(20)
);
CREATE TABLE Sells (bar CHAR(20),beer CHAR(20) REFERENCES Beers(name),
price REAL
);
18
Example:AsSchemaElementCREATE TABLE Beers(
name CHAR(20) PRIMARYKEY,
manf CHAR(20)
);
CREATE TABLE Sells (bar CHAR(20),beer CHAR(20),
price REAL
FOREIGNKEY(beer) REFERENCES Beers(name)
);19
EnforcingForeign-KeyConstraints
Ifthere isaforeign-keyconstraintfromrelationRtorelationS,twoviolations arepossible:
1. AninsertorupdatetoRintroducesvaluesnotfoundinS.
2. Adeletion orupdatetoScausessome tuplesofRto“dangle.”
20
ActionsTaken
Example: suppose R=Sells, S=Beers.
AninsertorupdatetoSells that introducesanonexistent beermustberejected.
Adeletion orupdatetoBeersthatremovesabeervaluefoundinsometuples ofSells canbehandled inthreeways.
21
ActionsTaken
Default:Rejectthemodification.
Cascade:Makethesamechanges inSells.◦ Deleted beer:delete Sellstuple.◦ Updatedbeer:changevalueinSells.
SetNull:ChangethebeettoNULL.
22
Example:Cascade
Delete theBudtuplefromBeers:◦ Thendelete alltuples fromSells thathavebeer=‘Bud’.
UpdatetheBudtuplebychanging ‘Bud’to‘Budweiser’◦ ThenchangeallSellstupleswithbeer=‘Bud’tobeer=‘Budweiser’
23
Example:SetNULL
Delete theBudtuplefromBeers:◦ Changealltuples ofSells thathavebeer=‘Bud’tohavebeer=NULL.
UpdatetheBudtuplebychanging ‘Bud’to‘Budweiser’:◦ Samechangeasfordeletion.
24
ChoosingaPolicy
Whenwedeclareaforeignkey,wemaychoosepolicies SETNULLorCASCADEindependently fordeletions andupdates.
Followtheforeign-keydeclarationby:ON[UPDATE,DELETE][SETNULLCASCADE]
Twosuchclausesmaybeused.
Otherwise, thedefault (reject)isused.
25
Example:SettingPolicyCREATE TABLE Sells (
barCHAR(20),beer CHAR(20),price REAL,FOREIGNKEY(beer)
REFERENCES Beers(name)ONDELETESETNULLONUPDATECASCADE
);
26
Attribute-BasedChecks
Constraints onthevalueofaparticular attribute.
AddCHECK(<condition>) tothedeclarationfortheattribute.
Theconditionmayusethenameoftheattribute,butanyotherrelationorattributemustbeinasub-query.
27
Example:Attribute-BasedCheck
CREATE TABLE Sells (
barCHAR(20),
beer CHAR(20)CHECK(
beer IN(SELECTnameFROMBeers)),
price REALCHECK(price<=5.00)
);
28
TimingofChecks
Attribute-based checksareperformedonlywhenavalueforthatattributeisinserted orupdated.
◦ Example: CHECK(price<=5.00)checkseverynewpriceandrejectsthemodification (forthattuple) ifthepriceismorethan$5.
◦ Example: CHECK(beer IN(SELECTnameFROMBeers))notchecked ifabeer isdeleted fromBeers (unlikeforeign-keys).
29
Tuple-BasedChecks
CHECK(<condition>) maybeaddedasarelation-schema element.
Theconditionmayrefertoanyattributeoftherelation.◦ Butotherattributes orrelations requireasub-query.
Checked oninsert orupdateonly.
30
Example:Tuple-BasedCheck
• OnlyJoe’sBarcansellbeerformorethan$5.
CREATE TABLE Sells (
bar CHAR(20),
beer CHAR(20),
price REAL,
CHECK(bar=‘Joe’’s Bar’ORprice<=5.00)
);
31
Questions?
32
I’LL BE ANSWERING QUESTIONS NOW
Q A&
THANKS FOR LISTENING
Citations,ImagesandResourcesDatabaseManagementSystems(3rd Ed.),Ramakrishnan&Gehrke
SomecontentisbasedofftheslidesofDr.Fei Chiang- http://www.cas.mcmaster.ca/~fchiang/
http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/06112016031910AM/sql.png
33