33
SQL: Data Definition Language CSC 343 Winter 2018 MICHAEL LIUT ( [email protected] ) DEPARTMENT OF MATHEMATICAL AND COMPUTATIONAL SCIENCES UNIVERSITY OF TORONTO MISSISSAUGA

SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

  • Upload
    others

  • View
    21

  • Download
    0

Embed Size (px)

Citation preview

Page 1: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 2: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

DatabaseSchemasinSQLSQLisprimarilyaquerylanguage,forgetting informationfromadatabase.◦ DML:DataManipulation Language

ButSQLalso includes adata-definitioncomponent fordescribing databaseschemas.◦ DDL:DataDefinition Language

2

Page 3: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Creating(Declaring)aRelationSimply:◦ CREATE TABLE <table_name> (

<list ofelements>);

Deleting arelation:◦ DROPTABLE <table_name>;

3

Page 4: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 5: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example:CreateTable

CREATE TABLE Sells (

bar CHAR(20),

beer VARCHAR(20),

price REAL

);

5

Page 6: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

SQLValues

Integersandrealsarerepresented asyouwouldexpect.

Stringsaretoo,excepttheyrequiresingle quotes.◦ Twosinglequotes =realquote

e.g.‘Joe’’s Bar’.

AnyvaluecanbeNULL◦ Unless attribute hasNOTNULLconstraint

e.g.priceREALnotnull,

6

Page 7: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 8: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

TimesandValues

Theformofatimevalue is:◦ TIME‘hh:mm:ss’– withanoptionaldecimalpointforafractionofasecond.

e.g.TIME‘15:30:02.5’=twoandahalfseconds after3:30pm.

8

Page 9: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

DeclaringKeys

Anattributeorlistofattributesmaybedeclared PRIMARYKEYorUNIQUE.

Eithersaysthatnotwotuples oftherelationmayagree inalltheattribute(s) onthe list.

9

Page 10: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 11: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

DeclaringSingle-AttributeKeys

PlacePRIMARYKEYorUNIQUEKEYafterthetype inthedeclaration oftheattribute.

Example:

CREATE TABLE Beers (

nameCHAR(20)UNIQUE,

manf CHAR(20)

);

11

Page 12: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

DeclaringMulti-AttributeKeysAkeydeclaration canalsobeanotherelement inthe listofelements ofaCREATE TABLE statement.

Thisformisessential ifthekeyconsists ofmorethanoneattribute.◦ Couldbeusedforone-attributekeys.

12

Page 13: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example

ThebarandbeertogetherarethekeyforSells:

CREATE TABLE Sells (

bar CHAR(20),beer VARCHAR(20),price REAL,PRIMARYKEY(bar,beer)

);

13

Page 14: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

PrimaryKeyvs.Unique

1. TherecanbeonlyonePRIMARYKEYforarelation,butseveralUNIQUEattributes.

2. NoattributeofaPRIMARYKEYcaneverbeNULLinanytuple.Butattributes declaredUNIQUEmayhaveNULL’s,andtheremaybeseveraltupleswithNULL.

14

Page 15: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

TypesofConstraints1. Keys

2. Foreign-key (referential-integrity) constraint

3. Domain constraint◦ Constrainvaluesofaparticularattribute.

4. Tuple-based constraint◦ Relationshipamongcomponents.

5. Assertions:anySQLBooleanexpressions

15

Page 16: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

ForeignKeys

Valuesappearing inattributes ofonerelationmustappeartogether incertainattributes ofanotherrelation.

Example: inSells(bar,beer,price),wemightexpectthatabeervaluealsoappears inBeers.name

16

Page 17: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

ExpressingForeignKeys

UsekeywordREFERENCES, either:1. Afteranattribute(forone-attribute keys).2. Asanelement oftheschema:

FOREIGNKEY(<listofattributes>)

REFERENCES <relation> (<attributes>)

Referencedattributesmustbedeclared PRIMARYKEYorUNIQUE.

17

Page 18: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 19: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 20: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

EnforcingForeign-KeyConstraints

Ifthere isaforeign-keyconstraintfromrelationRtorelationS,twoviolations arepossible:

1. AninsertorupdatetoRintroducesvaluesnotfoundinS.

2. Adeletion orupdatetoScausessome tuplesofRto“dangle.”

20

Page 21: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

ActionsTaken

Example: suppose R=Sells, S=Beers.

AninsertorupdatetoSells that introducesanonexistent beermustberejected.

Adeletion orupdatetoBeersthatremovesabeervaluefoundinsometuples ofSells canbehandled inthreeways.

21

Page 22: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

ActionsTaken

Default:Rejectthemodification.

Cascade:Makethesamechanges inSells.◦ Deleted beer:delete Sellstuple.◦ Updatedbeer:changevalueinSells.

SetNull:ChangethebeettoNULL.

22

Page 23: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example:Cascade

Delete theBudtuplefromBeers:◦ Thendelete alltuples fromSells thathavebeer=‘Bud’.

UpdatetheBudtuplebychanging ‘Bud’to‘Budweiser’◦ ThenchangeallSellstupleswithbeer=‘Bud’tobeer=‘Budweiser’

23

Page 24: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example:SetNULL

Delete theBudtuplefromBeers:◦ Changealltuples ofSells thathavebeer=‘Bud’tohavebeer=NULL.

UpdatetheBudtuplebychanging ‘Bud’to‘Budweiser’:◦ Samechangeasfordeletion.

24

Page 25: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

ChoosingaPolicy

Whenwedeclareaforeignkey,wemaychoosepolicies SETNULLorCASCADEindependently fordeletions andupdates.

Followtheforeign-keydeclarationby:ON[UPDATE,DELETE][SETNULLCASCADE]

Twosuchclausesmaybeused.

Otherwise, thedefault (reject)isused.

25

Page 26: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example:SettingPolicyCREATE TABLE Sells (

barCHAR(20),beer CHAR(20),price REAL,FOREIGNKEY(beer)

REFERENCES Beers(name)ONDELETESETNULLONUPDATECASCADE

);

26

Page 27: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Attribute-BasedChecks

Constraints onthevalueofaparticular attribute.

AddCHECK(<condition>) tothedeclarationfortheattribute.

Theconditionmayusethenameoftheattribute,butanyotherrelationorattributemustbeinasub-query.

27

Page 28: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Example:Attribute-BasedCheck

CREATE TABLE Sells (

barCHAR(20),

beer CHAR(20)CHECK(

beer IN(SELECTnameFROMBeers)),

price REALCHECK(price<=5.00)

);

28

Page 29: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 30: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Tuple-BasedChecks

CHECK(<condition>) maybeaddedasarelation-schema element.

Theconditionmayrefertoanyattributeoftherelation.◦ Butotherattributes orrelations requireasub-query.

Checked oninsert orupdateonly.

30

Page 31: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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

Page 32: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

Questions?

32

I’LL BE ANSWERING QUESTIONS NOW

Q A&

THANKS FOR LISTENING

Page 33: SQL: Data Definition Language · Database Schemas in SQL SQL is primarily a query language, for getting information from a database. DML: Data Manipulation Language But SQL also includes

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