sql: learn sql in 24 hours or less - a beginner’s guide to...

Post on 29-Jul-2020

6 Views

Category:

Documents

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

SQL:

LearnSQLin24HoursOrLess

ABeginner’sGuideToLearningSQLProgrammingNow

TableOfContents

Introduction

Chapter1:FundamentalConceptsRegardingSQLandDatabases

RelationalDatabases

TheSQLLanguage

TheSQLStatements

TheDifferentExecutionTypes

Chapter2:TheEnvironmentoftheSQLLanguage

SQL’sEnvironment–TheBasics

MoreDetailsAboutSQLCatalogs

TheSchemas

HowtoNameDatabaseObjects

HowtoGenerateaSchema

CreatingaNewDatabase

Chapter3:HowtoGenerateandModifyTables

GeneratinganSQLTable

SpecifyingtheDataTypeofaColumn

HowtoSpecifytheDefaultValueofaColumn

HowtoAlteranSQLTable

HowtoDeleteanSQLTable

Chapter4:HowtoEnsureDataIntegrity

IntegrityConstraints–TheBasics

TheNotNullConstraint

TheUniqueConstraint

ThePRIMARYKEYConstraint

TheFOREIGNKEYConstraints

TheCHECKConstraint

Chapter5:HowtoCreateanSQLView

HowtoAddaViewtoaDatabase

HowtoCreateanUpdateableView

HowtoDropaView

Chapter6:DatabaseSecurity

TheSecurityModelofSQL

CreatingandDeletingaRole

GrantingandRevokingaPrivilege

Conclusion

Bonus:PreviewOf“PHP:LearnPHPIn24HoursOrLess–ABeginner’sGuideToLearningPHPProgrammingNow”

ConditionalStructures

TheLoopStructures

Introduction

InthisbookyouwillfindpracticaltipsanddetailedinstructionsonhowtolearntheSQLlanguageinjustoneday.

ThiseBookwillteachyouthemostimportantaspectsofSQL.Itwillgiveyoutheoreticalexplanations, realisticexamples,actual syntaxand lotsofcodes. Ifyou’re looking foracomprehensiveguideabouttheSQLlanguage,thisisthematerialyou’relookingfor.

By reading this book, you’ll learn about a wide range of SQL-related topics. Here aresomeexamples:

Thedifferenttypesofdatabases

HowtouseSQLforarelationaldatabase

ThedifferenttypesofSQLcommands

Howtocreateadatabase

Howtogive/revokeaccountprivilegestousers

Howtocreatetablesandcolumns

Howtocustomizecolumns

ThedifferentdatatypesinSQL

Howtoapplyconstraintsontablesandcolumns

Howtoworkwithrelatedtables

Howtoenternewinformationintoadatabase

YoucancertainlybenefitfromthiseBookevenifyouhaveneverprogrammedanythingbefore. This eBook will teach you the basics of SQL programming and give you thesyntaxofimportantSQLcommands.IfyouwanttobecomeaskilledSQLprogrammerinjust24hours,getthiseBooknowandreaditcarefully.

Let’sbeginthejourney

Chapter1:FundamentalConceptsRegardingSQLandDatabases

ThischapterwillteachyouthebasicsoftheSQLlanguageandtherelationaldatabases.Byreadingthismaterial,you’llknowhowthelanguageworksandhowtousearelationaldatabase.

TheDatabases

SQL(i.e.StructuredQueryLanguage)allowsyoutocreateandmaintainrelationaldatabases.Italsoallowsthemanagementofinformationinsidethosedatabases.BeforediscussingSQLfurther,let’sdefinewhattheterm“database”means.Peopleusethistermwhenreferringtoacollectionofinformation(e.g.names,phonenumbers,addresses,etc.)thatisorganizedaccordingtoadefinitestructure.

Herearethemostcommonstructuresusedinmoderndatabases:

Hierarchical–Thisstructureusesparent-childrelationships.Itorganizesinformationthroughnodes,whicharethecounterpartoftablesinrelationaldatabases.Parentnodescanhavemultiplechildnodes.Childnodes,however,canhavejustone“parent.”Thehierarchicalstructureisextremelypopular,althoughitisinflexibleanddoesn’tsupportcomplicatedrelationships.

Network–Thenetworkstructuresolvestheproblemsfoundinthehierarchicalstructure.Here,youwillorganizeinformationinto“recordtypes.”Thisstructurearrangesinformationintoasystemthatlinkspairsofrecords:membersandowners.Arecordtypecanworkwithotherrecordtypes.Thus,anetworkdatabasesupportscomplicatedsearchesandrelationships.Themaindisadvantageofthisstructureisitscomplexity:youneedtoknowhowthestructureworksandhowinformationisstored.

Relational–Thisisthemostpopularstructurethesedays.Arelationaldatabaseaddressestheissueslinkedwithnetworkandhierarchicaldatabases.Inanetworkorhierarchicalsystem,you’llrelyonaparticulardatabaseimplementation,whichyouwill“hardcode”ontothedatabaseapplicationyouareusing.Youneedtoadjustthedatabaseapplicationwheneveryouadditemstoyourdatabase.Inarelationaldatabase,however,youwon’thavetoworryaboutyourapplication.Youmayalteryourdatabasewithoutaffectingtheapplicationitself.

RelationalDatabases

SinceyouwilluseSQLwithrelationaldatabases,weneedtodiscussthiskindofstructureindetail.Themainelementofarelationaldatabaseisthe“relation”,whichareessentiallygroupsofrowsandcolumnsplacedinatablethatrepresentsoneobject.Anobject(alsoknownas“entity”),ontheotherhand,consistsofrelatedinformation.

Entitiesarethings,events,places,persons,orconceptsaboutwhichinformationisgathered.Eachrelationconsistsofdifferentcolumns(whichrepresentattributes).Attributesareunitsthatdefineorcharacterizeentities.Forinstance,inthetablegivenbelow,theentityisabookwithsize,color,andweightasattributes.

Name_of_Pen:Brand

Pen_Size:Size

Pen_Color:Color

Product_Weight:Weight

PenA Small Red Light

PenB Medium Yellow Heavy

PenC Large Blue Heavy

Inthistable,alloftheattributeshaveadomain(i.e.thenamethatspecifieswhichtypeofinformationyoucanstoreintheattribute).Youshouldn’tconfuseattributeswithdatatypes.Datatypesareparticularkindsofconstraints(i.e.toolsusedtosecureinformationintegrity)linkedwithcolumns,whiledomainsdescribewhatinformationyoucanincludeintheattributesassociatedwiththem.Forinstance,theattributenamedProduct_WeightislinkedwiththeWeightdomain.

ImportantNote:Itwouldbebestifyouwilluseadomainthatdescribestheattributeitwillhold.Althoughthisapproachisoptional,itcanhelpyouimprovetheusabilityandreadabilityofyourdatabaseentries.

TheSQLLanguage

SQLisacomputerlanguagedesignedforrelationaldatabases.However,thislanguageisn’tadatabaseimplementation.Althoughtherelationalstructuregivesthecoreelementsofarelationaldatabase,SQLsupportstheactualimplementationofthiskindofdatabase.

SQL,oneofthemostpopularlanguagestoday,isnotsimilartootherprogramminglanguages(e.g.Java,C,C++,etc.).Mostprogramminglanguagesareprocedural,whichmeanstheydefinehowaprogrammustperformitsfunctions.SQL,whichisanon-procedurallanguage,focusesontheresultsofaprogram’sfunctions.Thesoftwareenvironmentyou’reusingwilldeterminethedatabaseapplicationthatwillcompleteitstasks.

TheSQLlanguagelackstheprogrammingfeaturesofotherlanguages.ThisisthereasonwhysomeprogrammersrefertoSQLasa“sublanguage.”Basically,youwilluseSQLwithotherlanguages(e.g.C#)toperformtasks.

TheSQLStatements

SQLhasdifferenttypesofstatementsthatyoucanuseinmanagingadatabase.Inthissection,let’sdivideSQLstatementsaccordingtotheirfunctions:

DDL(i.e.DataDefinitionLanguage)–Thesestatementsallowyoutogenerate,delete,ormodifydatabaseobjects(e.g.schemas,triggers,tables,etc.).ThemostpopularstatementsofthiscategoryareCREATE,DROP,andALTER.Forinstance,youmustuse“CREATETABLE”togenerateanewtable,“ALTERTABLE”tochangethepropertiesofatable,and“DROPTABLE”toremovetheinformationregardingatablefromyourdatabase.

DCL(i.e.DataControlLanguage)–Withthesestatements,youcanspecifythepeopleorprogramsthatcanaccesstheobjectsinsideyourdatabase.UsingDCL,youmaygiveortakeawayaccessusing“GRANT”or“REVOKE,”respectively.YoucanalsouseDCLstatementstomanagethekindofaccessdatabaseusershavetoyourinformation.Forinstance,youmaysetwhichdatabaseuserscaneditacertainblockofdata.

DML(i.e.DataManipulationLanguage)–ADMLstatementallowsyoutoadd,modify,delete,orretrieveinformationstoredinsideyourdatabaseentries.ThemainkeywordsoftheDMLcategoryare:UPDATE,SELECT,DELETE,andINSERT.Youmayuse“SELECT”toretrieveinformationfromadatabasetableand“INSERT”toaddinformation.

TheDifferentExecutionTypes

TheSQLlanguagehasdifferentbindingstyles(orexecutionmethods).Thesemethodsdon’tjustinfluencetheexecutionofthestatements:theyalsodeterminewhichSQLstatementwillworkwithanygivenbindingstyle.Herearethefourexecutionmethodsthatyou’llencounterwhileusingSQL:

DirectInvocation–Thismethodallowsyoutocommunicatewithadatabaseusingafront-endprogram(e.g.ManagementStudio,iSQL*Plus,etc.).YoumayenteryourdatabasequeriesintotheprogramandruntheSQLstatement.Yourcomputerwillreturnthesearchresultsaftersometime(thetimeframeinvolveddependsonyourmachine’scomputingpower).SQLusersconsiderthisasanexcellentwaytoviewinformation,checkrelationships,andverifydatabaseentries.

ModuleBinding–Withthismethod,youcangeneratesetsofSQLcommandsthatareseparatefromyourmainprogramminglanguage.Onceyouhavecreatedacommandset,youmayincorporateitintoadatabaseprogramusingalinker.Commandsets(alsoknownas“modules”)hold“procedures,”whichcontaintheSQLcommandsyou’reworkingwith.

EmbeddedSQL–Withthisbindingstyle,youwillencode(embed)SQLstatementsinthemainprogramminglanguage.Forinstance,youmayencodeanSQLstatementinsidethesourcecodeofaC#program.Beforecompilingthecode,apreprocessorwillanalyzetheSQLcommandsandseparatethemfromtheC#statements.Then,thepreprocessorwillconverttheSQLcommandsintoaformatthatthedatabasemanagementsystemcanread.TheC#codewillworkasnormal.

CLI(i.e.Call-LevelInterface)–YoucanusethisbindingstyletoexecuteSQLstatementsusinganinterface.Here,youwillpassSQLcommandsasargumentstooneormoresubroutines.Thesystemwon’tprecompileSQLstatementsasitdoesinmodulebindingandembeddedSQL.Rather,thedatabasemanagementsystemwillrunthesaidstatementsdirectly.

ImportantNote:Theexamplesyou’llfindlaterinthisbookwillusedirectinvocation.That’sbecausethisbindingstyleiscompatiblewithadhocdatabasequeriesandproducesresultsimmediately.

Chapter2:TheEnvironmentoftheSQLLanguage

ThischapterwillfocusontheSQLenvironment.Itwillexplainlanguagecatalogsandteachyouhowtocreatedatabasesandschemas.Readthismaterialcarefully:itwillhelpyoulearntheSQLlanguageinjustoneday.

SQL’sEnvironment–TheBasics

Theenvironmentofthiscomputerlanguageisthetotalityoftheelementsthatformthatenvironment.AlloftheseelementsworktogethertoperformSQLfunctionalitiessuchasqueryingandstoringinformation.Whencombined,theseelementscreateabasestructurefordatabasemanagementsystems.

SQL’senvironmentconsistsofsixdifferentelements.TheSQLserver/sandSQLclient/sbelongtotheimplementationofthelanguage:databaseusersconsiderthemasmeresubtypes.

Let’sdiscusstheseelementsindetail:

SQLAgent-ThisisthestructurethatexecutesSQLstatements.ThiselementcanonlyworkwithinthelimitsoftheSQLclientusedintheimplementation.

AuthorizationIdentifier–Thiselementrepresentsrolesorusersthatcanaccessthedataandobjectsinsidetheenvironment.“Users”refertothesecurityaccountsthatrepresentapplications,people,orsystemservices.“Roles,”ontheotherhand,aresetsofpredeterminedaccessprivilegesthatyoumayassigntousersorotherroles.

SQLImplementation–ThisistheelementthatrunsSQLcommandsaccordingtotheSQLagent’sneeds.An“implementation”involvesaclientandaserver.Here,theclientwillconnecttotheserverandkeepinformationthatisrelevanttotheinteractionsbetweentheformerandthelatter.Meanwhile,theserverwillmanagethesessionthatoccursduringtheconnectionandrunSQLcommandssentbytheclient.

ClientModule–AmoduleisasetofSQLcommandsthatyouwroteseparatelyfromanotherprogramminglanguage.Itholdsvaryingnumbersofexternallytriggeredprocesses,witheachprocessconsistingofoneSQLcommand.TheclientmoduleofSQLexistsinsidetheenvironmentandrunsthroughthelanguage’simplementation.

RoutineMapping–ThiselementlinksSQL-triggeredroutineswithforeignserverdescriptors.

UserMapping–Withthiselement,youcanpairauthorizationidentifierswithforeignserverdescriptors.

Site–AsiteisacollectionoftablesthatholdSQLinformationasdefinedbytheschemas’contents.SQLusersrefertotheinformationwithinasiteas“adatabase.”

Catalog–Thiselementisasetofschemasgroupedtogetherwithinaparticularnamespace.Catalogsholdthedataschema,whichinvolvesthedescriptorsofdifferentschemaobjects.

ImportantNote:Schemasarecontainersfordataobjects(e.g.domains,tables,views,etc.).You’lllearnaboutthistopicinthenextsection.

MoreDetailsAboutSQLCatalogs

Asstatedearlier,theenvironmentofSQListhecombinationofalltheelementsthatformthatenvironment.Well,SQLcatalogsinvolvethesamelogic.SQLcatalogsaregroupsofschemas;ifyou’llcombinetheseschemas,youwillbeabletodefinenamespacesinsidetheenvironmentofSQL.

ImportantNote:NamespacesarenamingstructuresthatindicaterelatedelementsinagivenSQLenvironment.Databaseusersoftendepictanamespaceasanupsidedowntree.Thisimagerepresentsthehierarchical(i.e.parent-child)relationshipsofdataobjects.

YoumayalsothinkofSQLcatalogsashierarchicalstructureswiththecatalogsasthetop-level(i.e.parent)objectsandschemasasthesub-level(i.e.child)objects.

TheSchemas

You’llfindschemasineachSQLcatalog.Schemasaregroupsofrelateddataobjectsthatbelongtothesamenamespace.Schemasserveascontainersfortheseobjects.KeepinmindthateachobjectstoresSQLinformationorconductinformation-relatedprocesses.Theschemas,theobjectstheycontain,aswellasthedatainsidethoseobjects,belongtotheauthorizationidentifierlinkedwiththoseschemas.

TheInformationSchema

AllSQLcatalogscontain“INFORMATION_SCHEMA,”whichisoneofthemostspecialschemasinthiscomputerlanguage.The“INFORMATION_SCHEMA”holdsinformationregardingdifferentschemaobjects(whichare“views”mostofthetime).Viewsarevirtualtablesthatallowyoutoseeinformationgatheredfromrealdatabasetables.Usingaview,youmayshowthedataaboutobjectswithinthatSQLcatalogasifitisSQL-basedinformation.

SchemaObjects

You’llfindschemaobjectsatthelowestportionoftheSQLcatalogstructure.Aschemaobjectisagroupofrelatedelementsthatexistinsideaschema.Thisleveloffunctionalityistheoneinvolvedindatastorage.Thus,youneedtobefamiliarwithitifyouwanttobeasuccessfulSQLprogrammer.YoucanusetheSQLlanguagetodefineanobject,changethatdefinition,andsaveand/oralterinformationinsidethatobject.Actually,almostallofthethingsyouwillbereadingfromhereonhasaconnectionwithschemaobjects.

Herearetheschemaobjectsthatyou’llencounterwhileusingSQL:

View–Youcaninvokethisschemaobjecttocreatevirtualtables.Thetableswon’treallyexist–thedatabasewilljustrunandstoretheSQLcommandthatdescribesthosetables.Afterinvokingthecommand,theviewwillpullinformationfromabasetableandshowtheresultsofyourqueryasifyou’relookingatanactualbasetable.

BaseTable–ThisisthebasicdataunitinSQL.Abasetableconsistsofrowsandcolumnsandissimilartotherelationaltheory’s“relation”(i.e.withitstuplesandattributes).Thecolumnsarelinkedwithdatatypesandcontainrelatedvalues.Forinstance,abasetableforbookswillhavecolumnsthatholdinformationaboutthosebooks(e.g.titles,authors,genres,etc.).

Domain–Youmayspecifythisobjectwhiledefiningcolumns.Domainsrelyonthedatatypespecifiedbytheuser,butmayholdconstraintsanddefaultvalues.Constraintshelpyouinlimitingtheinformationthatacolumncanstore.

UDT(User-DefinedType)–SQLallowsyoutospecifyaUDTwhilecreatingacolumn.TheSQLlanguageofferstwokindsofuser-definedtypes:structuredanddistinct.Astructuredtypeconsistsofdifferentattributevalues.Adistincttype,ontheotherhand,iscompletelybasedonadatatypeofSQLanditsvalues.

Constraint–Thisisalimitationthatyouneedtoplaceonadomain,table,orcolumntorestrictthekindofinformationthatyoucanaddtothedatabaseobjectyou’reworkingon.Forinstance,youmayuseaconstrainttomakesurethataparticularcolumncanonlyholdnumberswithinacertainrange.

ServerModule–ThisschemaobjectholdsSQL-triggeredroutines.Basically,amodulecancontainroutines,procedures,orSQLcommands.AnSQL-triggeredroutineisaprocessorfunctionthatyoucaninvokefromtheSQLlanguage.KeepinmindthatprocessesandfunctionsarekindsofSQLcommandsthatmayacceptparameters(i.e.thevaluesyou’llgivetoacommandwhileinvokingit).Functionsmayreceiveparametersandreturnvaluesdependingontheinformationincludedintheirstatement.Processes(alsoknownas“procedures”)maytakevaluesandgiveoutparameters.

Trigger–Thisisanobjectlinkedwithatable.Itspecifiestheaction/sthatthesystemmustperformwhensomethinghappenstothetableitisassociatedwith.Thedatabaseactionsthatcanactivatethe“trigger”aretableupdates,deletions,anddatainsertions.Forinstance,ifyou’lldeletearowfromonetable,youmightactivateatriggerthatdeletesinformationstoredinadifferenttable.

SQL-TriggeredRoutine–ThisisaprocessorfunctionthatyoucancallfromSQL.Ingeneral,thiskindofroutinecantaketheformofastand-aloneschemaobjectoramodule-dependentobject.

CharacterSet–Thissetofattributesspecifieshowthedatabasemustrepresentcharacters.Charactersetshavethreedifferentattributes,namely:form-of-use,defaultcollation,andrepertoire.The“form-of-use”attributespecifieshowcharacterswillappearasdatastringstosoftwareand/orhardware.“Defaultcollation”specifieshowthedatabasewillcomparestrings.Finally,the“repertoire”attributespecifiesthecharactersthatthesystemcanexpress.

Collation–Thisthecollectionofrulesthatdeterminehowadatabasemustcomparestringsthatareinsideasinglerepertoire.Youcanusethisinformationtoarrangethecharacters.InSQL,youneedtodefinedefaultrulesforallofyourcharactersets.

Transliteration–Basically,transliterationsareSQLoperationsthatmapthecontentsofacharactersettothecontentsofadifferentset.TransliterationsmayinvolveotherSQLoperationssuchascharactertranslations(i.e.fromlowercasetouppercase).

SequenceGenerator–Thisisamechanismthatyoucanusetogenerateconsecutiveintegers.Asequencegeneratorstoresthecurrentvalue-thatvaluewillbeusedingeneratingothersequencesofvalues.

HowtoNameDatabaseObjects

Theprevioussectionsfocusedontheoreticalandsupportinginformation.ThisapproachofexplainingtheSQLlanguageaimstohelpyoumasterthebasicsofSQL.Thisway,youwillbeabletounderstandSQLstatementsonceyou’reinthatpartofthebook.Atthispoint,there’sjustonemorefundamentaltopicthatyouneedtostudy–theobjectidentifiers.Identifiersarenamesthatyou’llassigntoSQLobjects.Inthiscomputerlanguage,anobject’snamecanhaveupto128characters.Inaddition,eachnameshouldfollowthepredeterminedconventions.Youmayassignanidentifiertoanydatabaseobject(e.g.views,tables,schemas,etc.)thatyouwillgeneratewithSQLcommands.

Acommonidentifierisrestrictiveandneedstofollowtherulesgivenbelow:

Itisnotcase-sensitive.ThatmeansBook_TitleisidenticaltoBOOK_TITLE.

Itcancontainunderscores,lettersandnumbers.Forinstance,youmaycreateFirst_Bookand1st_Bookasthenameofyourviews.Asyoucansee,youneedtouseanunderscoretoseparatewords.Youcan’tusespacesordasheswhilenamingSQLobjects.Actually,thislanguagetreatsadashasthe“subtractionoperator”(youwilllearnabouttheoperatorslater).

Itcannotcontainanyreservedkeywordofthelanguage.

ImportantNote:Keywordsarewordsthathavespecialfunctionsinacomputerlanguage.InSQL,keywordsmaybelongtooneofthesecategories:reservedandnon-reserved.Asitsnamesuggests,youcan’tuseareservedkeywordasidefromthefunctionitisintendedtobeusedforinanSQLcommand.Anon-reservedkeyword,ontheotherhand,doesn’thaveanyrestriction.

Thislanguageis“caseinsensitive”whenitcomestocommonidentifiers.Actually,itwillchangeidentifierstouppercasewhilestoringthem.ThisisthereasonwhySQLconsidersFirst_BookandFIRST_BOOKasidenticalnames.

A“delimitedidentifier”isnotasstrictasacommonidentifier.However,itshouldstillfollowcertainrules.Theserulesare:

Thenameshouldbeinsideapairofdoublequotes(e.g.“First_Book”).

Thedatabasewon’tstoreanyquotationmark.However,itwillstoretheidentifiersasyouwrotetheminyourSQLcommands.

Itiscase-sensitive.Thatmeans“First_Book”and“FIRST_BOOK”aretwodifferentnames.However,“FIRST_BOOK”andFirst_Bookareidentical(sinceSQLconvertsallregularidentifierstouppercase).

Youmayuseanycharacter.

Youcanuseanyword,eventhereservedkeywordsofSQL.

QualifiedIdentifiers

SQLqualifiestheidentifierofeachschemaobjectbasedonitspositionintheenvironment’shierarchicalstructure.Aqualifiedidentifiercontainsthenameoftheobject,schemaandcataloginvolved(i.e.youneedtoseparatethesevaluesusingperiods).Forinstance,let’sassumethatyou’reworkingonatablecalledBook_Authors.ThistableislocatedinaschemanamedBook_List,whichisstoredintheBookcatalog.ThequalifiedidentifierforthistableisBook.Book_List.Book_Authors.

HowtoGenerateaSchema

Atthispoint,you’vebecomefamiliarwiththenamingconventionsoftheSQLlanguage.It’stimetowriteSQLstatements.Let’sstartwith“CREATESCHEMA”sinceschemasaretop-levelobjectsintheSQLstructure.Whilelearninganewcomputerlanguage,youshouldalwaysbeginwiththesyntaxofthestatementsbeingdiscussed.HereisthesyntaxofCREATESCHEMA:

CREATESCHEMA{identifierclause}

[{thepathorcharacterset}]

[{theelementsoftheschema}]

ImportantNote:Thecurlybracesholddatathatrepresentsaclauseorvalueassociatedwiththatdata.Forinstance,{identifierclause}representsthevaluesandkeywordsyouusedinnamingthenewschema.Thebrackets,however,signifytheoptionalclausesofthesyntax.SQLdoesn’trequireyoutosetpaths,schemaelements,orcharactersetswhilecreatingaschema.

Let’sanalyzethissyntaxindetail.Here,“CREATESCHEMA”arekeywordsthatinformSQLregardingthetaskyouwanttocomplete.Thesekeywordscomebefore{identifierclause},whichisaplaceholderthatcontainstheschema’sname.InSQL,youmayaddanauthorizationidentifiertoyourCREATESCHEMAstatements.YoucandothisjustbyaddingAUTHORIZATION(i.e.anotherSQLkeyword)totheidentifierclauseofyourcommand.Thus,theidentifierclausemaytakeanyoftheseforms:

{schemaidentifier}

AUTHORIZATION{nameoftheauthorization}

{schemaidentifier}AUTHORIZATION{nameoftheauthorization}

The{nameoftheauthorization}partspecifiestheowneroftheschema.Ifyouwon’tspecifyanyvalue,thesystemwillassumethattheowneristhecurrentdatabaseuser.Ifyoudidn’tincludeaschemaidentifier,thesystemwillusethenameofyourauthorizationtogeneratethemissinginformation.

Thenextpart,{thepathorcharacterset},letsyouassigndefaultpaths,charactersets,orboth.YoushouldtypeDEFAULTCHARACTERSETbeforethecharactersetthatyouwanttouse.Thepath,ontheotherhand,setsasearchpatternforSQL-triggeredroutines(i.e.functionsandprocedures)thataregeneratedthroughtheCREATESCHEMAcommand.

ThefinalclauseofthesyntaxconsistsofdifferentkindsofSQLcommandsthatyoumayaddinthecurrentstatement.Inmostcases,youcanusethisclausetogeneratevarious

schemaobjects(e.g.domains,triggers,tables,etc.).Themainbenefitofthisfeatureisthatyoucanaddobjectstoyourschemaduringthecreationprocess.

Now,let’sdiscussanexampleofthiskindofstatement.Thecodegivenbelowgeneratesanewschemacalled“LIBRARY.”Also,itwillsetUSERastheauthorizationidentifierandLatin2asthecharacterset.

CREATESCHEMALIBRARYAUTHORIZATIONUSER

DEFAULTCHARACTERSETLatin2

CREATETABLEFICTION

(AUTHOR_IDINTEGER,AUTHOR_NAMECHARACTER(25));

Asyoucansee,thisexamplecreatesatablecalled“FICTION.”Thisisanelementthatyoucanspecifyinsidethelastclauseofthesyntax.Keepinmindthattherearenolimitsregardingthestatementsthatyoucanadd.Thestatementgivenabovegeneratesatablethathastwocolumns:AUTHOR_IDandAUTHOR_NAME.

CreatingaNewDatabase

TheSQLlanguagedoesn’thaveacommandforcreatingadatabase.However,youwilllikelyuseanRDBMS(i.e.relationaldatabasemanagementsystem)thatsupportsthegenerationofdatabaseobjectsandtheutilizationofthoseobjectsinmanaginginformation.Forthisreason,ifyouwanttotakeadvantageoftheprojectsandsamplesincludedinthiseBook,youneedtogenerateasampledatabase.Withthisapproach,youmaymanipulateinformationwithoutlosingimportantdatafromarealdatabase.

Mostdatabaseproductssupportcommandsthatcreatedatabaseobjects.Forinstance,MySQL,SQLServer,andOraclehave“CREATEDATABASE”intheirbuilt-inSQLlanguages.However,theparametersyoucandefine,thepermissionsyouneedinexecutingthecommand,andhowsystemsimplementadatabaseobjectdifferfromonedatabaseproducttoanother.Fortunately,almostalldatabaseproductsutilizethesamesyntaxtogeneratedatabaseobjects:

CREATEDATABASE{nameofthedatabase}

{extraparameters}

Beforegeneratinganydatabase,youneedtoreadthedocumentationoftheproductyou’reusing.Additionally,talktothedatabaseadministratorstomakesurethatyoucanadddatabasestoyourSQLenvironment.Aftercreatingadatabase,youmaygenerateschemas,views,tables,andotherkindsofobjectsinthatdatabase.Then,youmaystartpopulatingthetableswiththeappropriateinformation.

Chapter3:HowtoGenerateandModifyTables

InSQL,tablesserveastheprimarytoolformanagingdata.Almostalloftheprogrammingyou’lldoislinkedtooneormoretables.Consequently,priortoinsertingdataintoadatabase,youneedtomakesurethatthecorrecttablesexist.

ThischapterwillteachyouhowtogenerateandmodifyanSQLtable.Readthischaptercarefully–itwillhelpyoulearnSQLinjust24hours.

GeneratinganSQLTable

Thiscomputerlanguagesupportsthreekindsoftables:(1)basetables,(2)derivedtables,and(3)viewedtables.AccordingtoSQLusers,abasetableisusuallyaschemaobjectthatcontainsSQLinformation.Aderivedtable,ontheotherhand,istheresultthatyou’llseewhenqueryinginformationfromadatabase.Lastly,aviewedtableisadifferentnamefora“view,”withthedefinitionsavedinsidetheschema.

Thissectionwillfocusonbasetables.Actually,almostallofthesamplesandprojectsyou’llseeinthiseBookinvolvebasetables.However,basetableshavedifferentcharacteristics.Sometablesarepermanent(alsocalledpersistent)whileothersaretemporary.Therearemodule-basedtablesandtherearedataobjects.Allmodule-basedtablesaretemporary.Herearethebasetablesthatyou’llencounterwhileusingSQL:

PersistentBaseTable–YoucandefinethisschemaobjectusingtheCREATETABLEcommand.ApersistentbasetablecontainstheSQLinformationyoustoredinadatabase.Thiskindofbasetableisextremelypopular.Actually,peopleoftenrefertoapersistentbasetablewhenevertheytalkabout“tables”or“basetables.”Thistablewillexistwhileitsdefinitionexists.Inaddition,youcancallitfromanysession.

DeclaredLocalTemporaryTable–Youwilldeclarethistableasaprocessinsideamodule.Thedefinitionofthetableisn’tstoredwithintheschema.Also,itwon’texistuntiltheprocedureruns.Justlikeanytemporarytable,youcanonlyuseadeclaredtemporarytableduringthesessionyou’vecreateditin.

CreatedLocalTemporaryTable–Tocreatethistable,youneedtousetheCREATELOCALTEMPORARYTABLEcommand.Youcanonlyusethiskindoftableduringthesessionitwascreatedin.Additionally,youneedtobeinsidethecorrectmoduleinordertoaccessthistable.

GlobalTemporaryTable–YoumustusethecommandCREATEGLOBALTEMPORARYTABLEtogeneratethisschemaobject.Eventhoughitsdefinitionbelongstotheschema,thetablewillonlyexistifreferencedinsidethesessionitwascreatedin.Thatmeansthetablewilldisappearassoonastherelatedsessionends.Thistemporarytableiscalled“global”becauseitallowsyoutouseitscontentsatanypartofthecurrentsession.

ImportantNote:InSQLprogramming,“sessions”refertotheconnectionsbetweenSQLagentsanddatabaseusers.Duringasession,theuserwillinvokeasetofconsecutivecommands.Ontheotherhand,amoduleisadatabaseobjectthatholdsroutines,processes,orSQLcommands.You’lllearnmoreaboutmodulesinlaterchapters.

Keepinmindthatyoucanuse“CREATETABLE”togenerateanykindofbasetableexceptalocaltemporaryone.Theremainingpartofthischapterwillfocusonpermanentbasetables.HereisthesyntaxoftheCREATETABLEcommand:

CREATE{[LOCAL|GLOBAL]TEMPORARY}TABLE<nameofthetable>

<(elementofthetable){[,(elementofthetable)]…}>

{ONCOMMIT[DELETE|PRESERVE]ROWS}

ImportantNote:Youshouldreadthepipesymbol(i.e.“|”)as“or.”Thus,youmustchooseoneofthetwooptionsgivenforeachappropriateclause.

Forthesyntaxgivenabove,thecurlybracesgroupdataelementstogether.TheinitiallineofthatformatgroupstheLOCAL|GLOBALkeywordstogether.Here,youmustdecidehowyouwillmanagethecontentsofthebracesandknowhowtheycanfunctionintheclause.Forthefirstpartofthesyntax,youneedtochooseeitherLOCALorGLOBALwithTEMPORARY,butthisisoptional.

Thethreedotsyouseeinthenextlineshowthatyoumayrepeatthatpartasmanytimesasyouneed.Thatmeansyoucanaddanynumberof“(elementofthetable)”clausestoyourcommand.

Inthefirstpartofthecurrentsyntax,youmayindicatewhetheryouwantatemporarytableorapermanentone.Youcanalsosetthetable’sname.Thus,youmayuseonethesevariants:

CREATETABLE(thetable’sname)

CREATEGLOBALTEMPORARYTABLE(thetable’sname)

CREATELOCALTEMPORARYTABLE(thetable’sname)

Thenextpartoftheformatletsyoudeterminetheelementsthatformthetable(you’lllearnaboutthatlater).Thefinalline,however,appliestotemporarytablesonly.YoucanusethislinetosetwhetherthenewtablewilldeleteallofitscontentsoncetheCOMMITcommandruns.YoucanusetheCOMMITcommandtoimplementmodificationstoyourdatabase.

Youmayconsiderthe(elementofthetable)clause/sasthemainpartoftheCREATETABLEcommand.Thispartallowsyoutodefinetheelements(e.g.constraints,columns,etc.)ofthetableyouwanttocreate.InSQL,youmaydefineanynumberof“(elementofthetable)”clauses.Ifyouwilldefinemultipleclauses,youneedtoseparatetheentriesusingcommas.

Let’sanalyzethesyntaxfordefininganewcolumn:

(thecolumn’sname)[(domain)|(typeofdata)]

{(thedefaultclause)}{(thecolumn’sconstraint)}{COLLATE(thecollationidentifier)}

Thesyntax’sinitiallinerequiresyoutosetthecolumn’snameandchooseadomainordatatype.You’lllearnhowtospecifythedatatypesofyourcolumnslaterinthischapter.Thenextline,however,allowsyousetacollation,adefaultvalue,orcolumnconstraints.

Here’sabasicexampleoftheCREATETABLEcommand:

CREATETABLEAUTHORS

(AUTHOR_IDINTEGER,

AUTHOR_NAMECHARACTER(50));

ThiscommandcreatesatablecalledAUTHORSandtwocolumns.ThenameofthefirstcolumnisAUTHOR_IDwhilethatofthesecondoneisAUTHOR_NAME.TheformerislinkedwiththeINTEGERtypeofdata.Thelatter,ontheotherhand,belongstotheCHARACTERtype.Asyoucansee,youneedtouseacommatoseparatecolumndefinitions.

Youprobablynoticedthatthecolumndefinitionsarelocatedindifferentlinesandthattheyarealignedbecauseofextraspaces.ThisstyleofwritingSQLstatementshelpyouinimprovingthereadabilityofyourcodes.TheSQLlanguagedoesn’trequirethesespacesofnewlinecharacters.However,youshouldusethisstyleasmuchaspossible.

Ifyouwillrunthecommandgivenabove,youwillseeatablethatlookslikethis:

AUTHOR_ID:INTEGER

AUTHOR_NAME:CHARACTER(50)

1001 StephenKing

1002 ArthurConanDoyle

1003 E.L.James

1004 CharlesDickens

ImportantNote:Youwon’tseeanydataentryinsidethenewtable.Theinformationshowninthisexampleareincludedtohelpyouunderstandwhatkindoftablethecurrent

commandcreates.

Atthispoint,let’sdiscusshowyoucanspecifythedatatypeofyourcolumns.Youneedtomasterthistopicsincedatatypesplayanimportantroleinthecreationofanycolumn.

SpecifyingtheDataTypeofaColumn

Whendefiningacolumn,youshouldalwayssetitsnameandassociateddomainordatatype.Thedomainanddatatypelimittheinformationthatthecolumncanaccept.Forinstance,certaindatatypesrestrictthevaluesofacolumntonumerals.InSQL,adatatypebelongstooneofthesecategories:

Predefined–Thesedatatypesareextremelypopular.Basically,apredefineddatatypeisanelementthatrestrictsvaluesbasedonthecriteriasetforthedatabase.Thiscategoryconsistsoffivedatatypes,namely:string,interval,numeric,Booleananddatetime.

Constructed–Aconstructeddatatypecancontainmultiplevalues.Thus,thedatatypesyou’llfindinthiscategoryaremorecomplexandpowerfulthantraditionalones.

User-Defined–Auser-defineddatatypeisbasedonapredefinedattributedefinitionordatatype.YouneedtoaddittoyourSQLenvironmentasaschemaobject.InSQL,auser-defineddatatypecaneitherbestructuredordistinct.Astructureddatatypeusesanattributedefinitionasitstemplate.Adistincttype,ontheotherhand,requiresapredefinedtypeasatemplate.

Let’sdiscusseachdatatypeindetail:

TheStrings

Astringdatatypeallowsyoutosetvaluesaccordingtodatabitsorcharactersets.Thevaluesyouusemaybefixedorvaryinginlength,dependingonthedatatypeyouarecurrentlyusing.InSQL,thestringdatatypehasfoursubtypes:

CharacterString–Withthissubtype,youmustchoosetheallowedvaluesfromacertaincharacterset.Youmayuseadefaultsetoronethatyouhavedefinedwhilecreatingthecolumn.

NationalCharacterString–Thissubtypeissimilartothecharacterstring.Theonlydifferenceisthatyoushoulduseacharacterthedatabaseimplementationhasdefined.Consequently,whenyouspecifythissubtype,thevaluesyou’redealingwithshouldbecompatiblewiththecharactersspecifiedbyyoursystem.SQLusersutilizeanationalcharacterstringtostoredataindifferenthumanlanguages(e.g.English,French,Italian,etc.)withinasingledatabase.

BitString–Here,youshouldbaseyourpermittedvaluesonbinarydigits(i.e.databits)insteadofcollationsorcharactersets.Thatmeansthissubtypecanhandlezeroesandonesonly.

BinaryString–Abinarystringhasmanysimilaritieswithabitstring.Themaindifferenceisthattheformerusesbytes(notbits)inspecifyingtheallowedvalues.Eachbyteisequivalenttoeightbits,whichisthemainreasonwhySQLusersrefertobytesas“octets.”

TheDatetimeType

Youcanusethisdatatypetotracktimesanddates.TheSQLlanguagesupportsthreekindsofdatetimedatatypes:

Date–Thissubtypespecifiesadate’sday,month,andyearvalue.Thedayvaluehastwodigitsandgoesfrom01to31;themonthvaluehastwodigitsandgoesfrom01to12;andtheyearvaluehasfourdigitsandgoesfrom0001to9999.

Time–Youcanusethissubtypetospecifyatime’ssecond,minute,andhourvalue.Allofthesevalueshavetwodigits.Thesecondvaluegoesfrom00to61.999(takingthe“leapseconds”intoaccount);theminutevaluegoesfrom00to59;andthehourvaluegoesfrom00to23.

Timestamp–ThissubtypecombinesthedataofDATEandTIME.ItusessixfractionaldigitsforthevalueofTIME.Tochangethenumberoffractionaldigits,youjusthavetoindicatethenumberyouwanttouseasaparameter(e.g.TIMESTAMP(5).

Interval

Thisdatatypehasacloserelationshipwiththedatatimetype.Basically,youwilluseanintervaldatatypetoshowthedifferencebetweendifferentdatetimevalues.TheSQLlanguagesupportsthefollowingsubtypes:

Day-TimeIntervals-Withthissubtype,youcanspecifytheintervalbetweenthesevalues:seconds,minutes,hours,ordays.

Year-MonthIntervals–Usethissubtypetospecifytheintervalbetweenmonths,years,orboth.

TheBooleanType

ProgrammersconsiderBooleanvaluesaseasyandstraightforwardpiecesofinformation.TheBooleantypeusesatrue/falseformatthatacceptsthreevaluesonly:unknown,false,andtrue.Nullvaluesevaluatetounknown.Inthiscomputerlanguage,you’llusenullvaluestoexpressunknownorundefinedvalues.

YoumayuseBooleanvaluesinyourSQLexpressionsandqueriestoperformcomparisons.ComparisonsinvolvingBooleaninformationfollowthislogic:

A“true”hasahighervaluethana“false.”

Youwillget“unknown”ifyouwillperformacomparisoninvolvinganullvalue.

Youcanassign“unknown”tocolumnsthatsupportit.

Tousethisdatatype,youshouldtypeBOOLEANwithoutanyparameter.Here’sanexample:

BOOK_HAS_SEQUELBOOLEAN

ThecolumnnamedBOOK_HAS_SEQUELwillrejectvaluesthatarenot“unknown,”“false,”or“true.”

TheNumericType

Asitsnamesuggests,thenumericdatatypespecifiesnumbersasallowedvalues.Thistypehasascaleandaprecision.The“scale”isthetotalnumberofintegersfoundinthefractionalpartofavalue.The“precision,”ontheotherhand,isthenumberofintegersthatyoucanstore.Forinstance,thescaleandprecisionof9.999is3and4,respectively.Keepinmindthatavalue’sscaleshouldalwaysbepositiveandlowerthantheprecision.Ifthescaleofyourvalueiszero,youaredealingwithawholenumber(i.e.anumberthatdoesn’thaveanyfractionalpart).

TheSQLlanguagesupportstwosubtypesofthenumericdatatype.Thesesubtypesare:

ExactNumeric–Whenusingthissubtype,yourpermittedvaluesmusthaveascaleandaprecision.

ApproximateNumeric–Thissubtypedoesn’tacceptscales.Thus,yourallowedvaluesmayhavea“floating”decimalpoint.Floating-pointvaluesarenumbersthathaveadecimalpoint,buttheplacementofthatdecimalpointisnotimportant.Thisisthereasonwhyanapproximatenumericdatatype“doesn’ttakeascale.”

HowtoUsetheDataTypesofSQL

Inthispartofthebook,you’lllearnhowtosetthedatatypeofnewcolumns.Here,youwillstillusetheCREATETABLEcommand.Analyzethefollowingexample:

CREATETABLEAUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50),

AUTHOR_DOBDATE,

BOOK_IN_STOCKBOOLEAN);

ThecolumnnamedAUTHOR_IDwilltakevaluesthatbelongtothenumerictype;theonenamedAUTHOR_NAMEtakesstringvalues;theAUTHOR_DOBcolumnacceptsdatetimevalues;andtheBOOK_IN_STOCKcolumntakesBooleandataonly.

HowtoSpecifytheDefaultValueofaColumn

OneofthemostpowerfulfeaturesofSQListhatitallowsyoutosetthedefaultvalueofanewcolumn.Youshouldusethisfeaturewhilecreatingatable(i.e.whileissuingCREATETABLE).Hereisthesyntaxthatyoushouldusewhilesettingacolumn’sdefaultvalue:

(nameofcolumn)(typeofdata)DEFAULT(thedefaultvalue)

The(typeofdata)and(nameofcolumn)parts,whichyou’veencounteredearlier,comebeforetheSQLkeywordDEFAULT.Afterthatkeyword,youneedtospecifythevalueyouwanttosetasdefault.Whensettingadefaultvalue,youmayusealiteral(i.e.adatavalueofSQL),auserfunction(i.e.onethatgivesuser-relateddata),oradatetimefunction.

Regardlessofthevalueyousetfor(thedefaultvalue),youshouldmeettherequirementsofyourchosendatatype.Forinstance,ifyousetacolumnsothatitacceptsnumericvaluesonly,youcan’tset“unknown”asitsdefaultvalue.

Intheexamplefoundbelow,you’lluseCREATETABLEtogenerateatablecalledAUTHORS.

CREATETABLEAUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50),

PLACE_OF_BIRTH-CHARACTER(50DEFAULT‘NULL‘);

Asyoucansee,thecolumncalledPLACE_OF_BIRTHhas‘NULL’asitsdefaultvalue.Thisvalueworkssinceitmeetstherequirementsofyourchosendatatype(i.e.CHARACTER).Inaddition,apairofsinglequotationmarksenclosethevalueinvolved.

ImportantNote:Ifyouwillinsertanewentryandyoudon’twanttopopulatethePLACE_OF_BIRTHcolumn,thesystemwillenterNULLonyourbehalf.

HowtoAlteranSQLTable

Thispartofthebookwillteachyouanewcommand,whichisALTERTABLE.Youcanusethiscommandtoalterthebasetablesinsideadatabase.Thebasicsyntaxofthiscommandis:

ALTERTABLE(nameoftable)

ADD{COLUMN}(definitionofcolumn)

|ALTER{COLUMN}(nameofcolumn)

[DROPDEFAULT|SETDEFAULT(thedefaultvalue)]

|DROP{COLUMN}(nameofcolumn)[RESTRICT|CASCADE]

Thissyntaxletsyouperformoneoftheseactions:insertingacolumn,alteringacolumn,ordroppingacolumn.

ImportantNote:Youcanalsousethiscommandtoremoveorinserttableconstraints.Basically,tableconstraintsarerulesthatlimitwhatinformationyoucanenterintoatable.Theyarepartofatable’sdefinition.However,theydon’tbelongtospecificdefinitionsofcolumns.

The(definitionofcolumn)partofthesecondlinehassomesimilaritieswiththeoneusedinCREATETABLE.Youneedtosetthecolumn’snameanddomain/datatype.Additionally,youmayaddacollation,constraint,ordefaultclause.Forinstance,youmayusethecodebelowtoinsertanothercolumn(i.e.AUTHOR_DOB)tothetablecalledAUTHORS:

ALTERTABLEAUTHORS

ADDCOLUMNAUTHOR_DOBDATE;

Thethirdlineofferstwopossibleactions:removingthedefaultvalueorsettinganewone.Asanexample,let’sassumethattheAUTHOR_DOBcolumnhasnodefaultvalue.Youmayusethefollowingcodetoassignadefaultforthatcolumn:

ALTERTABLEAUTHORS

ALTERCOLUMNAUTHOR_DBSETDEFAULT‘N/A‘;

Toremovethedefaultvalue,usethiscommand:

ALTERTABLEAUTHORS

ALTERCOLUMNAUTHOR_DOBDROPDEFAULT;

Thelastlineofthesyntaxofferstwochoicesforremovingcolumns(andthedatatheycontain).Theseoptionsare:RESTRICTandCASCADE.Theformerwilldeleteacolumnifthere’snoroutine,view,trigger,orconstraintthatpointstoit.Thelatter,ontheotherhand,deletesacolumnanditscontentsevenifobjectsreferenceit.Forinstance,thefollowingcommandremovesAUTHOR_DOBanditsdataregardlessofthecurrentobjectdependencies:

ALTERTABLEAUTHORS

DROPCOLUMNAUTHOR_DOBCASCADE;

ALTERTABLEisausefulcommandsincetabledefinitionsoftenchange.However,justlikeotherSQLstatements,thiscommandmayhavedifferentfeaturesbasedonthedatabaseimplementationyouareusing.Forinstance,RESTRICTandCASCADEarenotavailableinSQLServer.Meanwhile,OraclerequiresyoutotypeCASCADECONSTRAINTSinsteadofCASCADE(thisimplementationdoesn’tsupportRESTRICTexplicitly).

HowtoDeleteanSQLTable

InSQL,deletingtablesandtheircontentsiseasyandsimple.Hereisthesyntaxthatyouneedtouse:

DROPTABLE(nameoftable)[RESTRICT|CASCADE]

Whenusingthiscommand,youhavetochooseeitherRESTRICTorCASCADE.TheRESTRICToptiondeletesthetableifnootherobjects“depend”onit.CASCADE,however,removesthetableandalloftheobjectsthatpointtoit.Forinstance,thecommandgivenbelowremovesthetablenamedAUTHORSandallofitscontents,evenifobjectscurrentlypointtoit:

DROPTABLEAUTHORSCASCADE;

Chapter4:HowtoEnsureDataIntegrity

SQLdatabasesdon’tjuststoreinformation.Theyneedtomakesurethattheinformationtheystoreisreliable.Iftheinformation’sintegrityhasbeencompromised,itsreliabilitybecomesquestionable.Ifthedataisunreliable,thedatabasethatcontainsitalsobecomesunreliable.

Tosecuredataintegrity,SQLoffersawiderangeofrulesthatcanlimitthevaluesatablecanhold.Theserules,knownas“integrityconstraints,”workoncolumnsandtables.Thischapterwillexplaineachkindofconstraint.Itwillalsoteachyouhowtoapplythesaidconstraintstoyourowndatabase.

IntegrityConstraints–TheBasics

SQLusersdivideintegrityconstraintsintothefollowingcategories:

TheAssertions–Youneedtodefinethisconstraintinsideaseparatedefinition(whichiscalledthe“assertiondefinition”).Thatmeansyouwon’tindicateanassertioninyourtable’sdefinition.InSQL,youmayapplyanassertiontomultipletables.

TheTable-RelatedConstraints–Thisisaconstraintthatyouneedtodefineinsideatable’sdefinition.Youmaydefineaconstraintasacomponentofatable’sorcolumn’sdefinition.

TheDomainConstraints–Similartotheassertions,youneedtocreatedomainconstraintsinaseparatedefinition.Thiskindofconstraintworksonthecolumn/sthatyoudeclaredinsidethedomaininvolved.

Table-relatedconstraintsoffervariousconstraintoptions.Consequently,itisthemostpopularcategoryofintegrityconstraintsthesedays.Youcandividethiscategoryintotwo:columnconstraintsandtableconstraints.Theformerbelongtothedefinitionofacolumn.Thelatter,ontheotherhand,actaselementsofatable.

Thetableandcolumnconstraintsworkwithdifferentkindsofconstraints.Thedomainconstraintsandassertions,however,canworkwithoneconstrainttypeonly.

TheNotNullConstraint

Inthepreviouschapter,youlearnedthat“null”representsanunknown/undefinedvalue.Keepinmindthatundefined/unknownisdifferentfromzeroes,blanks,defaultvalues,andemptystrings.Rather,itsignifiestheabsenceofavalue.Youmayconsiderthisvalueasa“flag”(i.e.abit,number,orcharacterthatexpressessomedataregardingacolumn).Fornull,ifyouleaveacolumnempty,thesystemwillplacethe“flag”toindicatethatthere’sanunknownvalue.

Columnshaveanattributecalled“nullability.”Thisattributeshowswhetherthecolumnscantakeunknownvaluesornot.InSQL,columnsaresettotakenullvalues.However,youmaychangethisattributeaccordingtoyourneeds.Todisablethenullabilityofacolumn,youjusthavetousetheNOTNULLconstraint.ThisconstraintinformsSQLthatthecolumnwon’tacceptanynullvalue.

Inthislanguage,youneedtouseNOTNULLonacolumn.Thatmeansyoucan’tusethisconstraintonanassertion,domainconstraint,ortable-basedconstraint.UsingNOTNULLisasimpleprocess.Youjusthavetoaddthesyntaxgivenbelowtoyourcolumndefinition:

(nameofcolumn)[(domain)|(datatype)]NOTNULL

Asanexample,let’sassumethatyouneedtogenerateatablecalledFICTION_NOVEL_AUTHORS.Thistableneedsthreecolumns:AUTHOR_ID,AUTHOR_NAME,andAUTHOR_DOB.Youneedtoensurethateachentryyou’lladdhasvaluesforAUTHOR_IDandAUTHOR_NAME.Toaccomplishthis,youmustinserttheNOTNULLconstraintintothedefinitionofbothcolumns.Here’sthecode:

CREATETABLEFICTION_NOVEL_AUTHORS

(AUTHOR_IDINTNOTNULL,

AUTHOR_NAMECHARACTER(50)NOTNULL,

AUTHOR_DOBCHARACTER(50));

Asyoucansee,thiscodedidn’tsetNOTNULLfortheAUTHOR_DOBcolumn.Consequently,ifanewentrydoesn’thaveanyvalueforAUTHOR_DOB,thesystemwillinsertanullvaluetothatcolumn.

TheUniqueConstraint

Tableandcolumnconstraintsacceptuniqueconstraints.InSQL,uniqueconstraintsbelongtooneofthesetypes:

1. UNIQUE

2. PRIMARYKEY

ImportantNote:Thispartofthebookwillconcentrateonthefirsttype.You’lllearnaboutthesecondonelater.

Basically,youcanuseUNIQUEtomakesurethatacolumnwon’tacceptduplicatevalues.Thisconstraintwillstopyoufromenteringavaluethatalreadyexistsinthecolumn.

Let’sassumethatyouwanttoapplythisconstraintontheAUTHOR_DOBcolumn.Thisway,youcanmakesurethatthevaluesinsidethatcolumnareallunique.Now,let’ssayyourealizedthatrequiringdatesofbirthtobeuniqueisabadideasincepeoplemaybebornonthesamedate.YoumayadjustyourapproachbyplacingtheUNIQUEconstraintonAUTHOR_NAMEandAUTHOR_DOB.Here,thetablewillstopyoufromrepeatinganAUTHOR_NAME/AUTHOR_DOBpair.YoumayrepeatvaluesintheAUTHOR_NAMEandAUTHOR_DOBcolumns.However,youcan’treenteranexactpairthatalreadyexistsinthetable.

ItistimeforyoutocreateyourownUNIQUEconstraints.KeepinmindthatyoumaytagUNIQUEconstraintsastableconstraintsorcolumnconstraints.Togeneratecolumnconstraints,addthemtothedefinitionofacolumn.Hereisthesyntax:

(nameofcolumn)[(domain)|(datatype)]UNIQUE

IfyouneedtousetheUNIQUEconstraintonatable,youmustinsertitintothetabledefinitionasanelement.Thefollowingsyntaxwillshowyouhow:

{CONSTRAINT(nameofconstraint)}

UNIQUE<(nameofcolumn){[,(nameofcolumn)]…}>

Asthesyntaxaboveshows,usingUNIQUEonatableismorecomplicatedthanusingtheconstraintonacolumn.However,youcannotapplyUNIQUEonmultiplecolumns.Regardlessofhowyouusethisconstraint(i.e.eitherasatableconstraintoracolumn

constraint),youmaydefineanynumberofUNIQUEconstraintswithineachtabledefinition.

Let’sapplythisconstraintonacolumnarlevel:

CREATETABLEBOOK_LIBRARY

(AUTHOR_NAMECHARACTER(50),

BOOK_TITLECHARACTER(70)UNIQUE,

PUBLISHED_DATEINT);

YoumayalsouseUNIQUEonothercolumns.However,itsresultwouldbedifferentfromthatofusingatableconstraintonmultiplecolumns.Thefollowingcodewillillustratethisidea:

CREATETABLEBOOK_LIBRARY

(AUTHOR_NAMECHARACTER(50),

BOOK_TITLECHARACTER(70),

PUBLISHED_DATEINT,

CONSTRAINTUN_AUTHOR_BOOKUNIQUE(AUTHOR_NAME,BOOK_TITLE));

Now,theAUTHOR_NAMEandBOOK_TITLEcolumnsmusthaveuniquevaluesforthetabletoacceptanewentry.

Asyou’vereadearlier,theUNIQUEconstraintmakessurethatoneormorecolumnswon’ttakeduplicatevalues.Thatisanimportantruletoremember.However,youshouldalsoknowthatUNIQUEdoesn’tworkon“null.”Thus,acolumnwillacceptanynumberofnullvaluesevenifyouhavesetaUNIQUEconstraintonit.

Ifyouwanttosetyourcolumnssothattheywillnotacceptanullvalue,youmustuseNOTNULL.Let’sapplyNOTNULLonthecolumndefinitionofBOOK_TITLE:

CREATETABLEBOOK_LIBRARY

(AUTHOR_NAMECHARACTER(50),

BOOK_TITLECHARACTER(70)UNIQUENOTNULL,

PUBLISHED_DATEINT);

InSQL,youmayalsoinsertNOTNULLintocolumndefinitionsthatatable-levelconstraintispointingto:

CREATETABLEBOOK_LIBRARY

(AUTHOR_NAMECHARACTER(50),

BOOK_TITLECHARACTER(70)NOTNULL,

PUBLISHED_DATEINT,

CONSTRAINTUN_AUTHOR_BOOKUNIQUE(BOOK_TITLE));

Inbothcases,theBOOK_TITLEcolumngetstheconstraint.ThatmeansBOOK_TITLEwon’tacceptnullorduplicatevalues.

ThePRIMARYKEYConstraint

ThePRIMARYKEYconstraintisalmostidenticaltotheUNIQUEconstraint.YoumayuseaPRIMARYKEYtopreventduplicateentries.Inaddition,youmayapplyittomultiplecolumnsanduseitasatableconstraintoracolumnconstraint.TheonlydifferenceisthatPRIMARYKEYhastwodistinctrestrictions.Theserestrictionsare:

IfyouwillapplyPRIMARYkeyonacolumn,thatcolumnwon’tacceptanynullvalue.Basically,youwon’thavetousetheNOTNULLconstraintonacolumnthathasPRIMARYKEY.

Atablecan’thavemultiplePRIMARYKEYconstraints.

Theserestrictionsexistbecauseprimarykeys(alsoknownas“uniqueidentifiers”)playanimportantroleineachtable.Asdiscussedinthefirstchapter,tablescannothaveduplicaterows.ThisruleiscrucialsincetheSQLlanguagecannotidentifyredundantrows.Ifyouwillchangearow,allofitsduplicateswillalsobeaffected.

Youneedtochooseaprimarykeyfromthecandidatekeysofyourdatabase.Basically,candidatekeysaregroupsofcolumnsthatidentifyrowsinauniquemanner.Youmayenforceacandidatekey’suniquenessusingUNIQUEorPRIMARYKEY.However,youmustplaceoneprimarykeyoneachtableevenifyoudidn’tdefineanyuniqueconstraint.Thisrequirementensurestheuniquenessofeachdatarow.

Todefineaprimarykey,youneedtoindicatethecolumn/syouwanttouse.YoucancompletethistaskthroughPRIMARYKEY(i.e.theSQLkeyword).Thisprocessissimilartotheonediscussedintheprevioussection.WhenapplyingPRIMARYKEYonanewcolumn,youshouldusethissyntax:

(nameofcolumn)[(domain)|(datatype)]PRIMARYKEY

TousePRIMARYkeyonatable,youmustenteritasanelementofthetableyou’reworkingon.Checkthesyntaxbelow:

{CONSTRAINT(nameofconstraint)}

PRIMARYKEY<(nameofcolumn){,(nameofcolumn)]…}>

SQLallowsyoutodefineprimarykeysusingcolumnconstraints.However,youcanonly

usethisfeatureonasinglecolumn.Analyzethefollowingexample:

CREATETABLEFICTION_NOVEL_AUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50)PRIMARYKEY,

PUBLISHER_IDINT);

IfyouwanttoapplyPRIMARYKEYonmultiplecolumns(orstoreitasanotherdefinition),youmayuseitonthetabularlevel:

CREATETABLEFICTION_NOVEL_AUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50),

PUBLISHER_IDINT,

CONSTRAINTPK_AUTHOR_IDPRIMARYKEY(AUTHOR_ID,AUTHOR_NAME));

Thisapproachplacesaprimarykeyontwocolumns(i.e.AUTHOR_IDandAUTHOR_NAME).Thatmeansthepairedvaluesofthetwocolumnsneedtobeunique.However,duplicatevaluesmayexistinsideanyofthecolumns.Experienceddatabaseusersrefertothiskindofprimarykeyasa“superkey.”Theterm“superkey”meanstheprimarykeyexceedsthenumberofrequiredcolumns.

Inmostcases,youneedtosetbothUNIQUEandPRIMARYKEYconstraintsonatable.Toachievethis,youjusthavetodefinetheinvolvedconstraintsasnormal.Forinstance,thecodegivenbelowappliesbothoftheseconstraints:

CREATETABLEFICTION_NOVEL_AUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50)PRIMARYKEY,

PUBLISHER_IDINT,

CONSTRAINTUN_AUTHOR_NAMEUNIQUE(AUTHOR_NAME));

Thefollowingcodewillgiveyouthesameresult:

CREATETABLEFICTION_NOVEL_AUTHORS

(AUTHOR_IDINT,

AUTHOR_NAMECHARACTER(50)->UNIQUE,

PUBLISHER_IDINT,

CONSTRAINTPK_PUBLISHER_IDPRIMARYKEY(PUBLISHER_ID));

TheFOREIGNKEYConstraints

Theconstraintsdiscussedsofarfocusonsecuringthedataintegrityofatable.NOTNULLstopscolumnsfromtakingnullvalues.PRIMARYKEYandUNIQUE,ontheotherhand,guaranteethatthevaluesofoneormorecolumnsareunique.Inthisregard,FOREIGNKEY(i.e.anotherSQLconstraint)isdifferent.FOREIGNKEY,alsocalled“referentialconstraint,”focusesonhowinformationinsideatableworkswiththeinformationwithinanothertable.

Inthefirstchapterofthisbook,youlearnedthatthetablesofrelationaldatabasesareinterconnected.Thisconnectionensuresinformationintegritythroughoutthedatabase.Inaddition,theconnectionbetweendifferenttablesresultsto“referentialintegrity.”Thiskindofintegritymakessurethatdatamanipulationdoneononetablewon’taffectthedatainsideothertables.Thetablesgivenbelowwillhelpyouunderstandthistopic.Eachofthesetables,namedPRODUCT_NAMESandPRODUCT_MANUFACTURERS,haveoneprimarykey:

PRODUCT_NAMES

PRODUCT_NAME_ID:INT

PRODUCT_NAME:

CHARACTER(50)MANUFACTURER_ID:INT

1001 XPen 91

1002 YEraser 92

1003 ZNotebook 93

PRODUCT_MANUFACTURERS

MANUFACTURER_ID:INT

BUSINESS_NAME:CHARACTER(50)

91 THEPENMAKERSINC.

92 THEERASERMAKERSINC.

THENOTEBOOK

93 MAKERSINC.

ThePRODUCT_NAME_IDcolumnofthePRODUCT_NAMEStablehasaPRIMARYKEY.TheMANUFACTURER_IDofthePRODUCT_MANUFACTURERStablehasthesameconstraint.Thesecolumnsareinyellow(seethetablesabove).

Asyoucansee,thePRODUCT_NAMEStablehasacolumncalledMANUFACTURER_ID.ThatcolumnhasthevaluesofacolumninthePRODUCT_MANUFACTURERStable.Actually,theMANUFACTURER_IDcolumnofthePRODUCT_NAMEStablecanonlyacceptvaluesthatcomefromtheMANUFACTURER_IDcolumnofthePRODUCT_MANUFACTURERStable.

Additionally,thechangesthatyou’llmakeonthePRODUCT_NAMEStablemayaffectthedatastoredinthePRODUCT_MANUFACTURERStable.Ifyouwillremoveamanufacturer,youalsoneedtoremovetheentryfromtheMANUFACTURER_IDcolumnofthePRODUCT_NAMEStable.YoucanachievethisresultusingFOREIGNKEY.Thisconstraintensuresthereferentialintegrityofyourdatabasebypreventingactionsonanytablefromaffectingtheprotectedinformation.

ImportantNote:Ifatablehasaforeignkey,itiscalled“referencingtable.”Thetableaforeignkeypointstoiscalled“referencedtable.”

Whilecreatingthiskindofconstraint,youneedtoobeythefollowingguidelines:

YoumustdefineareferencedcolumnbyusingPRIMARYKEYorUNIQUE.MostSQLprogrammerschoosePRIMARYKEYforthispurpose.

YoumaytagFOREIGNKEYconstraintsascolumnconstraintsortableconstraints.YoumayworkwithanynumberofcolumnsifyouareusingFOREIGNKEYasatableconstraint.Ontheotherhand,ifyouwillusethisconstraintatthecolumn-level,youcanworkonasinglecolumnonly.

Areferencingtable’sforeignkeyshouldcoverallofthecolumnsyouaretryingtoreference.Inaddition,thecolumnsofthereferencingtableshouldmatchthedatatypeoftheircounterparts(i.e.thecolumnsbeingreferenced).However,youdon’thavetousethesamenamesforyourreferencingandreferencedcolumns.

Youdon’tneedtoindicatereferencecolumnsmanually.SQLwillconsiderthecolumnsofthereferencedtable’sprimarykeyasthereferencedcolumnsifyouwon’tspecifyanycolumnfortheconstraint.Thisprocesshappensautomatically.

You’llunderstandtheseguidelinesonceyouhaveanalyzedtheexamplesgivenbelow.Fornow,let’sanalyzethesyntaxofthisconstraint.Here’stheformatthatyoumustusetoapplyFOREIGNKEYatthecolumnarlevel:

(nameofcolumn)[(domain)|(datatype)]{NOTNULL}

REFERENCES(nameofthereferencedtable){<(thereferencedcolumns)>}

{MATCH[SIMPLE|FULL|PARTIAL]}

{(thereferentialaction)}

TousethisFOREIGNKEYasatabularconstraint,youneedtoinsertitasatable’selement.Here’sthesyntax:

{CONSTRAINT(nameofconstraint)}

FOREIGNKEY<(thereferencingcolumn){[,(thereferencingcolumn)]…}>

REFERENCES(thereferencedtable){<(thereferencedcolumn/s)>}

{MATCH[SIMPLE|FULL|PARTIAL]}

{(thereferentialaction)}

You’veprobablynoticedthatFOREIGNKEYismorecomplexthantheconstraintsyou’veseensofar.Thiscomplexityresultsfromtheconstraint’soption-filledsyntax.However,generatingthiskindofconstraintiseasyandsimple.Let’sanalyzeabasicexamplefirst:

CREATETABLEPRODUCT_NAMES

(PRODUCT_NAME_ID->INT,

PRODUCT_NAME->CHARACTER(50),

MANUFACTURER_ID->INT->REFERENCESPRODUCT_MANUFACTURERS);

ThiscodeappliestheconstraintonthecolumnnamedMANUFACTURER_ID.Toapplythisconstraintonatable,youjusthavetotypeREFERENCESandindicatethereferencedtable’sname.Inaddition,thecolumnsofthisforeignkeyisequaltothatofthereferencedtable’sprimarykey.Ifyoudon’twanttoreferenceyourtarget’sprimarykey,youneedtospecifythecolumn/syouwanttouse.Forinstance,REFERENCESPRODUCT_MANUFACTURERS(MANUFACTURER_ID).

ImportantNote:TheFOREIGNKEYconstraintrequiresanexistingreferencedtable.In

addition,thattablemusthaveaPRIMARYKEYorUNIQUEconstraint.

Forthesecondexample,youwilluseFOREIGNKEYasatabularconstraint.Thecodeyou’llseebelowspecifiesthereferencedcolumn’snameevenifthatinformationisnotneeded.

CREATETABLEPRODUCT_NAMES

(PRODUCT_NAME_IDINT,

PRODUCT_NAMECHARACTER(50),

MANUFACTURER_IDINT,

CONSTRAINTTS_MANUFACTURER_IDFOREIGNKEY(MANUFACTURER_ID)

REFERENCESPRODUCT_MANUFACTURERS(MANUFACTURER_ID));

Youmayconsiderthetwolinesatthebottomastheconstraint’sdefinition.Theconstraint’sname,TS_MANUFACTURER_ID,comesafterthekeywordCONSTRAINT.Youdon’tneedtospecifyanameforyourconstraintssinceSQLwillgenerateoneforyouincasethisinformationismissing.Ontheotherhand,youmaywanttosetthenameofyourconstraintmanuallysincethatvalueappearsinerrors(i.e.whenSQLcommandsviolateanexistingconstraint).Inaddition,thenamesyouwillprovidearemorerecognizablethansystem-generatedones.

Next,youshouldsetthekindofconstraintyouwanttouse.Then,enterthenameofyourreferencingcolumn(MANUFACTURER_IDforthecurrentexample).Youwillthenplacetheconstraintonthatcolumn.Ifyouaredealingwithmultiplecolumns,youmustseparatethenamesusingcommas.Afterward,typeREFERENCESaswellasthereferencedtable’sname.Lastly,enterthenameofyourreferencedcolumn.

That’sit.Onceyouhavedefinedthisconstraint,theMANUFACTURER_IDcolumnofPRODUCT_NAMESwon’ttakevaluesexceptthosethatarealreadylistedinthePRODUCT_MANUFACTURERStable’sprimarykey.Asyoucansee,aforeignkeydoesn’tneedtoholduniquevalues.Youmayrepeatthevaluesinsideyourforeignkeysasmanytimesasyouwant,unlessyouplacedtheUNIQUEconstraintonthecolumnyou’reworkingon.

Now,let’sapplythisconstraintonmultiplecolumns.Youshouldmasterthistechniquebeforestudyingtheremainingelementsoftheconstraint’ssyntax.Forthisexample,let’susetwotables:BOOK_AUTHORSandBOOK_GENRES.

ThetablenamedBOOK_AUTHORShasaprimarykeydefinedintheAUTHOR_NAMEandAUTHOR_DOBcolumns.TheSQLstatementfoundbelowgeneratesatablecalledBOOK_GENRES.ThistablehasaforeignkeyconsistingoftheAUTHOR_DOBandDATE_OF_BIRTHcolumns.

CREATETABLEBOOK_GENRES

(AUTHOR_NAMECHARACTER(50),

DATE_OF_BIRTHDATE,

GENRE_IDINT,

CONSTRAINTTS_BOOK_AUTHORSFOREIGNKEY(AUTHOR_NAME,DATE_OF_BIRTH)REFERENCESBOOK_AUTHORS(AUTHOR_NAME,AUTHOR_DOB));

Thiscodehasapairofreferencedcolumns(i.e.AUTHOR_NAME,AUTHOR_DOB)andapairofreferencingcolumns(i.e.AUTHOR_NAMEandDATE_OF_BIRTH).ThecolumnsnamedAUTHOR_NAMEinsidethedatatablescontainthesametypeofdata.ThedatatypeoftheDATE_OF_BIRTHcolumnisthesameasthatofAUTHOR_DOB.Asthisexampleshows,thenameofareferencedcolumndoesn’tneedtomatchthatofitsreferencingcounterpart.

TheMATCHPart

Now,let’sdiscussanotherpartoftheconstraint’ssyntax:

{MATCH[SIMPLE|FULL|PARTIAL]}

Thecurlybracesshowthatthisclauseisoptional.Themainfunctionofthisclauseistoletyouchoosehowtohandlenullvaluesinsideaforeignkeycolumn,consideringthevaluesthatyoumayaddtoareferencingcolumn.Thisclausewon’tworkoncolumnsthatdon’tacceptnullvalues.

Thispartofthesyntaxoffersthreechoices:

SIMPLE–Ifyouwillchoosethisoption,andatleastoneofyourreferencingcolumnshasanullvalue,youmayplaceanyvalueontherestofthereferencingcolumns.Thesystemwillautomaticallytriggerthisoptionifyouwon’tspecifytheMATCHsectionofyourFOREIGNKEY’sdefinition.

FULL–Thisoptionrequiresallofyourreferencingcolumnstoacceptnullvalues;otherwise,noneofthemcanacceptanullvalue.

PARTIAL–Withthisoption,youmayplacenullvaluesonyourreferencingcolumnsifotherreferencingcolumnscontainvaluesthatmatchtheirrespectivereferencedcolumns.

The(referentialaction)Part

ThisisthefinalsectionoftheFOREIGNKEYsyntax.JustliketheMATCHpart,“referentialaction”iscompletelyoptional.Youcanusethisclausetospecifywhichactionstotakewhileupdatingorremovinginformationfromoneormorereferencedcolumns.

Forinstance,let’sassumethatyouwanttoremoveanentryfromtheprimarykeyofatable.Ifaforeignkeyreferencestheprimarykeyyou’reworkingon,yourdesiredactionwillviolatetheconstraint.Youshouldalwaysincludethedataofyourreferencingcolumnsinsideyourreferencedcolumns.

Whenusingthisclause,youwillsetaspecificactiontothereferencingtable’sdefinition.Thisactionwilloccuronceyourreferencedtablegetschanged.Hereisthesyntaxthatyoumustuse:

ONUPDATE(thereferentialaction){ONDELETE(thereferentialaction)}|ONDELETE(thereferentialaction){ONUPDATE(thereferentialaction)}(thereferentialaction)::=

RESTRICT|SETNULL|CASCADE|NOACTION|SETDEFAULT

Accordingtothissyntax,youmaysetONDELETE,ONUPDATE,orboth.Theseclausescanacceptoneofthefollowingactions:

RESTRICT–ThisreferentialactionpreventsyoufromperformingupdatesordeletionsthatcanviolatetheFOREIGNKEYconstraint.TheinformationinsideareferencingcolumncannotviolateFOREIGNKEY.

SETNULL–Thisactionchangesthevaluesofareferencingcolumnto“null”ifitscorrespondingreferencedcolumngetsremovedorupdated.Ifyouwanttousethisoption,makesurethatyourreferencingcolumnsacceptnullvalues.

CASCADE–Withthisreferentialaction,thechangesyou’llapplyonareferencedcolumnwillalsobeappliedtoitsreferencingcolumn.

NOACTION–JustlikeRESTRICT,NOACTIONstopsyoufromperformingactionsthatwillviolateFOREIGNKEY.ThemaindifferenceisthatNOACTIONallowsdataviolationswhileyouareexecutinganSQLcommand.However,theinformationwithinyourforeignkeywillnotbeviolatedoncethecommandhasbeenexecuted.

SETDEFAULT–Withthisoption,youmaysetareferencingcolumntoitsdefaultvaluebyupdatingordeletingthedatainsidethecorrespondingreferencedcolumn.

Thisreferentialactionwon’tworkifyourreferencingcolumnsdon’thavedefaultvalues.

Tousethisclause,youjusthavetoinsertittothelastpartofaFOREIGNKEY’sdefinition.Here’sanexample:

CREATETABLEAUTHORS_GENRES

(AUTHOR_NAMECHARACTER(50),

DATE_OF_BIRTHDATE,

GENRE_IDINT,

CONSTRAINTTS_BOOK_AUTHORSFOREIGNKEY(AUTHOR_NAME,DATE_OF_BIRTH)REFERENCESBOOK_AUTHORSONDELETERESTRICTONUPDATERESTRICT);

TheCHECKConstraint

Youcanapplythisconstraintonatable,column,domain,orinsideanassertion.Thisconstraintletsyousetwhichvaluestoplaceinsideyourcolumns.Youmayusedifferentconditions(e.g.valueranges)thatdefinewhichvaluesyourcolumnsmayhold.

AccordingtoSQLprogrammers,theCHECKconstraintisthemostcomplexandflexibleconstraintcurrentlyavailable.However,thisconstrainthasasimplesyntax.TouseCHECKasacolumnconstraint,addthesyntaxbelowtoyourcolumndefinition:

(nameofcolumn)[(domain)|(datatype)]CHECK<(thesearchcondition)>

Ifyouwanttousethisconstraintonatable,insertthesyntaxbelowtoyourtable’sdefinition:

{CONSTRAINT(nameofconstraint)}CHECK<(thesearchcondition)>

ImportantNote:You’llknowhowtousethisconstraintonassertionsanddomainslater.

Asthissyntaxshows,CHECKiseasytounderstand.However,itssearchconditionmayinvolvecomplexandextensivevalues.ThisconstraintteststheassignedsearchconditionfortheSQLcommandsthattrytoaltertheinformationinsideacolumnprotectedbyCHECK.IftheresultofthetestisTRUE,thecommandswillrun;iftheresultisfalse,thesystemwillcancelthecommandsanddisplaysomeerrormessages.

Youneedtoanalyzeexamplesinordertomasterthisclause.However,almostallcomponentsofthesearchconditioninvolvepredicates.Predicatesareexpressionsthatworkonvalues.InSQL,youmayuseapredicatetocomparedifferentvalues(e.g.COLUMN_3<5).The“lessthan”predicatecheckswhetherthevaluesinsideCOLUMN_3arelessthan5.

Mostcomponentsofthesearchconditionalsoutilizesubqueries.Basically,subqueriesareexpressionsthatactascomponentsofotherexpressions.Youwilluseasubqueryifanexpressionneedstoaccessorcomputedifferentlayersofinformation.Forinstance,anexpressionmightneedtoaccessTABLE_XtoinsertinformationtoTABLE_Z.

Fornow,let’sfocusonthebasicsoftheCHECKconstraint.Intheexamplebelow,

CHECKdefinesthehighestandlowestvaluesthatyoumayenterinacolumn.ThistabledefinitiongeneratesaCHECKconstraintandthreecolumns:

CREATETABLEBOOK_TITLES

(BOOK_IDINT,

BOOK_TITLECHARACTER(50)NOTNULL,

STOCK_AVAILABILITYINT,

CONSTRAINTTS_STOCK_AVAILABILITY(STOCK_AVAILABILITY<50ANDSTOCK_AVAILABILITY>1));

Theresultingtablewillrejectvaluesthatareoutsidethe1-50range.Here’sanotherwayofwritingthetable:

CREATETABLEBOOK_TITLES

(BOOK_IDINT,

BOOK_TITLECHARACTER(50)NOTNULL,

STOCK_AVAILABILITYINTCHECK(STOCK_AVAILABILITY<50ANDSTOCKAVAILABILITY>1));

Now,let’sanalyzetheconditionclauseofthesestatements.ThisclausetellsSQLthatallofthevaluesaddedtotheSTOCK_AVAILABILITYcolumnshouldbelowerthan50.ThekeywordANDinformsSQLthatthere’sanotherconditionthatmustbeapplied.Lastly,theclausetellsSQLthateachvalueaddedtothesaidcolumnshouldbehigherthan1.Toputitsimply,eachvalueshouldbelowerthan50andhigherthan1.

Thisconstraintalsoallowsyoutojustlistyour“acceptablevalues.”SQLusersconsiderthisasapowerfuloptionwhenitcomestovaluesthatwon’tbechangedregularly.Inthenextexample,youwillusetheCHECKconstrainttodefineabook’sgenre:

CREATETABLEBOOK_TITLES

(BOOK_IDINT,

BOOK_TITLECHARACTER(50),

GENRECHAR(10),

CONSTRAINTTS_GENRECHECK(GENREIN(‘DRAMA‘,‘HORROR‘,‘SELFHELP‘,‘ACTION‘,‘MYSTERY‘,‘ROMANCE‘)));

EachvalueinsidetheGENREcolumnshouldbeincludedinthelistedgenresofthecondition.Thesystemwillgiveyouanerrormessageifyouwillentervaluesotherthan“null”orthesixlistedgenres.Asyoucansee,thisstatementusesIN(i.e.anSQLoperator).Basically,INmakessurethatthevalueswithinGENREareincludedinthelistedentries.

Thisconstraintcanbeextremelyconfusingsinceitinvolvesalotofparentheses.YoumaysimplifyyourSQLcodesbydividingthemintomultiplelines.Asanexample,let’srewritethecodegivenabove:

CREATETABLEBOOK_TITLES

(

BOOK_IDINT,

BOOK_TITLECHAR(50),

GENRECHAR(10),

CONSTRAINTTS_GENRECHECK

(

GENREIN

(‘DRAMA‘,‘HORROR‘,‘SELFHELP‘,‘ACTION‘,‘MYSTERY‘,‘ROMANCE‘

)

)

);

ThisstyleofwritingSQLcommandsensurescodereadability.Here,youneedtoindenttheparenthesesandtheircontentssothattheyshowtheirpositionclearlyinthedifferentlayersoftheSQLstatement.Byusingthisstyle,youcanquicklyidentifytheclausesplacedineachpairofparentheses.Additionally,thisstatementworkslikethepreviousone.Theonlydrawbackofthisstyleisthatyouneedtouselotsofspace.

Let’sanalyzeanotherexample:

CREATETABLEBOOK_TITLES

(BOOK_IDINT,

BOOK_TITLECHAR(50),

STOCK_AVAILABILITYINT,

CONSTRAINTTS_STOCK_AVAILABILITYCHECK((STOCK_AVAILABILITYBETWEEN1AND50)OR(STOCK_AVAILABILITYBETWEEN79AND90)));

ThiscodeusesBETWEEN(i.e.anotherSQLoperator)tosetarangethatincludesthelowestandhighestpoints.Becauseithastworanges,itseparatestherangespecificationsusingparentheses.TheORkeywordconnectstherangespecifications.Basically,ORtellsSQLthatoneoftheconditionsneedtobesatisfied.Consequently,thevaluesyouwillenterinthecolumnnamedSTOCK_AVAILABILITYshouldbefrom1through50orfrom79through90.

HowtoDefineanAssertion

AssertionsareCHECKconstraintsthatyoucanapplyonmultipletables.Becauseofthis,youcan’tcreateassertionswhiledefiningatable.Here’sthesyntaxthatyoumustusewhilecreatinganassertion:

CREATEASSERTION(nameofconstraint)CHECK(thesearchconditions)

Defininganassertionissimilartodefiningatable-levelCHECKconstraint.AftertypingCHECK,youneedtospecifythesearchcondition/s.

Let’sanalyzeanewexample.AssumethattheBOOK_TITLEStablehasacolumnthatholdsthequantityofbooksinstock.Thetotalforthistableshouldalwaysbelowerthanyourdesiredinventory.ThisexampleusesanassertiontocheckwhetherornotthetotaloftheSTOCK_AVAILABILITYcolumnislowerthan3000.

CREATEASSERTIONLIMIT_STOCK_AVAILABILITYCHECK((SELECTSUM(STOCK_AVAILABILITY)FROMBOOK_TITLES)<3000);

Thisstatementusesasubquery(i.e.“SELECTSUM(STOCK_AVAILABILITY)FROMBOOK_TITLES”)andcomparesitwith3000.ThesubquerystartswithanSQLkeyword,SELECT,whichqueriesinformationfromanytable.TheSQLfunctioncalledSUMaddsupallofthevaluesinsideSTOCK_AVAILABILITY.ThekeywordFROM,ontheotherhand,setsthecolumnthatholdsthetable.Thesystemwillthencomparethesubquery’sresultto3000.Youwillgetanerrormessageifyou’lladdanentrytotheSTOCK_AVAILABILITYcolumnthatmakesthetotalexceed3000.

HowtoCreateaDomainandaDomainConstraint

Asmentionedearlier,youmayalsoinserttheCHECKconstraintintoyourdomaindefinitions.Thiskindofconstraintissimilartotheonesyou’veseenearlier.Theonlydifferenceisthatyouwon’tattachadomainconstrainttoaparticulartableorcolumn.Actually,adomainconstraintusesVALUE,anotherSQLkeyword,whilereferringtoavalueinsideacolumnspecifiedforthatdomain.Now,let’sdiscussthesyntaxyouneedtousewhilegeneratingnewdomains:

CREATEDOMAIN(nameofdomain){AS}(typeofdata)

{DEFAULT(thedefaultvalue)}

{CONSTRAINT(nameofconstraint)}CHECK<(thesearchcondition)>

Thissyntaxhaselementsyou’veseenbefore.You’velearnedaboutdefaultclausesanddatatypesinthethirdchapter.Thedefinitionoftheconstraint,ontheotherhand,hassomesimilaritieswiththeonesdiscussedinthelastfewsections.

Fortheexamplebelow,youwillgenerateanINT-typedomain.Thisdomaincanonlyacceptvaluesbetween1and50:

CREATEDOMAINBOOK_QUANTITYASINTCONSTRAINTTS_BOOK_QUANTITYCHECK(VALUEBETWEEN1and50);

Thisexampleinvolvesonenewitem,whichistheVALUEkeyword.Asmentionedearlier,thiskeywordreferstoacolumn’svaluespecifiedusingtheBOOK_QUANTITYdomain.Consequently,youwillgetanerrormessageifyouwillenteravaluethatdoesn’tsatisfytheassignedcondition(i.e.eachvaluemustbebetween1and50).

Chapter5:HowtoCreateanSQLView

YourdatabasestoresSQLinformationusing“persistent”(i.e.permanent)tables.However,persistenttablescanbeimpracticalifyoujustwanttocheckparticularentriesfromoneormoretables.Becauseofthis,theSQLlanguageallowsyoutouse“views”(alsocalled“viewedtables”).

Viewsarevirtualtableswhosedefinitionsactasschemaobjects.Themaindifferencebetweenviewsandpersistenttablesisthattheformerdoesn’tstoreanydata.Actually,viewedtablesdon’treallyexist–onlytheirdefinitionexists.Thisdefinitionletsyouchoosespecificdatafromatableoragroupoftables,accordingtothedefinition’squerystatements.Toinvokeaview,youjusthavetoincludeitsnameinyourqueryasifitsanordinarytable.

HowtoAddaViewtoaDatabase

Viewsbecomeextremelyusefulwhenyou’retryingtoaccessvariouskindsofinformation.Ifyouwilluseaview,youmaydefinecomplicatedqueriesandsavetheminsideaviewdefinition.Ratherthantypingquerieseachtimeyouusethem,youmayjustcalltheview.Inaddition,viewsallowyoutopresentdatatootherpeoplewithoutshowinganyunnecessaryorconfidentialinformation.

Forinstance,youmightneedtoallowsomeuserstoaccesscertainpartsofemployeerecords.However,youdon’twantthesaiduserstoaccesstheSSN(i.e.socialsecuritynumber)orpayratesofthelistedemployees.Here,youmaygenerateviewsthatshowonlythedataneededbytheusers.

HowtoDefineanSQLView

InSQL,themostbasicviewthatyoucancreateisonewhichpointstoasingletableandcollectsinformationfromcolumnswithoutchanginganything.Hereisthebasicsyntaxofaview:

CREATEVIEW(nameofview){<(nameoftheview’scolumns)>}

AS(thequery)

{WITHCHECKOPTION}

ImportantNote:Thispartofthebookwillfocusonthefirstandsecondlinesoftheformat.You’lllearnaboutthethirdlinelater.

Youneedtosettheview’snameinthefirstpartofthedefinition.Additionally,youshouldnametheview’scolumnsifyouarefacinganyofthesecircumstances:

Ifyouneedtoperformanoperationtogetthecolumn’svalues,insteadofjustcopyingthemfromatable.

Ifyouareworkingwithduplicatecolumnnames.Thissituationhappenswhenyoucombinetables.

Youmaysetnamesforyourcolumnsevenifyoudon’tneedto.Forinstance,youmayassignlogicalnamestoyourcolumnssothatevenaninexperiencedusercanunderstandthem.

Thesecondpartoftheformathasamandatorykeyword(i.e.AS)andaplaceholderforthequery.Despiteitsapparentsimplicity,thequeryplaceholdermayinvolveacomplicatedstructureofSQLstatementsthatperformdifferentoperations.

Let’sanalyzeabasicexample:

CREATEVIEWBOOKS_IN_STOCK

(BOOK_TITLE,AUTHOR,STOCK_AVAILABILITY)AS

SELECTBOOK_TITLE,AUTHOR,STOCK_AVAILABILITY

FROMBOOK_INVENTORY

Thissampleisoneofthesimplestviewsthatyoucancreate.Itgetsthreecolumnsfromatable.RememberthatSQLisn’tstrictwhenitcomestolinebreaksandspaces.Forinstance,whilecreatingaview,youmaylistthecolumnnames(ifapplicable)onaseparateline.Databasemanagementsystemswon’tcarewhichcodingtechniqueyou’lluse.However,youcanensurethereadabilityofyourcodesbyadoptingacodingstyle.

Atthispoint,let’sdissectthesamplecodegivenabove.ThefirstpartsetsBOOKS_IN_STOCKastheview’sname.ThesecondpartsetsthenameofthecolumnsandcontainstheSQLkeywordAS.

Ifyouwon’tspecifythenamesyouwanttouse,theview’scolumnswilljustcopythenamesofthetable’scolumns.Thelasttwolinesholdthesearchexpression,whichisaSELECTstatement.Hereitis:

SELECTBOOK_TITLE,AUTHOR,STOCK_AVAILABILITY

FROMBOOK_INVENTORY

ThisisoneofthemostpopularstatementsintheSQLlanguage.SELECTisflexibleandextensive:itallowsyoutowritecomplexqueriesthatgivetheexactkindofinformationyouneed.

TheSELECTstatementofthisexampleisabasicone.Itonlyhastwoclauses:SELECTandFROM.Thefirstclausesetsthecolumntobereturned.Thesecondclause,however,setsthetablewheretheinformationwillbepulledfrom.OnceyoucalltheBOOKS_IN_STOCKSview,youwillactuallycalltheembeddedSELECTcommandof

theview.Thisactiongetstheinformationfromthecorrecttable/s.

Forthesecondexample,you’llcreateaviewthathasanextraclause:

CREATEVIEWBOOKS_IN_STOCK_80s

(BOOK_TITLE,YEAR_PUBLISHED,STOCK_AVAILABILITY)AS

SELECTBOOK_TITLE,YEAR_PUBLISHED,STOCK_AVAILABILITY

FROMBOOK_INVENTORY

WHEREYEAR_PUBLISHED>1979ANDYEAR_PUBLISHED<1990;

Thelastclausesetsacriterionthatshouldbesatisfiedforthesystemtoretrievedata.Thisexampleissimilartothepreviousone.Theonlydifferenceisthat,ratherthanpullingtheauthors’information,itfilterssearchresultsbasedontheyeareachbookwaspublished.

ImportantNote:Thecontentsofthelastclausedon’taffectthesourcetableinanyway.Theyworkonlyontheinformationreturnedbytheview.

YoumayuseWHEREinyourSELECTstatementstosetdifferenttypesofcriteria.Forinstance,youcanusethisclausetocombinetables.Checkthefollowingcode:

CREATEVIEWBOOK_PUBLISHERS

(BOOK_TITLE,PUBLISHER_NAME)AS

SELECTBOOK_INVENTORY.BOOK_TITLE,TAGS.PUBLISHER_NAME

FROMBOOK_INVENTORY,TAGS

WHEREBOOK_INVENTORY.TAG_ID=TAGS.TAG_ID;

ThiscodecreatesaviewnamedBOOK_PUBLISHERS.TheBOOK_PUBLISHERSviewcontainstwocolumns:BOOK_TITLEandPUBLISHER_NAME.Withthisview,you’llgetdatafromtwodifferentsources:(1)theBOOK_TITLEcolumnoftheBOOK_INVENTORYtableand(2)thePUBLISHER_NAMEcolumnoftheTABStable.

Fornow,let’sfocusonthethirdclause(i.e.theSELECTstatement).Thisclausequalifiesthecolumnsbasedonthenameoftheirrespectivetables(e.g.BOOK_INVENTORY.BOOK_TITLE).Ifyouarejoiningtables,youneedtoqualifythenamesofeachtabletoavoidconfusion.Obviously,columnscanbehighlyconfusingiftheyhaveduplicatenames.However,ifyou’redealingwithsimplecolumnnames,youmayomitthenameof

yourtables.Forinstance,yourSELECTclausemightlooklikethis:

SELECTBOOK_TITLE,PUBLISHER_NAME

Now,let’sdiscussthestatement’sFROMsection.Whilecombiningtables,youneedtonameallofthetablesyouwanttouse.Separatetheentriesusingcommas.Asidefromtheconcernregardingduplicatenames,thisclauseisidenticaltothatofthepreviousexamples.

WHERE,thelastclauseofthisstatement,matchesdatarowstogether.Thisclauseisimportantsince,ifyouwon’tuseit,youwon’tbeabletomatchvaluesyou’vegatheredfromdifferenttables.Inthecurrentexample,thevaluesinsidetheTAG_IDcolumnofBOOK_INVENTORYshouldmatchthevaluesinsidetheTAG_IDcolumnofthetablenamedTAGS.

SQLallowsyoutoqualifyaquerybyexpandingthelatter’sWHEREclause.Inthenextexample,WHERErestrictsthereturnedrowstothosethathold“999”intheBOOK_INVENTORYtable’sTAG_IDcolumn:

CREATEVIEWBOOK_PUBLISHERS

(BOOK_TITLE,BOOK_PUBLISHER)AS

SELECTBOOK_INVENTORY.BOOK_TITLE,TAGS.BOOK_PUBLISHER

FROMBOOK_INVENTORY,TAGS

WHEREBOOK_INVENTORY.TAG_ID=TAGS.TAG_ID

ANDBOOK_INVENTORY.TAG_ID=999;

Let’sworkonanotherexample.Similartotheexamplesyou’veseenearlier,thisviewcollectsinformationfromasingletable.Thisview,however,performscomputationsthatreturnthemodifiedinformation.Hereisthestatement:

CREATEVIEWBOOK_DISCOUNTS

(BOOK_TITLE,ORIGINAL_PRICE,REDUCED_PRICE)AS

SELECTBOOK_TITLE,ORIGINAL_PRICE,REDUCED_PRICE*0.8

FROMBOOK_INVENTORY;

Thisstatementcreatesaviewthathasthreecolumns:BOOK_TITLE,

ORIGINAL_PRICE,andREDUCED_PRICE.Here,SELECTindicatesthecolumnsthatholdtheneededinformation.ThestatementdefinesBOOK_TITLEandORIGINAL_PRICEusingthemethodsdiscussedinthepreviousexamples.ThesystemwillcopythedatainsidetheBOOK_INVENTORYtable’sBOOK_TITLEandORIGINAL_PRICEcolumns.Then,thesystemwillpastethedatatothecolumnsofthesamenameinsidetheBOOK_DISCOUNTSview.

Thelastcolumnisdifferent,however.Asidefromtakingvaluesfromitscorrespondingcolumn,itmultipliesthecollectedvaluesby0.8(i.e.80%).Thisway,thesystemwilldeterminethecorrectvaluestodisplayintheview’sREDUCED_PRICEcolumn.

SQLalsoallowsyoutoinserttheWHEREclausetoyourSELECTstatements.Here’sanexample:

CREATEVIEWBOOK_DISCOUNTS

(BOOK_TITLE,ORIGINAL_PRICE,REDUCED_PRICE)AS

SELECTBOOK_TITLE,ORIGINAL_PRICE,REDUCEDPRICE*0.8

FROMBOOK_INVENTORY

WHERESTOCK_AVAILABILITY>20;

ThisWHEREclauselimitsthesearchtothoseentrieswhoseSTOCK_AVAILABILITYvalueishigherthan20.Asthisexampleshows,youmayperformcomparisonsoncolumnsthatareincludedintheview.

HowtoCreateanUpdateableView

IntheSQLlanguage,someviewsallowyoutoperformupdates.Simplyput,youmayuseaviewtoaltertheinformation(i.e.addnewrowsand/oralterexistinginformation)insidethetableyou’reworkingon.The“updateability”ofaviewdependsonitsSELECTstatement.Usually,viewsthatinvolvesimpleSELECTstatementshavehigherchancesofbecomingupdateable.

RememberthatSQLdoesn’thaveanysyntaxforcreatingupdateableviews.Rather,youneedtowriteaSELECTstatementthatadherestocertainstandards.Thisistheonlywayforyoutocreateanupdateableview.

Theexamplesyou’veseeninthischapterimplythattheSELECTstatementservesasthesearchexpressionofaCREATEVIEWcommand.Tobeprecise,queryexpressionsmaybelongtodifferentkindsofexpressions.AsanSQLuser,you’llbedealingwithqueryspecificationsmostofthetime.QueryexpressionsareSQLexpressionsthatstartwithSELECTandcontainsdifferentelements.Toretainthesimplicityofthisbook,let’sassumethatSELECTisaqueryspecification.Databaseproductsalsousethisassumptionsoitiscertainlyeffective.

Herearethethingsyouneedtorememberwhilewritinganupdateableview:

Youcan’tsummarize,combine,orautomaticallydeletetheinformationinsidetheview.

Thetableyou’reworkingwithshouldhaveatleastoneupdateablecolumn.

Everycolumninsidetheviewshouldpointtoasinglecolumninatable.

Everyrowinsidetheviewshouldpointtoasinglerowinatable.

HowtoDropaView

Insomecases,youneedtodeleteaviewfromadatabase.Toaccomplishthistask,youneedtousethefollowingsyntax:

DROPVIEW(nameoftheview);

Thesystemwilldeletetheviewassoonasyourunthisstatement.However,theprocesswon’taffecttheunderlyinginformation(i.e.thedatastoredinsidetheactualtables).Afterdroppingaview,youmayrecreateitoruseitsnametogenerateanotherview.Let’sanalyzeabasicexample:

DROPVIEWBOOK_PUBLISHERS;

ThiscommandwilldeletetheBOOK_PUBLISHERSviewfromthedatabase.However,theunderlyinginformationwillbeunaffected.

Chapter6:DatabaseSecurity

Securityisanimportantelementofeverydatabase.Youneedtomakesurethatyourdatabaseissafefromunauthorizeduserswhomayvieworalterdata.Meanwhile,youalsoneedtoensurethatauthorizeduserscanaccessand/orchangedatawithoutanyproblems.Thebestsolutionforthisproblemistoprovideeachuserwiththeprivilegeshe/sheneedstodohis/herjob.

Toprotectdatabases,SQLhasasecurityschemethatletsyouspecifywhichdatabaseuserscanviewspecificinformation.Thisschemealsoallowsyoutosetwhatactionseachusercanperform.Thissecurityscheme(ormodel)reliesonauthorizationidentifiers.Asyou’velearnedinthesecondchapter,authorizationidentifiersareobjectsthatrepresentoneormoreusersthatcanaccess/modifytheinformationinsidethedatabase.

ThischapterwillexplainSQL’ssecuritymodel.Itwillalsoteachyouhowtouseauthorizationidentifiers.IfyouwanttobeaneffectiveSQLuser,youneedtoreadthismaterialcarefully.

TheSecurityModelofSQL

Thesecurityofyourdatabasereliesonauthorizationidentifiers.Youcanusetheseidentifierstoallowotherpeopletoaccessand/oralteryourdatabaseentries.Ifanauthorizationidentifierlackstherightprivilegestoalteracertainobject,theuserwon’tbeabletochangetheinformationinsidethatobject.Additionally,youmayconfigureeachidentifierwithvariouskindsofprivileges.

InSQL,anauthorizationidentifiercanbeauseridentifier(i.e.“user”)orarolename(i.e.“role”).A“user”isasecurityprofilethatmayrepresentaprogram,aperson,oraservice.SQLdoesn’thavespecificrulesregardingthecreationofauser.YoumaytietheidentifiertotheOS(i.e.operatingsystem)wherethedatabasesystemruns.Alternatively,youmaycreateuseridentifiersinsidethedatabasesystemitself.

Aroleisagroupofaccessrightsthatyoumayassigntousersorotherroles.Ifacertainrolehasaccesstoanobject,allusersandrolesyou’veassignedthatroletocanaccessthesaidobject.

SQLusersoftenutilizerolestoprovideuniformsetsofaccessrightstootherauthorizationidentifiers.Oneofthemainbenefitsofferedbyaroleisthatitcanexistwithoutanyuseridentifier.Thatmeansyoucancreatearolebeforecreatingauser.Inaddition,arolewillstaynthedatabaseevenifyouhavedeletedallofyouruseridentifiers.Thisfunctionalityallowsyoutoimplementaflexibleprocessforadministeringaccessrights.

TheSQLlanguagehasaspecialauthorizationidentifiercalledPUBLIC.Thisidentifiercoversallofthedatabaseusers.Similartootheridentifiers,youmayassignaccessrightstoaPUBLICprofile.

ImportantNote:YouneedtobecarefulwhenassigningaccessrightstothePUBLICidentifier.Usersmightutilizethatidentifierforunauthorizedpurposes.

CreatingandDeletingaRole

Generatingnewrolesisasimpleprocess.Thesyntaxhastwoclauses:anoptionalclauseandamandatoryclause.

CREATEROLE(nameofrole)

{WITHADMIN[CURRENT_ROLE|CURRENT_USER]}

Asyoucansee,CREATEROLEistheonlymandatorysectionofthisstatement.Youdon’tneedtosetthestatement’sWITHADMINpart.Actually,SQLusersrarelysetthatclause.WITHADMINbecomesimportantonlyifyourcurrentrolename/useridentifierpairdoesn’thaveanynullvalue.

Let’susethesyntaxtocreatearole:

CREATEROLEREADERS;

That’sit.Aftercreatingthisrole,youwillbeabletograntittousersorotherroles.

Todrop(ordelete)arole,youjusthavetousethefollowingsyntax:

DROPROLE(nameofrole)

Thissyntaxhasasinglerequirement:thenameoftheroleyouwanttodelete.Thefollowingexamplewillshowyouhowthissyntaxworks:

DROPROLEREADERS;

GrantingandRevokingaPrivilege

Wheneveryougrantaprivilege,youareactuallylinkingaprivilegetoanauthorizationidentifier.Youwillplacethisprivilege/authorizationidentifierpaironanobject,allowingtheformertoaccessthelatterbasedonthedefinedprivileges.Hereisthesyntaxthatyoumustusewhengrantingprivileges:

GRANT[(listofprivileges)|ALLPRIVILEGES]

ON(typeofobject)(nameofobject)

TO[(listofauthorizationidentifiers)|PUBLIC]{WITHGRANTOPTION}

{GRANTEDBY[CURRENT_ROLE|CURRENT_USER]}

Thissyntaxhasthreemandatoryclauses,namely:ON,TOandGRANT.Thelasttwoclauses,GRANTEDBYandWITHGRANTOPTION,arecompletelyoptional.

Theprocessofrevokingprivilegesissimpleandeasy.Youjusthavetousethesyntaxgivenbelow:

REVOKE{GRANTOPTIONFOR}[(listofprivileges)|ALLPRIVILEGES]

ON(typeofobject)nameofobject)

FROM[{listofauthorizationidentifiers)|PUBLIC}

ConclusionThisbookdiscussedthemostimportantideasandprinciplesrelatedtoSQL.Byutilizingthe tips, syntax, andcoding stylespresented in thismaterial, youwill be a skilledSQLprogrammerinnotime.

ThenextstepistoreadmorebooksaboutSQLprogrammingandcontinuewritingyourown codes.Keep inmind that computer languages such asSQLare too complex to bemasteredquickly.Thus,ifyou’replanningtouseSQLonaregularbasis,youshouldgetalloftheSQL-relatedreadingmaterialsavailabletoyou.Thisstyleofcollectingvaluableinformationcanhelpyoumasteranycomputerlanguage.

Additionally,youneedtopracticeyourskillsregularly.Readingbooksisgood.However,that is not enough to help you become a skilled SQL user. You also need to use theknowledgeyou’vegained.Bycreatingactualtablesanddatabases,you’llgaintheskillsandexperiencerequiredtobecomeanexpert.

Iwishyouthebestofluck!

RobertDwight

Bonus:PreviewOf“PHP:LearnPHPIn24HoursOrLess–ABeginner’sGuideToLearningPHPProgrammingNow”

TheControlStructures

Thisprogramminglanguagesupportsthebestcontrolstructuresofferedbyothercomputerlanguages.PHPusersdividecontrolstructuresintotwotypes:conditionalcontrolandloopcontrol.A conditional control structure influences theprogram’s flowand runsor skipscertaincodesbasedonpredeterminedcriteria.Aloopcontrolstructure,ontheotherhand,runsapieceofcodemultipletimesaccordingtothecriteriasetbytheprogrammer.Let’sdiscusseachtypeofstructuresindetail:

ConditionalStructures

Youneed touse conditional statementswhenwritingprograms.These statements allowyourprogramstobehavedifferentlybasedontheuser’sinputsandtheirown“decisions.”InPHP,youcanuse“if”statementsand“switch”statements.Thesestatementsaretwoofthemostpopularcontrolstructuresincomputerprogramming.

The“if”Statements

Thiscategoryconsistsofthreestatements,namely:

3. if(conditional_expression)

statement/s

4. elseif(conditional_expression)

statement/s

5. elseif(conditional_expression)

statement/s

else

statements

These statements are considered as the most popular conditional constructs inprogrammingandscripting.Actually,you’llfindtheminmostcomputerlanguages.Each“if” statement has a conditional expression known as the “truth expression.” If an “if”statement’struthexpressionresults totrue, thestatementorgroupofstatementsunderitwillrun;otherwise,theywillbeignored.

Youmayplacean“else”clausetoyour“if”statementtoruncodesonlyiftheconditionalexpressionsyouhaveprovidedevaluatestofalse.Here’sanexample:

if($sample>=100){

print‘$sampleiswithinthegivenrange’;

}else{

print‘$sampleisinvalid’;

}

As you can see, curly braces define the statements under each “if” and “else” clauses,turningthesestatementsintoa“codeblock.”Inthisexample,youmayremovethecurlybracessinceeachcodeblockholdsasinglestatement.However,it’sstillbestifyouwillwrite braces in situations where they are completely optional. Braces improve thereadabilityofPHPcodes.

Youcanusean“elseif”construct toperformasequenceofconditionalassessmentsandonlyrunthecodeunderthefirstsatisfiedcondition.Forinstance:

if($sample<0{

print‘$sampleisanegativeinteger’;

}elseif($sample==0){

print‘sampleisequaltozero’;

}elseif($sample>0{

print‘$sampleisapositiveinteger’;

}

The“switch”Statement

Thesyntaxofaswitchstatementis:

switch(expression){

caseexpression:

statement/s

caseexpression:

statement/s

default:

statement/s

}

Programmers use switch statements to replace complicated if-elseif statements. Switchstatementscompareanexpressionagainstallof thepossibleentries inside theirbody. Iftheydon’tfindanexactmatch,theprogramwillrunthe“default”clauseandignoretherest of the statement. InPHP, youmayuse a “break” statement to terminate the code’sexecution and pass the control to the succeeding scripts. Most programmers place thebreakstatementatthelastpartoftheswitchstructure.Analyzethefollowingexample:

switch($solution){

case‘x’:

case‘x’:

print“Thesolutioniscorrect\n”;

break;

case‘u’:

case‘U’:

print“Thesolutionisincorrect\n”;

break;

default:

print“Error:Thesystemdoesn’trecognizethesolution\n”;

break;

}

TheLoopStructures

YoucanuseloopstructurestorepeatcertainprocessesinyourPHPscripts.Forinstance,youcanusea“loop” to submit the resultsofaquerymultiple times. In thispartof thebook,you’lllearnabouttheloopstructuressupportedbythePHPlanguage:

The“while”Loop

Whenwritinga“while”loop,youshouldusethefollowingsyntax:

while(expression)

statement/s

Mostprogrammersconsider“while”loopsasthesimplesttypeofloopsinanylanguage.Atthestartofeachrepetition,theprogramwillevaluatetheloop’struthexpression.Iftheexpression’sresultistrue,theloopwillrunallthestatementsinsideit.Iftheresultisfalse,however,theloopwillendandpasstheprogramcontroltothestatementsafterit.

The“break”and“continue”Clauses

InPHP,“break”clausesand“continue”clausesrequirethefollowingsyntax:

break;

breakexpression;

continue;

continueexpression;

Therearetimeswhenyouneedtoendtheloopduringaniteration.Becauseofthis,PHPoffers “break” statements. If a break statement appears as a single line (i.e. break;), theprogramwillaffecttheinnermostloop.Youcanspecifythemaximumlevelsyouwanttoworkonbysettinganargumentforyour“break”clause.Here’sthesyntax:

breakx;

The“do…while”Loop

Thisisthesyntaxthatyoushouldusewhilewritinga“do…while”loop.

do

statement/s

while(expression);

A“do…while”loopislikeanordinary“while”loop.Theonlydifferenceisthata“do…while”loopchecksitstruthexpressionbeforeendingeachiteration.Basically,thiskindofloop makes sure that your statement/s will run at least once, regardless of the truthexpression’svalue.

Programmers use “do… while” loops to terminate code blocks upon satisfying apredeterminedcondition.Here’sanexample:

do{

statement/s

if($sample){

break;

}statement/s

}while(false);

Sincea“do…while”looprunatleastonce,thestatementorstatementsyouplaceinsidethis loop will run once only. Additionally, the value of its truth expression alwaysevaluates to false.PHPallowsyou toplacebreakclauses insidea“do…while” loop toterminate its execution anytime.Obviously, youmay use this kind of loop to facilitatetypicalreiterationprocesses.

The“for”Loop

The“for”loopofPHPissimilartothatoftheClanguage.Thiskindoflooptakesthreeparameters:

for(start_expression;truth_expression;increment_expression)

Usually,programmersuseasingleexpressionforeachpartoftheloop(i.e.truth,start,andincrement).Thus,youcanusethefollowingsyntaxtocreateabasic“for”loop:

for(expression;expression;expression)

statement/s

ThePHPinterpreterevaluatesthe“start_expression”once.Thisexpressioninitializesthecontrol variable of the loop it belongs to. The element named “truth_expression”,meanwhile,runsatthestartofeachloopiteration.Allofthestatementswithinthe“for”loopwillruniftruth_expressionevaluatestotrue;ifitevaluatestofalse,theloopwillend.The interpreter checks the increment_expression before ending each iteration.Programmers use the increment_expression to adjust the value of the loop’s controlvariable.

Youcaninclude“continue”and“break”statementsinyour“for”loops.Keepinmindthat“continue”forcesthePHPinterpretertoevaluate“increment_expression”beforechecking“truth_expression.”Thefollowingexamplewillshowyouhowa“for”loopworks:

for($x=0;$x<5;$x++){

print“Thesquareofthisvariableis“.$x*$x.“\n”;

}

JustlikeC,PHPallowsyoutoprovidemultipleexpressionsforeachargumentoftheloop.Youjusthavetodelimitthoseexpressionsusingcommas.Ifyouwillusethisoption,eachargumentwilltakethevalueofitsrightmostexpression.

Additionally, youdon’t have toprovide arguments foryour “for” loops.The interpreterwilljustassumethatthemissingargumentsevaluatetotrue.Forinstance,thecodesnippetgivenbelowwillruncontinuously:

for(;;){

print“Thisloopisinfinite\n”;

}

Clickhereortheimagebelowtocheckouttherestof“PHP:LearnPHPIn24HoursOrLess–ABeginner’sGuideToLearningPHPProgrammingNow”onAmazon.

©Copyright2016byRobertDwight-Allrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopic and issue covered. The publication is soldwith the idea that the publisher is notrequired to render accounting, officially permitted, or otherwise, qualified services. Ifadviceisnecessary, legalorprofessional,apracticedindividual in theprofessionshouldbeordered.

From a Declaration of Principles which was accepted and approved equally by aCommittee of the American Bar Association and a Committee of Publishers andAssociations.

Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithinis thesolitaryandutterresponsibilityof therecipientreader.Under no circumstances will any legal responsibility or blame be held against thepublisher for any reparation, damages, ormonetary loss due to the information herein,eitherdirectlyorindirectly.

Respectiveauthorsownallcopyrightsnotheldbythepublisher.

Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.

Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkis without permission or backing by the trademark owner. All trademarks and brandswithin this book are for clarifying purposes only and are the owned by the ownersthemselves,notaffiliatedwiththisdocument.

top related