![Page 1: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/1.jpg)
![Page 2: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/2.jpg)
![Page 3: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/3.jpg)
SQL:
LearnSQLin24HoursOrLess
ABeginner’sGuideToLearningSQLProgrammingNow
![Page 4: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/4.jpg)
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
![Page 5: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/5.jpg)
HowtoDropaView
Chapter6:DatabaseSecurity
TheSecurityModelofSQL
CreatingandDeletingaRole
GrantingandRevokingaPrivilege
Conclusion
Bonus:PreviewOf“PHP:LearnPHPIn24HoursOrLess–ABeginner’sGuideToLearningPHPProgrammingNow”
ConditionalStructures
TheLoopStructures
![Page 6: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/6.jpg)
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
![Page 7: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/7.jpg)
![Page 8: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/8.jpg)
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.
![Page 9: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/9.jpg)
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.
![Page 10: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/10.jpg)
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.
![Page 11: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/11.jpg)
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.
![Page 12: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/12.jpg)
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.
![Page 13: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/13.jpg)
![Page 14: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/14.jpg)
Chapter2:TheEnvironmentoftheSQLLanguage
ThischapterwillfocusontheSQLenvironment.Itwillexplainlanguagecatalogsandteachyouhowtocreatedatabasesandschemas.Readthismaterialcarefully:itwillhelpyoulearntheSQLlanguageinjustoneday.
![Page 15: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/15.jpg)
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.
![Page 16: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/16.jpg)
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.
![Page 17: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/17.jpg)
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.
![Page 18: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/18.jpg)
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.
![Page 19: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/19.jpg)
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.
![Page 20: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/20.jpg)
Youcanuseanyword,eventhereservedkeywordsofSQL.
QualifiedIdentifiers
SQLqualifiestheidentifierofeachschemaobjectbasedonitspositionintheenvironment’shierarchicalstructure.Aqualifiedidentifiercontainsthenameoftheobject,schemaandcataloginvolved(i.e.youneedtoseparatethesevaluesusingperiods).Forinstance,let’sassumethatyou’reworkingonatablecalledBook_Authors.ThistableislocatedinaschemanamedBook_List,whichisstoredintheBookcatalog.ThequalifiedidentifierforthistableisBook.Book_List.Book_Authors.
![Page 21: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/21.jpg)
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
![Page 22: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/22.jpg)
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.
![Page 23: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/23.jpg)
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.
![Page 24: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/24.jpg)
![Page 25: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/25.jpg)
Chapter3:HowtoGenerateandModifyTables
InSQL,tablesserveastheprimarytoolformanagingdata.Almostalloftheprogrammingyou’lldoislinkedtooneormoretables.Consequently,priortoinsertingdataintoadatabase,youneedtomakesurethatthecorrecttablesexist.
ThischapterwillteachyouhowtogenerateandmodifyanSQLtable.Readthischaptercarefully–itwillhelpyoulearnSQLinjust24hours.
![Page 26: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/26.jpg)
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:
![Page 27: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/27.jpg)
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)]
![Page 28: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/28.jpg)
{(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
![Page 29: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/29.jpg)
commandcreates.
Atthispoint,let’sdiscusshowyoucanspecifythedatatypeofyourcolumns.Youneedtomasterthistopicsincedatatypesplayanimportantroleinthecreationofanycolumn.
![Page 30: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/30.jpg)
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:
![Page 31: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/31.jpg)
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.”
![Page 32: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/32.jpg)
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).
![Page 33: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/33.jpg)
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.”
![Page 34: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/34.jpg)
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.”
![Page 35: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/35.jpg)
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.
![Page 36: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/36.jpg)
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.
![Page 37: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/37.jpg)
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:
![Page 38: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/38.jpg)
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).
![Page 39: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/39.jpg)
HowtoDeleteanSQLTable
InSQL,deletingtablesandtheircontentsiseasyandsimple.Hereisthesyntaxthatyouneedtouse:
DROPTABLE(nameoftable)[RESTRICT|CASCADE]
Whenusingthiscommand,youhavetochooseeitherRESTRICTorCASCADE.TheRESTRICToptiondeletesthetableifnootherobjects“depend”onit.CASCADE,however,removesthetableandalloftheobjectsthatpointtoit.Forinstance,thecommandgivenbelowremovesthetablenamedAUTHORSandallofitscontents,evenifobjectscurrentlypointtoit:
DROPTABLEAUTHORSCASCADE;
![Page 40: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/40.jpg)
![Page 41: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/41.jpg)
Chapter4:HowtoEnsureDataIntegrity
SQLdatabasesdon’tjuststoreinformation.Theyneedtomakesurethattheinformationtheystoreisreliable.Iftheinformation’sintegrityhasbeencompromised,itsreliabilitybecomesquestionable.Ifthedataisunreliable,thedatabasethatcontainsitalsobecomesunreliable.
Tosecuredataintegrity,SQLoffersawiderangeofrulesthatcanlimitthevaluesatablecanhold.Theserules,knownas“integrityconstraints,”workoncolumnsandtables.Thischapterwillexplaineachkindofconstraint.Itwillalsoteachyouhowtoapplythesaidconstraintstoyourowndatabase.
![Page 42: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/42.jpg)
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.
![Page 43: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/43.jpg)
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.
![Page 44: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/44.jpg)
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
![Page 45: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/45.jpg)
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);
![Page 46: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/46.jpg)
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.
![Page 47: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/47.jpg)
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
![Page 48: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/48.jpg)
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
![Page 49: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/49.jpg)
(AUTHOR_IDINT,
AUTHOR_NAMECHARACTER(50)->UNIQUE,
PUBLISHER_IDINT,
CONSTRAINTPK_PUBLISHER_IDPRIMARYKEY(PUBLISHER_ID));
![Page 50: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/50.jpg)
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
![Page 51: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/51.jpg)
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.
![Page 52: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/52.jpg)
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
![Page 53: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/53.jpg)
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.
![Page 54: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/54.jpg)
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.
![Page 55: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/55.jpg)
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.
![Page 56: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/56.jpg)
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.
![Page 57: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/57.jpg)
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);
![Page 58: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/58.jpg)
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,
![Page 59: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/59.jpg)
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‘)));
![Page 60: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/60.jpg)
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),
![Page 61: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/61.jpg)
STOCK_AVAILABILITYINT,
CONSTRAINTTS_STOCK_AVAILABILITYCHECK((STOCK_AVAILABILITYBETWEEN1AND50)OR(STOCK_AVAILABILITYBETWEEN79AND90)));
ThiscodeusesBETWEEN(i.e.anotherSQLoperator)tosetarangethatincludesthelowestandhighestpoints.Becauseithastworanges,itseparatestherangespecificationsusingparentheses.TheORkeywordconnectstherangespecifications.Basically,ORtellsSQLthatoneoftheconditionsneedtobesatisfied.Consequently,thevaluesyouwillenterinthecolumnnamedSTOCK_AVAILABILITYshouldbefrom1through50orfrom79through90.
![Page 62: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/62.jpg)
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.
![Page 63: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/63.jpg)
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).
![Page 64: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/64.jpg)
![Page 65: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/65.jpg)
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.
![Page 66: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/66.jpg)
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.
![Page 67: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/67.jpg)
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
![Page 68: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/68.jpg)
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
![Page 69: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/69.jpg)
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,
![Page 70: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/70.jpg)
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.
![Page 71: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/71.jpg)
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.
![Page 72: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/72.jpg)
HowtoDropaView
Insomecases,youneedtodeleteaviewfromadatabase.Toaccomplishthistask,youneedtousethefollowingsyntax:
DROPVIEW(nameoftheview);
Thesystemwilldeletetheviewassoonasyourunthisstatement.However,theprocesswon’taffecttheunderlyinginformation(i.e.thedatastoredinsidetheactualtables).Afterdroppingaview,youmayrecreateitoruseitsnametogenerateanotherview.Let’sanalyzeabasicexample:
DROPVIEWBOOK_PUBLISHERS;
ThiscommandwilldeletetheBOOK_PUBLISHERSviewfromthedatabase.However,theunderlyinginformationwillbeunaffected.
![Page 73: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/73.jpg)
![Page 74: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/74.jpg)
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.
![Page 75: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/75.jpg)
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.
![Page 76: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/76.jpg)
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;
![Page 77: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/77.jpg)
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}
![Page 78: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/78.jpg)
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
![Page 79: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/79.jpg)
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:
![Page 80: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/80.jpg)
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’;
}
![Page 81: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/81.jpg)
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’;
}
![Page 82: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/82.jpg)
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”;
![Page 83: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/83.jpg)
break;
}
![Page 84: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/84.jpg)
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.
![Page 85: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/85.jpg)
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;
![Page 86: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/86.jpg)
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.
![Page 87: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/87.jpg)
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:
![Page 88: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/88.jpg)
for(;;){
print“Thisloopisinfinite\n”;
}
Clickhereortheimagebelowtocheckouttherestof“PHP:LearnPHPIn24HoursOrLess–ABeginner’sGuideToLearningPHPProgrammingNow”onAmazon.
![Page 89: SQL: Learn SQL in 24 Hours or Less - A Beginner’s Guide To …iliasoft.ir/Download/SQL_Robert_Dwight.pdf · 2016-05-06 · syntax of important SQL commands. If you want to become](https://reader034.vdocument.in/reader034/viewer/2022042711/5f7df671f179842862411bb2/html5/thumbnails/89.jpg)
©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.