SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning...
Transcript of SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning...
SQL
EasySQLProgramming&DatabaseManagementForBeginners.YourStep-By-StepGuideToLearningTheSQLDatabase.
FelixAlvaro
Acknowledgments
Firstly,IwanttothankGodforgivingmetheknowledgeandinspirationtoputthisinformativebooktogether.Ialsowanttothankmyparents,mybrothersandmypartnerSilviafortheirsupport.
TableofContents
ChapterOne:SQLOverview-HistoryofSQL-UsesofSQL
-PeopleUsingSQL
ChapterTwo:TheDatabaseEssentials-DatabaseFundamentals-RelationalDatabaseFundamentals-DatabaseManagementSystemsChapterThree:TheSQLStructure
-SQLFundamentalFeatures-SQLCommandTypes-SQLiteDatabaseFeaturesandInstallationInstructions
-
ChapterFour:DataTypes-DefinitionofData-TypesofData-User-DefinedDataTypeChapter
Five:DataDefinitionLanguageStatements-CREATEStatement-ALTERStatement-DROPStatementChapter
Six:DataManipulationLanguageStatements-INSERTStatement-UPDATEStatement-DELETEStatement
ChapterSeven:DataQueryLanguageStatements-SELECTStatement-WHEREStatement-ORDERBYandGROUP
BYStatementsChapterEight:TransactionalControlCommands-COMMITCommand-ROLLBACKCommand-SAVEPOINT
CommandChapterNine:DatabaseViews-DefiningViews-CreatingViews-DroppingViewsChapterTen:
EnhancingDatabaseDesigns-AssigningPrimaryandForeignKeys-UnderstandingIndexes-NormalizingDatabasesChapterEleven:DatabaseAdvanceTopics
-Cursors-Triggers-ErrorsRecap+FinalWords-RecapandFinalwords-Checkoutmyotherbooks
©Copyright2016byD.A.Alvaro-Allrightsreserved.Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.Itisnotlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibited.
IntroductionHithere!ThankyousomuchfordownloadingthiseBookinSQL
ProgrammingandDatabaseManagementforBeginners.Iassureyouthatyouhavemadeawisedecisionininvestinginyourskillsasadatabaseprofessional.ThiseBookwillteachyouvitalinformationonthefundamentalsofdatabaseprogrammingandmanagementusingoneofthepowerfulsoftwaretools–theSQLlanguage.IamFelix,whoalsostartedasasimpleanalystandnowprogressingintobecomingadatabasescientist.ThroughtheguidanceofthiseBook,youwillhaveabetterunderstandingofthecountlessopportunitiesthatthisSQLlanguagecanbringyou.Iwillbepresentingyoustep-by-stepinstructionsinlearningtheessentialskillsofthisreliabledatabasesoftware.
Atfirst,IdidnotrealizehowimportantitisforonetocomprehendSQLifthereareotherprogramapplicationsyoucanuse,suchasMicrosoftExcel,toprocessandpresentinformation.WhenIstartedresearchingforthevalueofSQL,ItoldmyselfthatifIcontinueembarkingonthisfieldthenIwillnotjustbepresentinginformationbutanalyzingdataaswell.Afterdownloadingandinstallingthesoftware,IhavefoundoutthatitisnotthatchallengingtostudySQLprogrammingafterall!Takingthatfirststeptounderstandingthebasicdatabaseconceptswillleadyoutoexpandingyourknowledgeinbecomingoneofthemostsought-afterITprofessionals.
Thecurrenttrendininformationtechnologyistobemoredigital,whichentailsmanipulatingdatabases.ThisiswhereSQLcomesinplace–asoftwarelanguagethatispowerfulyetsimple,flexible,portableand,mostofall,integratedintonumerousdatabaseapplications.Decidingtobecomeadatabaseprofessionalwilldefinitelypromiseyouasecuredjobwithapotentialhighremuneration.Ontheaverage,asimpledatabaseanalystintheUnitedStatesearnsanannualsalaryofaround$92,000USD.
Tostartyourjourneyinthisfieldofdatabaseprogrammingandmanagement,letthiseBookserveasyourinitialguideineducatingyourselfwiththebasicsofSQL.Iwillprovideyouanoverviewofhowthelanguagestarted,thevariousfeaturesofthesoftwareanditsenvironment,thedifferentcommandsandfunctions,theavailableerror-handlingtools,someadvancedtopicsandmanymore!MyultimateaimisforyoutoappreciatethepotentialsofSQLandgrasptheprogrammingconceptsinacoolway.Sowhatareyouwaitingfor?Letusgetstarted!
ChapterOne:SQLOverview
InthischapteryouwilllearnabriefbackgroundonhowandwhySQLcameintoexistence.GainingknowledgeonthehistoryofthiscomputerlanguagewillhelpyouunderstanditsimportancetomostITprofessionalswhofocusonthefieldofdatamanipulation.YouwillalsohaveanideaonhowtomaximizethepotentialsofSQLintheever-changingworldofInformationTechnology.
Thecurrenttrendinmostbusinessestodayistoinvestintechnologythatwillgatherdatainthemostefficientandeffectiveway.However,gatheringinformationisonlythestartoftheextensiveprocessofdatamanipulation.Companies,especiallymultinationalones,requireexpertswhopossesstheskillsofanalyzing,presenting,managingandstoringdata.Inotherwords,theyneedtousecomputerprogramsthatwilltransformrawcompanydatatousefulinformation.Now,thankstoStructuredQueryLanguage,orsimplySQL,thatbroughtaboutsuchtransformationinaccessingandmanipulatingdatainaverymeaningfulway.
HistoryofSQL
Pronouncedasees-que-ellorsee’qwl,SQLisacomputerlanguageinitiallyinventedbyanAmericanmultinationaltechnologyandconsultingcompanyknownasIBM(InternationalBusinessMachinesCorporation)wayback1970susingDr.E.F.Codd’spaperon“ARelationalModelofDataforLargeSharedDataBanks”fortheprototypedesign.ItwasoriginallycalledSEQUEL(StructuredEnglishQUEryLanguage)thathandledqueriesonthecollectionandorganizationofdata-orsimplyknownasadatabase.Morefeatureswereaddedtothecomputersoftwaretoimproveitsperformance,likebuildingandmanagingdatabasesecurity,amongothers.WhenIBMresearcherslearnedthatthereisanothercompanythathadthesame“Sequel”trademark,theyrenameditto“S-Q-L”(presentlyexpandedasStructuredQueryLanguage).
Sinceitwasfirstreleasedtothepublic,SQLalreadyhadmanyversions.In1979,RelationalSoftware,Incorporated(whichlaterbecametheOracleCorporation)releasedORACLE,thefirstSQLproduct.Now,asthedemandforcomputersthatmanagedatahasincreased,themoreSQLhasbecomeanindustrystandardinthefieldofInformationTechnology.SuchformalstandardissetandmaintainedbytheInternationalStandardsOrganization,orsimplyknownasISO.Itwason1986,basedonIBM’simplementation,thatSQLhasbeenrecognizedasthestandardlanguageindatabasecommunication.Thefollowingyear,ISOacceptedANSISQLastheinternationalstandard.ANSIstandsforAmericanNationalStandardsInstitute,whichisanorganizationthatapprovescertainstandardsinvariousUSindustries.Manyrevisionsofthestandardsfollowed,suchasin1992(SQL-92)andin1999(SQL-99).ThelatestoneisnowcalledSQL-2011,whichwasofficiallyreleasedinDecember2011.
UsesofSQL
Thecorporateworldisnowshiftingfrommerelyproducingproductsandprovidingservicestoinvestingindigitaltechnologiesthathandlevastamountsofdata,tobetransformedtomeaningfulpiecesofinformationthatwillgeneratemoreprofitableincomeforthecompany.ThisistheprimaryobjectiveofSQL–toaccessandmanipulatedatathatwillfurtherleadtobusinessinsights.Thisflexiblecomputerlanguagehasbeenthemostwidelyusedcommunicationtoolinhandlingdatabases(specificallyrelationaldatabasesthatwillbefurtherdiscussedinChapter3ofthisbook).
Trytoimaginethatyouaregoingtoaforeigncountryforavacation.Youmayneedtolearnthatcountry’slanguagetofindyourwayaroundasyouexplorethenewplace.Whenyoutryasksomeonefordirections,whoislocaltothatplaceandonlyspeaksthecountry’slanguage,thensurelyyouwillhaveahardtimeunderstandinghim.Inthisscenario,theforeignlandwillbeyourdatabaseinwhichyouneedtoseekinformationwhileSQListhelanguagethatyouwillusetogetwhatyouneedfromthedatabase.
Fromtimetotime,youwillencounterthetermquery,whichisalsoapartoftheabbreviationofSQL.QueryisbasicallythequestionwrittenusinganSQLstatementthatisbeingaskedfromthedatabase.SQLthenretrievestheneededinformationwhenanyofthedatainthedatabasemeetstherequirementsoftheconditionsofthegivenquery.Soinreal-lifeapplications,suchasanonlinestore,whenyouexecuteyourqueryforaspecificitembyenteringyoursearchcriteria,SQLprogrammingusuallytakesplaceinthebackgroundtomanagethedatabaseconnections.Youareactuallytellingthedatabase,throughthehelpofSQL,whatinformationyouwanttoseeandhowyouwantittobepresentedtoyou.
PeopleUsingSQL
SQLisnotonlyapplicableforITprofessionalsorgeekswhopossessremarkableprogrammingskills.Withthegrowingcorporateworldoftoday,non-ITpersonnelsuchasbusinessmenandmanagers,canalsobenefitfromlearningthesemanticsofSQL.Thisisbecausethecomputerlanguageenablesthemtounderstandtheinsandoutsoftheirbusinessesusingthedatathatdriveseverycompany.Moreover,itopensseveralcareeropportunitiesintheanalytical,managerial,strategicorresearchfields-forthosewhowanttostep-upfromtheircurrentpositions.OntheITfield,SQLknowledgecanleadtomorechallengingrolessuchasdatabasedesigners,administratorsorscientists,systemsengineers,projectmanagersandsoftwaredevelopers,amongothers.
InthischapteryouhavelearntanoverviewofSQL–itshistory,itsprimarypurposewhyitwascreatedandthosewhowillprofitfromlearningthispowerfuldatabasesoftware.Inthenextchapteryouwilllearntheessentialsofdatabase,whichistheprimaryreasonwhySQLwasdesignedinthefirstplace.
ChapterTwo:TheDatabaseEssentials
BeforeyoustartlearningthetechnicalitiesofSQLasacomputerlanguage,thischapterwilldiscussfirstwhatadatabaseisanditsfundamentalcharacteristics.Youwillalsobeinformedwhythebusinessworldisnowdriventogatherandmanipulatedatatobringforthmoreprofitableincome.
DatabaseFundamentalsTherearemanywaysonhowtodefineordescribewhatadatabaseis.Insimpleterms,itcanbedefinedasacollectionofitemsthatcanexistoveralongperiodoftime.Thinkofacallingcardholderasadatabasethatcontainsbusinesscardswithdifferentinformationofpeoplethatyouknow(e.g.person’sname,jobtitle,companyname,contactnumber).Anotheroneisaprintedtelephonedirectory(morepopularlyknownastheyellowpages)thatcontainsthename,phonenumberandaddressoftheregisteredresidentslivinginaparticulararea.
Somedefinedatabasemoreprofessionally,notjustacollectionofdata.Itisdescribedasanorganizedtoolcapableofkeepingdataorinformationthatyoucanretrieveinaneffectiveandefficientwaywhentheneedarises.Itcanalsobemorestrictlydefinedasaself-describingcollectionofobjectsthatareintegratedtooneanother.Whenyoucreaterepresentationsofthesephysicalorconceptualobjectsthentheywillbecalledrecords.Fromthepreviousexampleofyourcallingcardholder,ifyouwishtokeeptrackofyourbusinesscontactsthenyouhavetoassigneachbusinesscardaspecificrecord.Everyrecordcontainsmultipleinformationordata,suchasindividualname,jobtitle,companynameandaddress,phonenumberandmorethatyouwillnowcalltherecord’sattributes.
Adatabasedoesnotonlycontainthedatathatyouneed,butalsowhatyoucallitsmetadata.Thisistheinformationthatdefinesordescribesthedata’sstructurewithinthegivendatabase(thatiswhyitwasdefinedearlierasaself-describingentity),storedinaregioncalleddatadictionary.Thus,dataretrieval
willbefasterifyouknowhowinformationisarrangedandstored.Furthermore,relationshipsexistamongthedataitemssincetheyareintegratedtooneanother.Checkthefollowingfigureforasampleillustrationofwhatadatabaseis.
Whetheradatabasecontainsasimplecollectionofafewrecordsoramassivesystemcomposedofmillionsofrecords,itcanbecategorizedintothreetypes:personal,workgroupordepartmental,andenterprise.Eachcategoryischaracterizedbythedatabasesize,themachinerysizeintowhichthedatabaserunsandhowbigtheorganizationthatmanagesit.
PersonalDatabase–Thisisconceptualizedanddesignedbyasinglepersononastand-alonecomputer.Itsdatabasestructureisrathersimpleandthesizeisrelativelysmall.Forexample,yourpersonalelectronicaddressbook.Workgroup/DepartmentalDatabase–Thisisdesignedandcreatedbyindividualsofasingleworkgroupordepartmentwithinacertainorganization.Thedatabasestructureislargerandmorecomplex,ascomparedtothepersonalcategory,whichisalsoaccessedbymultipleusersatthesametime.EnterpriseDatabase–Amongthethreecategories,thistypeisconceptualizedandcreatedtohandletheentireflowofinformationofverylargeorganizations.Thus,thedatabasedesigninvolvesfarmore
complexstructures.
RelationalDatabaseFundamentalsTakingthediscussionfurtherintoamoretechnicalaspect,arelationaldatabaseisanentityconsistingoflogicalunitsknownastables.ThisrelationaldatabasemodelwasfirstformulatedbyDr.E.F.Coddin1970.Howthetablesarerelatedtoeachotherdefinestheirrelationships.Inthisscenario,dataissimplifiedintosmalleryetmorelogicalandmanageableunitsthatoptimizethedatabaseperformance.Thefollowingfigureshowsanillustrationonhowthevariouscomponentsofarelationaldatabaseareconnectedtoeachother.
Atableconsistsofrowsandcolumnsthatstoredata.Inarelationaldatabase,thesetablesarerelatedtooneanotherimprovingthedataretrievalprocesswhenaqueryissubmittedbytheuser.Foryoutoclearlypictureoutthisidea,converttheinformationfoundonthecallingcardholderintoaspreadsheetlikeaMicrosoftExcelfile.Assumethattheseareyourcontactsfromcompaniesthathaveorderedproductsandservicesfromyourbusiness.YouwillhaveatleastaCUSTOMERTABLE(containingallimportantinformationaboutyourcontacts)similartothefollowing:
CUSTOMERID
NAME POSITION COMPANY STATE CONTACTNO
1
KathyAle
President TileIndustrial
TX 3461234567
2 KevinLord
VP BestTooling
NY 5181234567
3 KimAsh
Director CarWorld CA 5101234567
4 AbbyKarr
Manager WestMart NV 7751234567
YouwillalsohaveanORDERTABLEthatwillstoreinformationsuchasorderID,date,quantityandmore.Checkthefollowingtable:
ORDERID
ORDERDATE
CUSTOMERID
PRODUCTID
ORDERQTY
1 2016-05-23 1 4 3002 2016-09-09 1 5 1003 2016-02-17 3 2 1504 2016-05-12 2 2 500
Asyoucansee,eachtablelookslikeanarrayofrowsandcolumns.ReferringtotheCUSTOMERTABLE,arowisalsocalledarecordoratuplethatholdsinformationforasinglecustomer.Ontheotherhand,acolumnholdsasingleattributeofthecustomer(i.e.,name,jobtitleorposition,companynameandaddress,contactnumber).Itisalsoself-consistent,meaningitcontainsthesametypeofdataineveryrow.Soifacolumncontainsthenameofyourcustomerinthefirstrow,thenthesucceedingrowswillhavetoshowthenamesofyourothercustomers.Thereisalsonosignificancewhichroworcolumnwillappearfirstandwhichwillbenext,sincethereisnoparticularorganizationthatisfollowed.Lookingatbothtables,youwillnoticethateachoneofthemhasacolumnthatcontainsthesamedatavalue–CUSTOMERID.Thisisnowcalledthecommonkey,whichlinksthetablestooneanotherinarelationaldatabase.Theexistenceofthecommonkeysmakesitpossibletomergedatafrommultipletablesinformingalargersetofdataentity.
Therelationbetweenthetwotablesconsistsofatwo-dimensionalarrayofdatastoredinrowsandcolumns.Theintersectionofarowandacolumniscalledacell.Eachcellcontainssinge-valuedentriesandeachrowisunique.Thus,eachcellhasonlyonevalueandnoduplicaterows.GoingbacktotheCUSTOMERandORDERTABLES,willbeabletocreatethefollowingrelationbyaddingtheCUSTOMERNAMEthatcorrespondstothegivenCUSTOMERID:
ORDERID
CUSTOMERID
CUSTOMERNAME
1 1 KathyAle2 1 KathyAle3 3 KimAsh4 2 KevinLord
Youwillseethatthereisnoemptycell.OneparticularorderreferencedbytheORDERIDisassociatedtoaparticularcustomer,indicatedbytheCUSTOMERIDandCUSTOMERNAME.TherearenotwocustomershavingthesameORDERID.Thatiswhy,therewillbenotworowsthatareexactlyidentical.
DatabaseManagementSystemsAdatabasemanagementsystem,orsimplyDBMS,isanimportantprogrammingtoolthatconsistsofasetofprogramsthatdefine,manageandprocessdatabasesandallapplicationsassociatedtothem.Throughthis,youareabletobuildastructureandoperateonthevaluabledatathatthedatabaseholdsinaveryefficientway.TherearetwomaintypesofusersthatworkonDBMS–theconventionaluserwhoretrievesormodifiesdataandtheadministratorwhoisresponsibleformaintainingthestructureofthedatabase.
ThefollowingarethekeyfeaturesofaDBMS:
AllowsthecreationofnewdatabasesandtheirdatastructuresAllowsdataqueryandmodificationusinganappropriateprogramminglanguageAllowsthestorageofvastamountsofdataoveralongperiodoftime
Enablesdatabaserecoveryintimesoffailure,errororintentionalmisuseControlsdataaccessfrommanyusersatonce
Itwasduringthelate1960swhenthefirstcommercialDBMSappeared.Itevolvedfromfilesystemsthatbasicallyprovideddatastorageforoveracertainperiodoftime.Thoughsuchsystemswerecapableofstoringtremendousamountofdata,computerprofessionalsstillhavetofaceproblemsofdatalossandaninefficientinformationretrievalsystem.Therewerealsoissuesoncontrolaccesswhereerrorsoccurwhentwousersmodifythesamefileatthesametime.Someexamplesoftheseapplicationsareairlinereservationsystems,bankingsystemsandcorporaterecordkeepingsystems,amongothers.
Withtheadvancementoftechnologyinthemarkettoday,youcanfindnumerousprogramsthatwillbesuitableforyourDBMSrequirements.Thereareapplicationsthatrunonasmallscalelevellikeyourpersonalcomputerortablet.Somearebuilttorunonalargeandpowerfulequipment,likethosebeingusedbymultinationalcompanies.Nevertheless,theon-goingtrendisforDBMStobeexecutedonmultipleplatformsormachines(whetherlargeorsmall)thatareinterconnectedtooneanother,forminganimmensescalablenetwork.ITexpertshavealsofoundwaysonhowstoredatausingInternettechnologyinpowerfuldatacentersormorepopularlyknownasclouds.Thiscloudcanbepublicentity(managedbyalargecompanylikeMicrosoftorGoogle)oraprivateone(maintainedandstoredviatheintranetwithinanorganization).
Inthischapteryouhavelearnttheessentialfeaturesofadatabaseandhowittransformstobecomearelationaldatabase.Also,youhadanoverviewofthehistoryandcharacteristicsofdatabasemanagementsystems.InthenextchapteryouwilllearnthefundamentalstructureoftheSQLlanguageanditscomponents.
ChapterThree:TheSQLStructure
InthischapteryouwilllearnthefundamentalfeaturesoftheSQLlanguageandanoverviewofitsprogrammingaspect.Inaddition,youwillbepresentedwithastep-by-stepinstructiononwhereandhowtodownloadSQLite,aversionoftheSQLsoftwarethatwillbeusedallthroughoutthediscussionofthise-Book.
SQLFundamentalFeaturesSQLisaflexiblecomputerlanguagethatyoucandeployindifferentwaystocommunicatewithrelationaldatabases.Thissoftwarehassomedistinctfeaturesthatdifferentiatesitfromotherprogrammingapplications.Firstandforemost,SQLisanonprocedurallanguage.Mostcomputerprograms(e.g.,C,C++andJava)solveproblemsbyfollowingasequenceofcommandsthatiscalledaprocedure.Inthiscase,onespecificoperationisperformedafteranotheruntiltherequiredtaskhasbeenaccomplished.Theflowofoperationcaneitherbealinearsequenceoraloopingone,dependingonwhattheprogrammerhadspecified.ThisisnotthesameforSQL.Inusingthisapplication,youwilljusthavetospecifytheoutputthatyouwant,nothowyouwanttogeneratetheoutput.FromtheCUSTOMERTABLE,ifyouwanttocreateaseparatelistofcontactswhosecompanyarelocatedinTexasthenyouhavetoretrievetherowswheretheSTATEcolumncontains“TX”asitsvalue.InwritingtheSQLcommand,youdon’thavetoindicatehowtheinformationshouldberetrieved.Itistheprimaryroleofthedatabasemanagementsystemtoexaminethedatabaseanddecidehowtogeneratetheresultsyouwanted.
LearningtheSQLsyntaxislikeunderstandingtheEnglishlanguagestructure.Itscommandlanguage,comprisedofalimitednumberofstatements,performsthreeprimarydatafunctions-definition,manipulationandcontrol.TheSQLprogramminglanguagealsoincludesreservedwordsthatareonlytobeusedforspecificpurposes.Thus,youcannotusethesewordsasnamesforvariables,tablesandcolumns;orinanyotherwayapartfromtheirintendeduse.
BelowaresomeofthemostcommonreservedwordsinSQL:2011.
ABS ALL ALLOCATE ALTER AND ANYARE ARRAY AS AT AVG BEGIN
BETWEEN BINARY BOOLEAN BOTH BY CALLCASCADED CASE CEILING CHAR CHARACTER CHECKCLOSE COLLATE COLLECT COLUMN COMMIT CONDITION
CONNECT CONSTRAINT CONVERT COUNT CREATE CURSORCYCLE DATE DAY DEALLOCATE DEC DECIMAL
DECLARE DEFAULT DELETE DESCRIBE DISCONNECT DISTINCTDOUBLE DROP DYNAMIC EACH ELEMENT ELSEEND ESCAPE EVERY EXCEPT EXECUTE EXISTS
EXTERNAL EXTRACT FALSE FETCH FILTER FLOATFLOOR FOR FOREVER FREE FROM FULL
FUNCTION FUSION GET GLOBAL GRANT GROUPGROUPING HAVING HOLD HOUR HOURS IDENTITY
IN INNER INOUT INSERT INT INTEGERINTERSECT INTERVAL INTO IS JOIN KEEPLANGUAGE LARGE LEAD LEFT LIKE LOCALLOWER MATCH MAX MEMBER MERGE METHODMINUTE MOD MODULE MONTH MULTISET NATIONALNATURAL NEW NIL NO NONE NORMALIZE
NOT NULL NUMERIC OF OFFSET OLDON ONLY OPEN OR ORDER OUT
OVER OVERLAY PARAMETER PARTITION POSITION POWERPRECISION PREPARE PRIMARY PROCEDURE RANGE RANK
REAL RECURSIVE REF REFERENCES REFERENCING RELEASERESULT RETURN REVOKE RIGHT ROLLBACK ROLLUPROW ROWS SCOPE SCROLL SEARCH SECOND
SELECT SET SIMILAR SOME SPECIFIC SQLSTART STATIC SUM SYMMETRIC SYSTEM TABLETHEN TIME TIMESTAMP TO TRANSLATE TREAT
TRIGGER TRUNCATE TRIM TRUE UNION UNIQUEUNKNOWN UPDATE UPPER USER USING VALUEVALUES VARCHAR VARYING VERSION WHEN WHENEVERWHERE WINDOW WITH WITHIN WITHOUT YEAR
IfyouthinkthatanSQLdatabaseisjustacollectionoftables,thenyouarewrong.Thereareadditionalstructuresthatneedtobespecifiedtomaintaintheintegrityofyourdata,suchasschemas,domainsandconstraints.
Schema–Thisisalsocalledtheconceptualvieworthecompletelogical
viewthatdefinestheentiredatabasestructureandprovidesoveralltableorganization.Suchschemaisconsideredametadata–storedintablesandpartofthedatabase(justliketablesthatconsistofregulardata).
Domain–Thisspecifiesthesetofallfinitedatavaluesyoucanstoreinaparticulartablecolumnorattribute.Forexample,inourpreviousCUSTOMERTABLEtheSTATEcolumncanonlycontainthevalues“TX”,“NY”,“CA”and“NV”ifyouonlyprovideproductsandservicesinthestatesofTexas,NewYork,CaliforniaandNevadarespectively.SothesefourstateabbreviationsarethedomainoftheSTATEattribute.
Constraint–Oftenignoredbutoneoftheimportantdatabasecomponents,thissetsdowntherulesthatidentifywhatdatavaluesaspecifictableattributecancontain.Incorporatingtightconstraintsassuresthatdatabaseusersonlyentervaliddataintoaparticularcolumn.Togetherwithdefinedtablecharacteristics,columnconstraintsdetermineitsdomain.UsingthesameSTATEcolumnasanexamplewiththegivenconstraintofonlythefourvalues,ifadatabaseuserenters“NJ”forNewJersey,thentheentrywillnotbeaccepted.ThesystemwillnotproceeduntilavalidvalueisenteredfortheSTATEattribute,unlessthedatabasestructureneedstobeupdatedduetosuddenbusinesschanges.
SQLCommandTypesBeforeyoustartprogramminginSQL,youneedtounderstanditsbasiccommandcategoriesinperformingvariousfunctions–databasecreation,objectmanipulation,datapopulationandupdate,datadeletion,querysubmission,accesscontrolanddatabaseadministration,amongothers.Thefollowingarethemaincategories:
DataDefinitionLanguage(DDL)
DataDefinitionLanguage(orsimplyDDL)enablesyoutocreate,changeorrestructure,andevendestroythebasicelementsthatarecontainedinarelationaldatabase.DDLfocusesonlyonthestructure,notthedatacontainedwithintheelements.Thesebasicelementsordataobjectsincludetables,schemas,viewsandmore.Havingnoindependent
physicalexistence,aviewisregardedasavirtualtableinwhichitsdefinitiononlyexistsinthemetadata.However,theview’sdatacomesfromthetable(ortables)whereyouwillderivetheview.StatedbelowaresomeofthemostcommonDDLcommands:
CREATE–Thiscommandstatementisresponsibleforbuildingthedatabasestructure.Itssyntaxis:
CREATETABLECREATEVIEW
ALTER–Thiscommandstatementisinchargeofchangingthedatabasestructureafterithasbeencreated.Itssyntaxis:
ALTERTABLEALTERVIEW
DROP–ThiscommandisthereverseoftheCREATEstatement,whichdestroysthedatabasestructure.Itssyntaxis:
DROPTABLEDROPVIEW
DataManipulationLanguage(DML)
DataManipulationLanguage(orsimplyDML)consistsofSQLcommandsthathandledatamaintenancefunctions.Thismeansthatyouareabletomanipulatethedatacontainedwithintherelationaldatabaseobjects.Thecommandstatements,whichreadlikenormalEnglishsentences,willallowyoutoenter,change,removeorretrievedata.ThefollowingaretheDMLstatementscommonlyused:
INSERT–Thiscommandstatementisusedtoinsertnewdata
valuesintoacertaintable.Toaddvaluesintoatablewithtwocolumns,usethefollowingsyntax:
INSERTINTOTABLE_NAMEVALUES(‘value1’,‘value2’);TABLE_NAMEisthenameofthetablewhereyouwillbeaddingthenewvalues.ThenumberofitemsinsidetheVALUESparenthesisrepresentsthenumberofcolumnsofthetable,whicharearrangedinthesameorderasthesaidcolumns.Ifthevaluesareofcharacterordate/timedatatypes,theyneedtobeenclosedbysinglequotationmarks.Thisisnotrequiredfornumericornullvalues(thenullvalueshouldbewrittenasNULL).
UPDATE–Thiscommandstatementisusedtomodifyoralterpre-existingdatavaluesinatable,notaddorremoverecords.Theupdateisdoneonetableatatimeormultiplerows/columnsofonetablewithinadatabase.Tochangeasinglecolumn,usethefollowingsyntax:
UPDATETABLE_NAMESETCOLUMN_NAME=‘value’[WHERECONDITION];AslongasthegivenWHEREclauseissatisfied,thenthevalueoftheCOLUMN_NAMEwillbeupdated.ThiscouldbewithinoneormultiplerecordsofthegivenTABLE_NAME.
DELETE–Thiscommandstatementdeletescertainrecordsoreventheentiretable,notdatavaluesfromspecificcolumns.Toremoveasinglerowormultiplerecordsfromatable,usethefollowingsyntax:
DELETEFROMTABLE_NAME[WHERECONDITION];TheWHEREclauseisan
importantpartofthiscommandifyouwanttodeleteselectedrowsfromtheTABLE_NAME.
DataQueryLanguage(DQL)
DataQueryLanguage(orsimplyDQL)consistsofcommandsthatperformdataselection,whichisthemainfocusofrelationaldatabaseusersintheworldofSQL.ThestatementusedisSELECTthatcanbeaccompaniedbyotherclausesoroptionssothatyourextractedresultswillbeinanorganizedandreadableformat.Youcansubmitaquerytothedatabaseusingaseparateapplicationinterfaceorjustasinglecommand-line.ThefollowingisasyntaxforasimpleSELECTstatement:SELECT[*|ALL|DISTINCTCOLUMN1,COLUMN2]
FROMTABLE1[,TABLE2];Usingtheasterisk(*)meansthatallcolumnsofthegiventableareincludedintheoutputandwillbedisplayed.TheALLoptionextractsanddisplaysallvalues,evenduplicates,foracolumn.Ontheotherhand,usingthekeywordDISTINCTpreventsduplicaterowsfrombeingincludedanddisplayedintheoutput.WhatfollowstheFROMkeywordisalistofoneormoretableswhereyouwanttogetthedata.Thecolumnsandtablesspecifiedinthesyntaxareallseparatedbycommas.
DataControlLanguage(DCL)
DataControlLanguage(orsimplyDCL)consistsofcommandsthatallowyoutomanagedataaccesswithinthedatabase.Furthermore,thedatabaseisprotectedfromaccidentalorintentionalmisusebycontrollinguserprivileges.DCLconcentratesontransactions,whichcaptureallSQLstatementsthatperformdatabaseoperationsandsavetheminalogfile.ThefollowingarethecommonDCLcommandstatements:
GRANT–Thisstatementprovidesyouwithcertainprivileges,
likegivingyouthepermissiontoaccessthedatabase.Itssyntaxis:
GRANTPRIVILEGE1,PRIVILEGE2,…TOUSER_NAME
REVOKE–Thisstatementrevokesyourprivileges,likeremovingyourpermissiontoaccessthedatabase.Itssyntaxis:
REVOKEPRIVILEGE1,PRIVILEGE2,…TOUSER_NAME
TransactionalControlCommands
Transactionalcontrolcommandsallowuserstomanipulatevarioustransactionsinmaintainingdatabaseintegrity.InSQL,transactionsbeginwhenapplicationsareexecuted.TheveryfirsttransactionisstartedattheonsetoftheSQLapplication,whilethelasttransactionisendedwhentheapplicationisterminated.Thefollowingarethecommontransactionalcontrolcommands:
COMMIT–Thisstatementcompletesatransactionbymakingthechangesyoumadetothedatabasepermanent,orsimplysavingthetransactions.Itssyntaxis:
COMMIT[WORK];Inthepreviouscommandline,thekeywordWORKisoptional.
ROLLBACK–Thisstatement’sprimaryfunctionistorestorethedatabasesystemtoitspreviousstateorundoalltheactionsthattookplaceinthetransactionlog.Itssyntaxis:
ROLLBACK[WORK];Inthepreviouscommandline,
thekeywordWORKisoptional.
SAVEPOINT–ThisstatementworkswiththeROLLBACKcommand,whereinitcreatessectionsorpointswithingroupsoftransactionsinwhichyouwillbeperformingtheROLLBACKcommand.Itssyntaxis:
SAVEPOINTSAVEPOINT_NAME;SQLiteInstallationInstructionsandDatabaseFeaturesBeforeyoustartoverwhelmingyourselfwithvariousdatabasesolutionsandSQLcommandlines,youneedtodeterminefirstyourpurposewhyyouarecreatingadatabase.Thiswillfurtherdetermineotherdatabasedesignconsiderationssuchassize,complexity,typeofmachinewheretheapplicationwillrun,storagemediumandmore.Whenyoustartthinkingofyourdatabaserequirements,youneedtoknowuptowhatlevelofdetailshouldbeconsideredinyourdesign.Toomuchdetailwillresulttoaverycomplexdesignthatfurtherwastestimeandeffort,andevenyourcomputer’sstoragespace.Toolittlewillleadtoapoorperforming,corruptandworthlessdatabase.Onceyouaredonewiththedesignphase,thenyoucandecidewhichdatabasesoftwareyoucandownloadtostartyourSQLexperience.
Forthesakeofthise-Book’sdiscussion,SQLite,asimplesoftwarelibrary,willbeusedasastarterdatabaseenginetodesign,buildanddeployapplications.Afreeandstand-alonedatabasesoftwarethatisquicktodownloadandeasytoadminister,SQLitewasdevelopedbyRichardHippandhisteamofprogrammers.Itiswasdesignedsothatitcanbeeasilyconfiguredandimplemented,whichdoesnotrequireanyclient-serversetupatall.Thus,SQLiteisconsideredasoneofthemostwidelyuseddatabasesoftwareapplicationsintheworld.
StatedbelowaresomeofthemajorfeaturesofSQLite:
Transactionsareatomic,consistent,isolatedanddurableCompilationissimpleandeasySystemcrashesandpowerfailuresaresupportedFullSQLimplementationwithastand-alonecommand-lineinterfaceclientCodefootprintissignificantlysmallAdaptableandadjustabletolargerprojectsSelf-containedwithnoexternaldependenciesPortableandsupportsotherplatformslikeWindows,Android,iOS,Mac,Solarisandmore
InusingSQLite,youneedtodownloadSQLiteStudioasyourdatabasemanagerandeditor.Withitsintuitiveinterface,thissoftwareisverylightyetfastandpowerful.Youdon’tevenneedtoinstallit,justdownload,unpackandruntheapplication.FollowthesesimplestepsindownloadingSQLiteStudioonaWindows10computer:
1. Gotohttp://sqlitestudio.pl/?act=about.Youshouldgetthefollowingpage:
2. Checktheversionofyourcomputer’soperatingsystemthenclicktheappropriatelinktostartdownloadingthesoftware.
3. Afterdownloadingthesoftware,gotothefolderwheretheapplicationwassaved(usuallytheDownloadsFolderinWindows).ClickontheExtracttabontopthenchoosetheExtractalloption.
4. YouwillgettheExtractCompressed(Zipped)Foldersdialogbox.ChangethedestinationfoldertoC:\SQLthenclicktheExtractbutton.ThiswillbethefolderwhereallyourSQLitefileswillbesaved.
5. Onceallthefileshavebeenextracted,youwillhavetheSQLiteStudiosubfolder.
6. FindtheapplicationprogramnamedSQLiteStudioinsidethesubfolder.Tocreateashortcutonyourdesktop(soyoucanquicklylaunchtheapplication),right-clickthefilename,selectSendtooptionthenchooseDesktop(createshortcut).
7. Whenyoudouble-clicktheSQLiteStudioicononyourdesktop,
8. youshouldgetthefollowingscreen:
TheDatabaseNavigator(leftpane)showsallthelogicalunitsofthedatabasesuchastablesandviews.ThegraypaneattherightistheSQLWorkAreawhereyouwillwriteyourquerystatements.Youwillhaveabetterunderstandingofthisprogram’sgraphicaluserinterfaceinthesucceedingchapters.
InthischapteryouhavelearntthefundamentalfeaturesoftheSQLdatabaselanguage,whichincludesprogramflow,syntaxcharacteristic,reservedwordslist,schema,domain,constraintandmore.ThemaincategoriesofSQLcommandswerealsointroduced,thatgovernthevariousfunctionsoftheprogramminglanguage.YouwerealsogivenaguideonhowtodownloadandinstallSQLiteandSQLiteStudioforyourapplicationsoftware.InthenextchapteryouwilllearnthedefinitionofdataanditsvarioustypessupportedbythedifferentSQLimplementations.
ChapterFour:DataTypes
Inthischapteryouwilllearnwhatdatais,itscharacteristicsandthevarioustypesthattheSQLprogramminglanguagesupports.Therearedifferentgeneraltypesofdatathatarefurthercategorizedintoseveralsubtypes.However,itisadvisablethatyouusedefineddatatypestoensuretheportabilityandcomprehensibilityofyourdatabase.
DefinitionofData
Sincedatabaseisacollectionofinformation,itcanstorenames,numbers,images,calculations,financialamounts,charactersandsoon.Thisstoredinformationiswhatyoucalldata,whichyoucanchangeormanipulateanytimeyouwant.Whenyoustartprovidingrulesonhowyouwriteandstoredata,thenyouaredealingwithdatatypes.Datatypestakeintoconsiderationthelengthallocatedbythedatabaseforeverycolumninthetableandwhatvaluesitcouldcontain-whetheritisalphanumeric,justnumbers,graphics,dateortime.Bydefiningwhatdataisstoredineachdatabasefield,youarepreventingtheoccurrenceofdataentryerrors.Thisformofvalidationthatcontrolsincorrectdatatobeenteredintothedatabaseisalsocalledfielddefinition.
Eachdatabasefieldwillhaveaspecificvalueifitcontainsadataitem.Therearetimes,however,thatacertainfielddoesnothaveanydataitematall.Inthiscase,thefield’svalueisconsiderednull-meaningthevalueisnotknown.Thisnullvalueisdifferentfromthenumericzerovalueortheblankcharactervalue,sincezeroesandblanksaredefinitevalues.Thefollowingarescenarioswhenyoumayhaveanullvalue:
Youdon’tknowwhatthevalueisyetevenifitpossiblyexists.Thevaluedoesnotexistyet.Thevalueisoutofrange.Thefieldisnotapplicableforaparticularrow.
TypesofData
ThefollowingarethegeneraldatatypespredefinedintheSQLlanguage(thatarefurthercategorizedintosubtypes):
Numeric–Thevaluedefinedbythenumericdatatypeissomekindofanumber,whichcouldeitherbeexpressedwithanexactorjustanapproximatevalue.
ExactNumeric
INTEGER–Thisconsistsonlyofwholenumbersthatarebothpositiveandnegative.Itdoesnotcontainadecimalnorafractionalpart.Thevaluerangesfrom-2,147,483,648to2,147,483,647,withanallocated4bytesofstoragesize.
SMALLINT–Thisisusedinreplacementofintegerstosavestoragespace,butwithaprecisionthatcannotbelargerthanthatofaninteger.Precisionincomputerprogrammingisthemaximumtotalofsignificantdigitsanumbercanhave.Thevaluerangesfrom-32,768to+32,767,withanallocated2bytesofstoragesize.
BIGINT–ThisisthereverseoftheSMALLINT,whereitsminimumprecisionisthesameastheINTEGERdatatypeorgreater.Thevaluerangesfrom-9,223,372,036,854,775,808to9,223,372,036,854,775,807,withanallocated8bytesofstoragesize.
NUMERIC(p,s)–Inadditiontotheintegerpart,thisdatatypealsocontainsafractionalcomponentthatindicatestheprecisionandscaleofthevalue.Scaleisthenumberofdigitsorplacesreservedinafractionalpartofthedata,locatedattherightsideofthedecimalpoint.InNUMERIC(p,s),‘p’specifiestheprecisionwhile‘s’isforthescale.Forexample,NUMERIC(6,3)meansthatthenumber’sabsolutevaluewillonlybeupto999.999(6totalsignificantdigitswith3digitsfollowingthedecimalpoint).
DECIMAL(p,s)–LiketheNUMERICdatatype,thishasafractionalcomponentwhereyoucanspecifyboththevalueprecisionandscale.However,thisdatatypeallowsgreaterprecision.Forexample,DECIMAL(6,3)cancontainvaluesupto999.999butthedatabasewillstillacceptvalueslargerthan999.999.Letussayyouenteredthenumber123.4564,thiswillberoundedoffto123.456.Theallocatedstoragesizeforthisdatatypeisbasedonthegivenprecision.
ApproximateNumeric
REAL(s)–Thisconsistsofasingle-precision,floating-pointnumberwherethedecimalpointcan“float”todifferentplacesinthesaidnumber.Thismeansthatthisdatatype’sdecimalvaluehasalimitlessprecisionandascaleofvariablelengths.Forexample,thevaluesforπ(pi)caninclude3.14159,3.14and3.1(eachvaluehasitsownprecision).Forsingle-precision,floatingpointnumbers,theirprecisionisbetween1and21inclusive.Italsoallocates4bytesofstoragesizeforitsvalues.
DOUBLEPRECISION(p,s)–Thisconsistsofa
double-precision,floating-pointnumberandthecapacityistwiceoftheREALdatatype.Thisdatatypecomesinhandywhenyourequiremoreprecisenumbers,likeinmostscientificfieldofdisciplines.Fordouble-precision,floatingpointnumbers,theirprecisionisbetween22and53inclusive.Italsoallocates8bytesofstoragesizeforitsvalues.
FLOAT(p,s)–Thisisthedatatypethatallowsyoutospecifytheprecisionandletsthecomputerdecidewhetheryouwillgoforasingle-oradouble-precision.ItactuallypertainstobothREALandDOUBLEPRECISION,dependingontheprecisionyouhavespecified.Becauseofthischaracteristic,itiseasiertomovethedatabasefromonecomputerplatformtoanother.
String–Thestringdatatypestoresalphanumericinformationandisalsoconsideredasoneofthemostcommonlyuseddatatypes.
CHARACTER(n)orCHAR(n)–Thisdatatypeisalsoknownasafixed-lengthstringoraconstantcharacter.Thismeansthatallthestringsstoredinthatparticularcolumnhavethesamelength,whichisrepresentedby‘n’(thenumberofcharactersorthemaximumallocatedlengthforthedefinedfield).Forexample,ifyousetthecolumn’sdatatypetoCHAR(23)thenthemaximumlengthofanydataenteredinthefieldis23characters.Ifthestring’slengthislessthan23,thenSQLfillstheremainingspaceswithblanks.Thisisthedrawbackofusingfixed-lengthstringsbecausestoragespaceiswasted.Ontheotherhand,ifthereisnovalueprovidedfor‘n’,thenSQLassumesalengthofonecharacter.ThemaximumlengthfortheCHARACTERdatatypeis254.
CHARACTERVARYING(n)orVARCHAR(n)–Thisisusedwhenthedataentriesareofdifferentlengths,ornotconstant,butyoudon’twantSQLtofilltheremainingspaceswithblanks.Thus,theexactnumberofcharactersyouenterwillbestoredinthedatabase-furthersavingstoragespace.Thisdatatypehasnodefaultvalueanditsmaximumlengthis32,672characters.
CHARACTERLARGEOBJECT(CLOB)–IntroducedinSQL:1999,thisvariable-lengthdatatypeisusedtocontainunicodecharacter-basedinformationthatistoobigtobestoredasaCHARACTERtype,suchaslargedocuments.ThemaximumvalueofaCLOBisupto2,147,483,647characterslong.
DateandTime–Thisdatatypemanagesanyinformationconcerningdatesandtimes.
DATE–Thisdatatypeprovidesstoragefortheyear,monthanddayvaluesofadate,inthatparticularorder.Theyearvalueisexpressedusingfourdigits,whichcanberepresentedbyanyvaluerangingfrom0001upto9999.Asforthemonthanddayvalues,theyarebothexpressedusingtwodigits.Theformatforthedatedatatypeisyyyy-mm-dd.
TIME–Thisdatatypestoresanddisplaystimevalueswithanhour-minute-secondformat(“HH:MM:SS”).
DATETIME–WhenthevaluecontainsbothdateandtimeinformationthenyouusetheDATETIMEdatatype,whichisdisplayedusingthe“YYYY-MM-DDHH:MM:SS”format.Thevalidrangeofvaluesforthistypeisfrom“1000-01-0100:00:00”to“9999-12-3123:59:59”.
TIMESTAMP–ThisissimilartotheDATETIMEdatatypebuttherangeofvaluesisfrom“1970-01-0100:00:01”UTCto“2038-01-1903:14:07”UTC.
Boolean–Thisdatatypeconsistsofvaluesthatareusedfordatacomparison:TRUE,FALSE,orNULL.Fordatatobereturned,alltheconditionsofthespecifiedcriteriaforagivenqueryshouldbemet–meaningtheBooleanvalueisTRUE.Ifdataisnotreturned,thenthevalueiseitherFALSEorNULL.
User-DefinedDataType
Afterlearningthegeneralpredefineddatatypes,youwillnowmovetouser-defineddatatypesorsimplyUDTs.Bythenameitself,thesearethedatavaluesthattheuserdefinesorspecifiesbasedontheexistingdatatypes.Thus,customizationisallowedtomaximizestoragespaceandmeetotheruserrequirements.Furthermore,databaseapplicationdevelopmentbecomesmoreflexibleforprogrammers.ThismeansthatyoucanuseUDTswhenyouneedtoenterthesametypeofdatainacolumnthatwillbedefinedinseveraltables.TodefineUDTs,youcanusetheCREATETYPEstatement.
Forexample,ifyouwanttodefineanddifferentiateUSDollarandUKPoundastwocurrenciesforyourdatabasethencreatethefollowingUDTS:
CREATETYPEUSDollarASDECIMAL(9,2);
CREATETYPEUKPoundASDECIMAL(9,2);
EvenifbothdatatypeswerecreatedusingthepredefinedDECIMALtype,eachhasitsownfunctionandcharacteristicinthedatabase.Goingbacktothesamplecustomerandorderinformationfromthepreviouschapters,youcannowcreatethefollowinginvoicetablesthatincludethetwoUDTs:
CREATETABLEAmericaInvoice(InvoiceIDINTEGERPRIMARY
KEY,CustomerIDINTEGER,OrderIDINTEGER,TotalSaleAmtUSDollar,ShippingFeeUSDollar
);
CREATETABLEUnitedKingdomInvoice(InvoiceIDINTEGERPRIMARY
KEY,CustomerIDINTEGER,OrderIDINTEGER,TotalSaleAmtUSDollar,ShippingFeeUSDollar
);
InthischapteryouhavelearntthecharacteristicsofthevariousdatatypesavailableintheSQLlanguage.Youwerealsoabletounderstandtheneedtocreateuser-defineddatatypestomakeyourdatabaselesscomplicatedandmoreportable.InthenextchapteryouwilllearnhowtousethedifferentDataDefinitionLanguagestatementsincreatingdatabaseobjectsusingSQLiteStudio.
ChapterFive:DataDefinitionLanguageStatements
InthischapteryouwillgainadeeperunderstandingofthethreeDataDefinitionLanguagestatements–CREATE,ALTERandDROP.UsingSQLiteStudio,youwillalsolearnhowtoencodethecorrespondingSQLstatementsthathandlethedatabasestructure.
Again,adatabaseobjectisanydefinedlogicalunitthatstoresorreferencesdata.Whenyouhaveacollectionofdatabaseobjects,youcreateaschemathatisassociatedwithoneparticulardatabaseowner.Thefocusofthischapteristhebasicformofdatastorage,whichistherelationaldatabasetable.Asimpletablefurtherconsistsofrows,whichcorrespondstotherecordsofdata,andcolumns,whicharealsoknownasfieldsthatcontainanassignedparticulartypeofdata.Adatabasetablewillalwayshaveatleastonecolumnandarowthatiscomposedofoneormorefields.
CREATEStatementThenumerousformsoftheSQLCREATEstatementareresponsibleforconstructingvitaldatabasestructuresandobjects–tables,views,schemas,domainsandsoon.Theactofcreatingtablescouldbeeasy,butyouneedtotakeintoconsiderationnumerousfactors.Planningtablestructuresbeforeactualimplementationcouldsaveyoutimeandeffortsinceyoudonotneedtoreconfigureafterthetableshavebeencreated.
Herearesomeofthefactorstotakeintoconsiderationthroughwhencreatingtables:
TypeofdatathetablewillcontainTableandcolumnnamesPrimarykey(thecolumnthatmakeseachrowofdatauniquetoavoidduplicaterecordsinatable)ColumnlengthColumnscontainingnullvalues
Syntax:CREATETABLETABLE_NAME(field1DATA_TYPE[notnull],field2
DATA_TYPE[notnull],field3DATA_TYPE[notnull],field4DATA_TYPE[notnull],field5DATA_TYPE[notnull]);Thecolumnnames(field1,field2,field3,field4andfield5)andthefielddatatypesarewritteninsidetheparenthesis,separatedbycommas.Anythingindicatedinsidethebracketsareconsideredoptionalandthesyntaxstatementfinallyendswithasemicolon.
UsingtheCUSTOMERTABLEfromChapter2,youwillcreateanewdatabasetableusingSQLiteStudio.
CreateaNewDatabase
1. OpenSQLiteStudiobydouble-clickingtheapplicationicononyourdesktop.
2. ClicktheDATABASEmenuthenselectADDADATABASE.
3. TypeSample_DBinsidetheFILEinputbox(whichisthenameofthenewdatabase)thenclickOK.
4. YouwillnowhavetheSample_DBobjectinsidetheDatabase
Navigatorpane.
CreateaNewTable
1. ClicktheTOOLSmenuthenselectOPENSQLEDITOR.YouwillhavetheSQLeditorareaattherightpane.Ifyoudouble-clickSample_DB,youwillseeTABLESandVIEWSunderthedatabaseobject.Rightnow,therearenotablesnorviewspresentsoyouwillcreateoneusingtheSQLEditorpane.
2. UndertheQUERYTab,typethefollowinglinesofcode
CREATETABLECustomer_TBL(CustomerIDINTEGERNOTNULLPRIMARYKEY,
CustomerNameVARCHARNOTNULL,JobPositionVARCHAR,CompanyNameVARCHARNOTNULL,USStateVARCHARNOTNULL,ContactNoBIGINTEGERNOTNULL);
3. ClicktheEXECUTEQUERYbutton ontopoftheQUERYTaborpressF9onthekeyboard.YouwillnowhavetheCustomer_TBLtablewith6columns.
ALTERStatementTheSQLALTERstatementisusedtomodifydatabaseobjects,specificallytables.Alteringtableelementscanincludeaddinganddroppingcolumns,changingcolumndefinitions,addinganddroppingconstraints,modifyingtablestoragevaluesandmore.
Syntax:ALTERTABLETABLE_NAME[modify][columnCOLUMN_NAME]
[DATATYPE|nullnotnull][restrict|cascade][drop][constraintCONSTRAINT_NAME][add][column]COLUMNDEFINITION;AlteraTablebyAddingaNewColumn
1. AnewcolumnthatcontainsthecompanyaddressofthecustomerwillbeaddedtotheCustomer_TBLtable.TypethefollowinglinesofcodeundertheQUERYtab:ALTERTABLECustomer_TBLADD
CompanyAddVARCHAR;
2. AfterclickingtheEXECUTEQUERYbutton ,theCompanyAddcolumnisaddedaftertheContactNocolumn.Thisfieldcontainsvaluesofstringdatatype.
DROPStatementYouusetheSQLDROPstatementifyouwanttodelete
databaseobjects.Thus,theDROPTABLEstatementisusedtodeletetablesthatyoudonotneedanymore.Oncethislineisexecuted,allthedataandmetadatacontainedinthetablearealsoremoved.DROPTABLEisconsideredtobetheeasiestcommandtoexecute.However,anerrorwilloccurifthetabletobedeletedisbeingreferencedbyanothertableinthedatabase.ThatiswhyyouneedtobecautiouswhenperformingtheDROPstatementtoavoiddeletingobjectsbymistake(mostespeciallyiftherearemultipleuserswhoaccessthedatabase).
Syntax:DROPTABLETABLE_NAME[restrict|cascade]
TheRESTRICToptionisusedifanerroristobereturnedwhenatablereferencedbyanotherdatabaseobjectisdropped.Ontheotherhand,theCASCADEoptionallowsthetableandallotherreferencingobjectstobedeleted.TherearesomeSQLapplicationprogramsthatdonotpermittheCASCADEoptiontoguaranteethattherewillbenoinvaliddatabaseobjects.
DropanExistingTable
1. Sincethereisonlyonetableinthedatabase(Customer_TBL),youdonotneedtoworrywhethertousetheRESTRICTortheCASCADEoption.SimplyenterthefollowinglineofcodeinsidetheQUERYtab.
DROPTABLECustomer_TBL;
2. ClicktheEXECUTEQUERYbutton andinstantlytheCustomer_TBLtableisdeleted.
InthischapteryouhavelearnthowtoencodeprogramminglinesusingthecommonDDLcommandstatementsincreating,alteringanddroppingdatabasetablesinSQL.InthenextchapteryouwilllearnthedifferentDMLcommandsthatwillallowyoutomanipulateinformationcontainedindatabasetables.
ChapterSix:DataManipulationLanguageStatements
Inthischapteryouwilllearnhowtomanipulatedatabasetablesandmakethemusefulthroughdatainsertion,deletionandupdate.Toaccomplishthis,youwillbeprogramminginSQLiteStudiousingthreeDataManipulationLanguagestatements–INSERT,DELETEandDROP.
Normally,suchtablesareemptyaftertheyhavebeencreated.Thedatathatyoucanstoreinyourdatabaseobjectscanbeinvariousformats–non-digital,semi-digitalandfullydigital.Non-digitalformatmeansthatthedataneedstobeextractedfromanon-electronicsource,likecustomerinformationfrombusinesscards.Inthiscase,youarerequiredtostorethedatamanuallyintoyourdatabase.Asforthesemi-digital,thedatacouldalreadybeinsomesortofdigitalformbutnotthesameformatasyourdatabasetables.Forexample,youcouldhaverecordsofyourcustomers’businesscardsstoredinaMicrosoftExcelfilethatyoumayneedtotranslateintoanappropriateformatfitforyourdatabase.Lastly,fullydigitalmeansthatallofyourcustomerinformationisalreadyinelectronicformatthatalsomatchesthelayoutofyourdatabase.
Thecurrentdataformatwillfurtherdeterminehowyouwillbeabletomanipulateyourdatabase.ThisiswheretheDMLcommandsbecomeusefulinenteringnewdata,updatingexistingdataanddeletingdatafromtables.
INSERTStatement
Theprocessofenteringnewdatacouldbedoneeithermanuallythroughindividualcommandsorautomaticallyusingbatchprocessprograms.Therearealsofactorsthatwilldeterminewhatandhowmuchdatayoucaninsertinyourdatabasetables–fieldlength,columndatatype,tablesizeandmore.Inpopulatingtableswithdata,youwillusetheINSERTstatement.
OneRowataTime
Whenyouwanttoenterallthedataintoasinglerowofyourdatabasetable,youcancreateaform-baseddataentryapplication.Inthisfeature,ascreenisdesignedthatcontainsfieldswhereyoucaninputtheinformationbeingasked-foreverycolumninthetable.Usethefollowingsyntaxinaddingdataonerowatatime:
INSERTINTOTABLE_NAME[(column_1,column_2,…,
column_n)]VALUES(value_1,value_2,…,value_n);
Anythinginsidethesquarebracketsareconsideredoptional,meaningyoudon’tneedtolistthecolumnnames.Bytheway,“n”isthemaximumnumberoftablecolumns.Thedefaultorderofthecolumnlististhesameorderasyourcolumntables.Thus,ifyoulisttheitemsinsidetheVALUESsectioninthesameorderasyourtablecolumns,thenthevalueswillbeenteredinthecorrectcolumns.Youonlyneedtoindicatethecolumnnamesifyouneedtospecifythevaluesinadifferentorder.
Now,letusinsertrecordstoourCustomer_TBLtableusingthecustomerinformationprovidedintheChapter2.
1. TypethefollowingprogramminglinesintheSQLeditor:
INSERTINTOCustomer_TBL(CustomerID,CustomerName,
JobPosition,CompanyName,USState,ContactNo)
VALUES(1,‘KathyAle’,‘President’,‘TileIndustrial’,‘TX’,3461234567)
2. ClicktheEXECUTEQUERYbutton andyouwillgetthefollowingscreen(thereshouldbenoerrorsintheStatusArea):
3. Tocheckiftherecordofdatawasinsertedinthetable,double-clickCustomer_TBLattheleftpane.ClicktheDATAtabattherightpane,whichisinbetweenSTRUCTUREandCONSTRAINTStabs.Yourtableshouldbesimilartowhatisshowninthescreenbelow:
4. Clickthe optionatthebottomleftcornerofthescreen.Toaddanotherrecordwithoutspecifyingthecolumnnames,deletetheprogrammingcodesinsidetheQUERYtabandtypethefollowinglines:
INSERTINTOCustomer_TBLVALUES(2,‘KevinLord’,‘VP’,‘BestTooling’,‘NY’,5181234567)
5. ClicktheEXECUTEQUERYbutton andprovidedthattheorderofthevaluescorrespondsexactlytotheorderoftheCustomer_TBLtable’scolumns,thenthereshouldbenoerrorsintheStatusArea.
6. ClicktheCUSTOMER_TBL(SAMPLE_DB)option
atthebottomleftcornerofthescreen.UndertheGRIDVIEWtab,click
theREFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldseethenewrecordaddedtothetable.
MultipleRowsataTime
Multipleinsertsarebeneficialifyouneedtoenteranumberofrecordsintoyourtable.Thisprocessisalsomoreefficientratherthaninsertingonerecordatatime.AllyouneedtodoisrepeattheclausefollowingtheVALUESstatementandmakesureyouseparatethemwithacomma.
ToinsertthetworemainingrecordsintoourCustomer_TBL(seeChapter2forthedetails):
1. GoingbacktotheSQLEditor,enterthefollowinglinesofcodes(withoutspecifyingthecolumnnamesanymore):
INSERTINTOCustomer_TBLVALUES(3,‘KimAsh’,‘Director’,‘CarWorld’,‘CA’,5101234567),(4,‘AbbyKarr’,‘Manager’,‘WestMart’,‘NV’,7751234567)
2. ClicktheEXECUTEQUERYbutton .
3. Gotothe
option.Makesuretoclickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldnowseetwomorerecordsinsertedtothedatabasetable.
OnlySelectedColumnsataTime
InChapter5,theJobPositionfieldofCustomer_TBLtablewasdefinedtoallownullvalues.Ifincaseyouhaveanewcustomerbutyoudonotknowhispositionyetinthecompany,thenyoucanleavetheJobPositionfieldblankwhileprovidingthenecessaryinformationfortherestofthefields.
ToaddanewrecordwithoutprovidingdatafortheJobPositionfield:
1. EnterthefollowingSQLlines(makesureyouindicatethecolumnnames):
INSERTINTOCustomer_TBL(CustomerID,CustomerName,CompanyName,USState,ContactNo)VALUES(5,‘MikeArmhs’,‘1DrivingSchool’,‘NJ’,2011234567)
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.
3. Gotothe optionthenclicktheREFRESH
TABLEDATAbutton orpressF5onyourkeyboard.NoticethatsinceyoudidnotprovideanyinformationfortheJobPosition
field,itcontainsaNULLvalue.
UPDATEStatement
Sincechangeisinevitable,SQLprovidesawayforyoutoupdateexistingdatastoredinyourdatabase.Dependingonyourneeds,youcanmodifyasinglerecordormultiplerecordsatonetimeusingtheUPDATEcommand.However,onlyonetableisgenerallyupdatedatatimeinagivendatabase.ThestandardsyntaxforthisDMLstatementis:
UPDATETABLE_NAMESETcolumn_1=EXPRESSION_1,column_2=EXPRESSION_2,…
column_n=EXPRESSION_N[WHEREpredicates];
Again,anythinginsidethebracketsthatisindicatedintheWHEREclausestatementisoptionalandthemaximumnumberofcolumnsisrepresentedby“n”.Thesaidclauseidentifieswhichrowsneedtobeupdated-thismeansthatiftheWHEREclauseisnotpresentthenalltherecordsofthetableareautomaticallymodified.
OneRecordataTime
Fromthepreviousdiscussion,youaddedarecordofcustomerinformationwithoutprovidingdatafortheJobPositionfield.Ifincaseyouhavelearnedthatthecontactpersonisthevice-presidentofthecompany,thenyoucanmodifythisexistingrecord.
1. GobacktotheSQLEDITORbyclickingtheoption.Enterthefollowinglinesofcode:UPDATECustomer_TBL
SETJobPosition=‘VP’WHERECustomerName=‘MikeArmhs’;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.
3. Clickthe optionthenclickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youwillnowsee‘VP’undertheJobPositionfieldforthecustomernamedMikeArmhs.
MultipleRecordsataTime
Now,ifyouwanttomodifythe‘VP’valueoftheJobPositionfieldto‘Vice-President’soitwillbemorecomprehensibletodatabaseusers,thenyouhavetoupdatemultiplerecordsatonetime.
1. Clickthe optionatthebottomleftcornerofthescreenandthenchangetheprogramminglinesintothefollowing:
UPDATECustomer_TBL
SETJobPosition=‘Vice-President’WHEREJobPosition=‘VP’;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.
3. Clickthe optionthenclickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldnowseethattheprevious‘VP’valuehasbeenchangedto‘Vice-President’.
AllRecordsataTime
Ifyouwanttogivemoreemphasistothecustomernamebychangingittouppercaseletters,thenyoucanmodifyalltherecordsofthedatabasetableatonetime.Inthiscase,youwillnotbeneedingtheWHEREclauseanymore.
1. Clickthe optionatthebottomleftcornerofthescreenandthenenterthefollowingprogramminglines:
UPDATECustomer_TBL
SETCustomerName=UPPER(CustomerName)
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.
3. Clickthe optionthenclickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Noticethattheformatofthecustomernameforalltherecordsinthetablehavebeenchangedtocapitalletters.
DELETEStatement
TheDELETEstatementisaDMLcommandthatwillremoverecordsfromatablebutwillstillkeepitsexistenceinthedatabase.Thishappenswhenyoudon’tneedaparticularinformationinyourdatabase,eitherbecausetheyareobsoleteorhavenouseanymore.Thus,youcanfreeupsomestoragespace.YoucanexecutetheDELETEcommandtoremovejustonerecord,multiplerecordsorevenalltherecordsofthetableatonetime.Justareminder,thiscommanddoesnotdeletevaluesfromaspecificcolumn,butremovesanentireroworafullrecord.Thatiswhyyouhavetobeverycarefulwhenexecutingthiscommand.ThereisapossibilitythattheeffectoftheDELETEcommandispermanentandyoumaynotbeabletorecovertheeraseddata.ThestandardsyntaxforthisDMLstatementis:
DELETEFROMTABLE_NAME[WHERECONDITION];
EveniftheWHEREclauseisanoptionalpart,youarerequiredtoincludeitwhenyouwanttodeleteselectedrowsofdatafromacertaintable.WithouttheWHEREclause,youwillberemovingalltherecordsfromthetable.
TodemonstratethefunctionoftheDELETEstatement,youwillcreateacopyoftheCustomer_TBLtablefirst.Inthisway,youwillstillbeablekeeptheoriginaltabletobeusedforfurtherexercises.
1. GototheDATABASENAVIGATORthenright-clickonCustomer_TBL.ChooseCREATEASIMILARTABLE.
2. Youwillbeaskedtoprovideanameforyourtable.TypeCustomer_TBL2insidetheTABLENAMEinputbox.
3.Clickonthe
COMMITSTRUCTURECHANGESbutton undertheSTRUCTUREtab.Youwillgetthescreenbelow.
4. ClickontheOKbuttonandanewCustomer_TBL2tablewillbecreated.ThiswillbethetablethatyouwillworkaroundtodemonstratetheDELETEcommand.
AtthispointintimeCustomer_TBL2tableisempty,soyouhavetocopytherecordsfromCustomer_TBLtable.Todothis,followthestepsbelow:
1. Clickthe optionthenclickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Thiswillensurethatyourdatainthedatabasetableisupdated.
2. Clickontopofthefirstrow,justbeforetheCustomerIDcolumnheading.Thiswillhighlightalltherecordsinthetable.
3. Tocopythevalues,right-clickonthefirsthighlightedcell(justundertheCustomerIDcolumn)thenchooseCOPY.
4. Double-clickonCustomer_TBL2locatedintheleftpane.ClicktheDATAtabandmakesurethatyouareontheGRIDVIEWtab.Youwillseethesamecolumnsasintheoriginaltable,whichyouwillbepopulatingwiththedatayoucopiedfromtheCustomer_TBLtable.
5. ClickthedropdownarrowbesidetheINSERTROWbutton(justbelowtheGRIDVIEWtab).SelectINSERTMULTIPLEROWSoption.
6. InsidetheNUMBEROFROWSTOINSERTinputboxtype5.ClickOK.
7. Yourtablewillnowhave5rowsofdatathatcontainNULLvalues.ThisiswhereyouwillinsertthevaluesthatyoucopiedfromtheCustomer_TBLtable.
8. Right-clickonthefirstcellthenchoosethePASTEoption.
9. AllthedatavaluesfromtheCustomer_TBLtablewillbeinsertedtotheCustomer_TBL2table,whichyouwillmanipulatetodemonstratetheDELETEcommand.
10.ClickontheCOMMITSTRUCTURECHANGESbutton
tosavethedatainthetable.
SingleRecord
TodeleteonlyonerecordofdatafromtheCustomer_TBL2tablewherethecustomer’snamematchesto‘KATHYALE’:
1. Clickthe option,typethefollowinglinesofcodeintheQUERYtabandthenclicktheEXECUTEQUERYbutton
.
DELETEFROMCustomer_TBL2
WHERECustomerName=‘KATHYALE’;
2. Tocheckiftherecordhasbeendeleted,gototheCustomer_TBL2tablebyclickingon
.Thenclickonthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.Youwillnoticethattherecordhasbeendeletedalready.
MultipleRecords
Todelete2recordsofdatafromtheCustomer_TBL2tablewherethecustomer’spositionmatchesto‘Vice-President’:
1. Clickthe option,typethefollowinglinesof
codeandthenclicktheEXECUTEQUERYbutton .
DELETEFROMCustomer_TBL2
WHEREJobPosition=‘Vice-President’;
2. Tocheckiftherecordhasbeendeleted,gotothe
Customer_TBL2tablebyclickingon
.Thenclickonthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.Youwillnoticethatthetworecordshavebeendeletedalready.
WholeTable
TodeletealltheremainingrecordsfromtheCustomer_TBL2tableatonetime:
1. Clickthe option,typethefollowinglinesofcodeintheQUERYtabandthenclicktheEXECUTEQUERY
button .
DELETEFROMCustomer_TBL2
2. Tocheckiftherecordhasbeendeleted,gotothe
Customer_TBL2tablebyclickingon
.ThenclickontheREFRESH
TABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.YouwillnoticethatexecutingthesingleDELETEcommandhasdeletedalltherecordsfromthetable.
InthischapteryouhavelearnthowtoencodeprogramminglinesusingthemostcommonlyusedDMLcommandstatementsininserting,updatinganddeletingrecordsfromdatabasetablesinSQL.InthenextchapteryouwilllearnthedifferentDQLcommandsthatwillallowyoutoretrievevaluableinformationcontainedindatabasetables.
ChapterSeven:DataQueryLanguageStatements
InthischapteryouwilllearnhowtousetheavailableDataQueryLanguagestatementsinretrievingdatafromdatabasetables.ThroughSQLiteStudio,youwillbeabletouseSELECT,WHERE,ORDERBYandGROUPBYstatementsinrequestinganddisplayingsignificantdatabaseinformation.
Onceyouhavecreatedandpopulatedyourtableswithdatavalues,therewillcomeatimethatyouwillneedtoperformdatabasequeriestoretrieverelevantinformation.Aqueryisavalidinquiryintothedatabasetoextractanddisplaydatainareadableorunderstandableformat,dependingontheuser’srequest.ThemainchallengeinSQListocorrectlyinstructthecomputerwhattosearchforbymanipulatingthedatabasethroughrowselection.Onceyouhaveselectedthevaluesyouneedthenyoucanfurtherperformvariousoperationssuchasdataaddition,deletion,modificationandmore.
SELECTStatement
Retrievingdatavaluesisthemostperformedmanipulationtaskbydatabaseusers.IndoingsuchoperationyouneedtousetheDMLcommandstatementcalledSELECT.Youhavetheoptiontoretrievejustonerow,anumberofrowsoralltherowsofthedatabasetable.
UsingtheSELECTstatementinretrievingalltherecordsofaparticulartableisthebasicformofthisDMLcommandstatement.EveniftheSELECTcommandisconsideredtobethemostpowerfulstatement,itrequiresotherclausestofunctioncorrectlyinperformingaquery.Thesyntaxinitssimplestformis:SELECT*FROMTABLE_NAME;Intheprogramminglineabove,theasterisksign(*)signifieseverything.Thismeansthatthewildcardcharacterisashortcutforthelistingofallthecolumnnamesofaparticulartable.
ToselectallthedatarowsfromtheCustomer_TBLtable:
1. Clickthe optionandthentypethefollowinglinesofcode:
SELECT*FROMCustomer_TBL;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
TheresultbasicallyshowstheentiredataoftheCustomer_TBLtablesincethecodeinstructsthedatabasetoselectalltherowsandcolumnsofthesaidtable.
WHEREStatement
Whenyouwanttobemorespecificinselectingrowsofdatafromyourdatabasetablesthenyouneedtoaddabitofcomplexitytoyourprogramminglines.Atthispoint,youneedthefunctionoftheWHEREclause,whichmeansthattheSELECToperationwillbeperformedoncethestatedconditioninsidesuchclauseistrue.ThesyntaxoftheSELECTstatementwiththeWHEREclauseisasfollows:SELECTCOLUMN_LIST
FROMTABLE_NAMEWHERECONDITION;
ToselectonlytherowsofdatawherethejobpositionofthecustomerisVice-President:
1. Clickthe optionandthentypethefollowinglinesofcode:
SELECT*FROMCustomer_TBLWHEREJobPosition=‘Vice-President’;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
TheresultshowstherecordsofthetwocustomersnamedKevinLordandMikeArmhswhoarebothVice-Presidentsoftheirrespectivecompanies.
Whatifyouonlywanttoselectcertaincolumnsofthetable,maybejustthefullnameandcompanyofthecustomer?Youwillnowmodifyyourlinesofcodeintothefollowing:
1. IntheQUERYtab,changethewildcardcharacter*(asterisksign)intoCustomerNameandCompanyNamebytypingthefollowing:
SELECTCustomerName,CompanyNameFROMCustomer_TBLWHEREJobPosition=‘Vice-President’;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
Byspecifyingthecolumnsyouwanttoselect,youaretryingtocustomizewhatdatayouwanttoretrieveandhowyouwantthemtobedisplayed.Inthepreviousexample,youonlywantedtoknowthecustomer’snameandhiscompanywherethejobpositionisvice-president.
ORDERBYandGROUPBYStatements
Whenyouwantthedatayouretrievetobedisplayedandsortedinsomeway,thenyouneedtoincludetheORDERBYorGROUPBYoperatorattheendofyourSQLstatement.TheprimaryfunctionoftheORDERBYstatementisbasicallytoarrangedatausingaspecificorder,whetherascendingordescending.Ontheotherhand,theGROUPBYstatementisusedtoputidenticaldatatogetherandarrangethequeryoutputintogroups.
ThestandardsyntaxfortheORDERBYclauseis:SELECTCOLUMN_LIST
FROMTABLE_NAMEORDERBYCOLUMN_LIST[ASC|DESC];Bydefault,ORDER
BYsortsindividualrowsinascendingorder.IfyouwanttoarrangeyourrecordsindescendingorderthenyouhavetoindicatetheDESCoperatorattheendoftheORDERBYclause.
ToretrieveallcustomerrecordsfromtheCustomer_TBLtableanddisplaytheminascendingorderbyUSstate:
1. Clickthe optionandthentypethefollowinglinesofcode:
SELECT*FROMCustomer_TBLORDERBYUSState;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
Sinceyoudidnotspecifyhowtherecordswillbesorted,thedatarowswerearrangedalphabetically(inanascendingorder)usingtheUSStatecolumn.Ifyouwanttosortyourrecordsindescendingorder:
1. InsidetheQUERYtab,addDESCafterUSStateintheORDERBYclause.
SELECT*FROMCustomer_TBLORDERBYUSStateDESC;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
Ifyouwanttodeterminesomethingaboutagroupofrecordsorneedtocombinecolumnswithduplicatevaluesinalogicalway,thenitistimetousetheGROUPBYclause.Othertermssimilartogroupingareaggregating,summarizingandrollingup.Toillustratethis,ifyouwanttoknowhowmanycustomersarethereforeveryjobpositionintheCustomer_TBLtablethenweneedtocountthenumberofrecordsanddisplaythetotalnumberofcustomersperjobposition.
1. Clickthe optionandthentypethefollowinglinesofcode:
SELECTJobPosition,COUNT(*)ASnumber_of_recordFROMCustomer_TBL
GROUPBYJobPosition;
2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.
Intheexampleabove,theCOUNTfunctionwasintroducedtoarrangethedataingroups.ThefollowingisasummaryofthecommonaggregatefunctionsusedtogetherwiththeGROUPBYstatement(xdenotesthecolumnnamewhereyouwanttoperformthefunction):
AVG(x)–computestheaverageofallthecolumnvalues(nullvaluesremoved)COUNT(x)–countsthenumberofnon-nullvaluesinthecolumn
COUNT(*)–countsthenumberofrecords
MAX(x)–computesthemaximumvalueinthecolumn(nullvaluesremoved)
MIN(x)-computestheminimumvalueinthecolumn(nullvaluesremoved)
SUM(x)–computesthesumortotalofthevaluesinthecolumn(nullvaluesignored)
GoingbacktotheGROUPBYexample,thedataintheJobPositioncolumnisretrievedandforeachinstanceofthevalue,arecordiscountedusingtheCOUNTfunction.Thenumber_ofrecordisanewcolumncreatedthatdisplaysthetotalnumberofrecordsperjobposition.TheDirector,ManagerandPresidentpositionshave1recordeachwhiletheVice-Presidenthas2.Thisisbecausetherearetwocustomerswhoarevice-presidents–KevinLordandMikeArmhs.Ifyoucanalsonotice,therecordsdisplayedaresortedinanascendingorderbydefault.
AlteringyourSQLstatementstodisplaythejobpositioninadescendingorderwillrequireyoutoaddtheORDERBYstatementaftertheGROUPBYclause(ORDERBYwillalwayscomeaftertheGROUPBYstatement).ChangeyourlinesofcodeintothefollowingandthenclicktheEXECUTEQUERY
button ontopoftheQUERYtab:SELECTJobPosition,COUNT(*)ASnumber_of_recordFROMCustomer_TBL
GROUPBYJobPositionORDERBYJobPositionDESC;
InthischapteryouhavelearnthowtoencodeprogramminglinesusingthemostcommonlyusedDQLcommandstatementsinselecting,orderingandgroupingrecordsfromdatabasetablesinSQL.Inthenextchapteryouwilllearnthedifferenttransactionalcontrolcommandsthatwillallowyoutomanageseveralrelationaldatabasetransactions.
ChapterEight:TransactionalControlCommands
Inthischapteryouwilllearnhowtousethreeoftheavailabletransactionalcontrolcommandsinarelationaldatabasemanagementsystem(RDBMS)usingSQLiteStudio–COMMIT,ROLLBACKandSAVEPOINT.Controllingtransactionsrequiresyoutobeabletomanagecertaindatabasechangesthatareusuallybroughtaboutbytheinsert,updateanddeletecommands.
Executingadatabasetransactionseemstohavebeensuccessfullycompletedwhenyounoticethatthetable’sdataorstructurehasbeenchanged.Whatisactuallyhappeningduringatransactionexecutionisthatinformationisstoredinatemporaryspaceinthedatabase(orwhatyoucancallarollbackarea).Whenyouwanttofinalizethesetransactionsandstoretheinformationpermanently,thenyoueithersaveordiscardthechangesmadetothedatabasetablesbyissuingtheappropriatetransactionalcontrolcommand.Onlythenthattherollbackareaisemptied.
COMMITCommand
UsingtheCOMMITcommandsavesallthetransactionsintoyourdatabase.Normally,inSQLiteStudio,wheneveryouexecuteaCREATE,INSERTorDELETEtransactionbywritingprogramminglinesintheSQLEditor,thechangesareautomaticallysaved.YouhavefirstencounteredtheCOMMITcommandthroughtheCOMMITCHANGESSTRUCTUREbuttoninChapter6,whereyoucreatedacopyoftheCustomer_TBLtable.Now,todemonstratethiscommandagaininSQLiteStudio,youwillmanipulatethetablestructurebyaddinganewrecordtotheCustomer_TBLtableinGRIDVIEWmode.
1. Clickthe option.Toensurethatthereareno
transactionscurrentlyrunninginthedatabase,typethefollowingprogramminglineintheQUERYtabthenclicktheEXECUTEQUERY
button :
ENDTRANSACTION;
2. Double-clickCustomer_TBLundertheTABLESlistintheDATABASENAVIGATORpane.ClicktheDATAtabattherightandmakesurethattheGRIDViewisdisplayed.YouwillseealltherecordsoftheCustomer_TBLtable.
3. Clickthefirstcolumnofthelastrowofthetable,whichisCustomerID5.
4. Clickthedrop-downarrowbesidetheINSERTROW(INS)buttonandselectPLACENEWROWSBELOWSELECTEDROWoption.
5. ThistimeclicktheINSERTROW(INS)buttonandyouwillseeanewemptyrowaddedtothetable.
6. Addthefollowingdatavaluesinthenewrecord:
CustomerID:6CustomerName:JOHNDEPPJobPosition:PresidentCompanyName:RockersMineCompanyUSState:TXContactNo:3467654321
7. ClicktheCOMMITbutton topermanentlysavethenewdatavaluesaddedtothetable.
ROLLBACKCommand
IftheCOMMITcommandsavesallthechangestothedatabase,theROLLBACKcommandisthereversewherealltheunsavedchangeswillbediscarded.However,youcanonlyundotransactionssincethelastCOMMITorROLLBACKstatementexecuted.Thestandardsyntaxforthistransactionalcontrolcommandis:
ROLLBACK[WORK];
Also,beforeyoucanperformaROLLBACKcommand,makesurethattransactionshavestarted.Thismeansthatyouneedtoexecutethefollowingprogrammingstatementattheverybeginning:
BEGINTRANSACTION;
TodemonstratehowaROLLBACKstatementworks,youwillmodifytheDROPTABLEcommandinSQLiteStudio:
1. Clickthe option.IntheQUERYtab,typethefollowing
programmingstatementandclicktheEXECUTEQUERYbutton :
BEGINTRANSACTION;
2. Clickthe optionandcleartheQUERYtab.Typethe
followingandthenclicktheEXECUTEQUERYbutton .YouwillnoticethattheCustomer_TBLtableisnowremovedfromtheTableslist.
DROPTABLECustomer_TBL;
3. Clickthe optionagainandcleartheQUERYtab.Type
thefollowingandthenclicktheEXECUTEQUERYbutton :
ROLLBACK;
4. TocheckiftheROLLBACKcommandreversedthedeletionoftheCustomer_TBLtable,right-clickanywhereinsidetheDATABASENAVIGATORpane.ChooseREFRESHALLDATABASESCHEMASoption.
5. ClicktheTABLElistattheleftpane.YoushouldnowseethattheCustomer_TBLtableisbackundertheTABLElist.
SAVEPOINTCommand
Whenyouwanttoreversethetransactionjustbacktoacertainpointand
nottheentiretransaction,thenyouhavetoexecutetheSAVEPOINTcommandbeforeperformingaROLLBACKaction.ThisishowyoumanageseveraltransactionsintosmallergroupsofSQLcommands.Thestandardsyntaxforthistransactionalcontrolcommandis:
SAVEPOINTSAVEPOINT_NAME;
WhenusingtheSAVEPOINTandtheROLLBACKcommandstogether,thesyntaxis:
ROLLBACKTOSAVEPOINT_NAME;
Asavepointnamecanbethesameasthedatabaseobject’snametowhichyouwillbeperformingtheSQLtransactions.However,youshouldremembertomakethemunique,differentfromthegroupoftransactionsthatyouwanttobreakdownintoseveralpointsorsegments.
TodemonstratehowaSAVEPOINTwithaROLLBACKcommandworks,youwilldeletecertainrecordsfromtheCustomer_TBLtableandreversethistransaction.
1.Clickthe option.IntheQUERYtab,typethefollowingprogrammingstatementandclicktheEXECUTEQUERY
button :
BEGINTRANSACTION;
2.Clickthe optionagainandcleartheQUERYtab.Thentypethefollowing:
SAVEPOINTCustomer_SP1;
ClicktheEXECUTEQUERYbutton .AsavepointsectioniscreatedbeforedeletingthelastrecordoftheCustomer_TBLtable.
3.TodeletethelastrecordoftheCustomer_TBLtable,clickthe
optionandcleartheQUERYtab.Typethefollowingand
thenclicktheEXECUTEQUERYbutton :
DELETEFROMCustomer_TBLWHERECustomerID=6;
4.Tocheckiftherecordwasdeleted,double-clickCustomer_TBLundertheTABLESlistintheDATABASENAVIGATORpanethenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clickthe
REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Yourtableshouldbethesameasthefollowing:
5.Tocreatethesecondsavepointsection,clickthe optionagain.CleartheQUERYtabandthentypethefollowing:
SAVEPOINTCustomer_SP2;
ClicktheEXECUTEQUERYbutton .ThistimeasavepointsectioniscreatedbeforedeletingtherecordwheretheCustomerIDisequalto5.
6.TodeletetherecordwheretheCustomerIDisequalto5,clickthe
optionagainandcleartheQUERYtab.Typethefollowing
andclicktheEXECUTEQUERYbutton :
DELETEFROMCustomer_TBLWHERECustomerID=5;
7.Tocheckiftherecordwasdeleted,clickthe
optionatthebottomleftcornerofthescreenthenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clicktheREFRESHTABLE
DATAbutton orpressF5.Yourtableshouldbethesameasthefollowing:
8.Toreversethelasttransactiondone,clickthe optionagainandcleartheQUERYtab.Typethefollowingandthenclickthe
EXECUTEQUERYbutton :
ROLLBACKTOCustomer_SP2;
9.Tocheckiftherecorddeletionwasreversed,clickthe
optionandthenclicktheDATAtabattheright.Under
theGRIDVIEWtab,clicktheREFRESHTABLEDATAbutton orpressF5.Yourtableshouldbethesameastheonebelow:
10.Toundothefirstrecorddeleted,clicktheoptionagainandcleartheQUERYtab.Typethefollowingandthenclick
theEXECUTEQUERYbutton :
ROLLBACKTOCustomer_SP1;
1.Tocheckiftherecorddeletionwasreversed,clickthe
optionandthenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clicktheREFRESHTABLEDATAbutton
orpressF5.Yourtableshouldbethesameastheonebelow:
InthischapteryouhavelearnttheprimaryfunctionsofthethreetransactionalcontrolcommandsinsavingordiscardingchangesinanSQLdatabase.InthenextchapteryouwilllearntheimportanceofviewsandhowtomanipulatethemusingCREATE,UPDATEandDROPcommands.
ChapterNine:DatabaseViews
InthischapteryouwilllearnwhatadatabaseviewisanditsimportanceinSQLprogramming.Inaddition,youwillbeabletoperformtheexistingSQLcommandsincreating,updatinganddroppingviews.
DefiningViewsAviewisadatabaseobjectformedwhenyourSELECTqueriesaresavedinthedatabaseforfutureuse.Thismeansthataviewexistsbecauseofthetableswhereitsdatavalueswerederivedfrom.Thus,oneormoretablescancreateadatabaseview.Also,ithasthesamecharacteristicssimilartotheactualtableexceptthatyoudon’tneedsomephysicalspacetostoreit(temporarilysavedinthecomputer’smemory).Moreover,beingavirtualtable,youcannotmodifyitsdatavalues.
WhenexecutingaSELECTstatementtocreatetheview,youcaneithergetthecolumnnamesfromaparticulartableorperformcertainfunctionsandcalculationsthatwillmanipulatethegivendatavalues.Oncecreated,theseviewscanperformanyofthefollowingtasks:
Simplifydataretrieval-Someendusersmaynothavetheknowledgetoperformdatabaseoperationstogetthequeryresulttheyneed.Sotomakethingseasier,youcancreatedifferentviewsfromthetablesthatusersrequire.
Implementdatabasesecurity–Therearetimesthatyouhavetorestrictcertainusersonwhattheycanaccessfromyourdatabase,whethertheyareallowedtomodifydataorjustviewinformation.Toensurethatthetablesaresecured,youcangenerateviewsthatonlydisplaythedatavaluesthatyouallowuserstoaccess.
Supportdatasummarizationandreportgeneration–Throughviews,youareabletoturnacomplicatedSELECTqueryintoasimplesummarized
datathatyoucangeneratefrommultipletables.Thissummaryorreportcouldbegeneratedandupdatedfromtimetotime.Thatiswhyinsteadofcomposingcomplexprogramminglinesyoucanjustuseaggregatefunctionsincorporatedinthecreationofviews.
CreatingViewsTheSQLstatementCREATEVIEWisusedingeneratingviewsfromoneormoretables,andevenfromanotherview.Thefollowingisthemostbasicsyntaxusedincreatingaviewfromasingletable:CREATEVIEWVIEW_NAMEAS
SELECTCOLUMN_LISTFROMTABLE_NAME;
CreatingaViewfromtheEntireContentofaSingleTable
Forthisexercise,youwillbeusingtheCustomer_TBLtableoftheSample_DBdatabasetocreateaCustomer_VWviewinSQLiteStudio.
1. Clickthe optionanddeleteeverythinginsidetheQUERYtab.Thentypethefollowinglinesofcode:
CREATEVIEWCustomer_VWASSELECT*FROMCustomer_TBL;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnownoticethatthereisaCustomer_VWviewundertheVIEWSsection,insidetheDATABASENAVIGATORpane.
3. Tocheckthecontentoftheview,double-clickCustomer_VWintheleftpanethentheDATAtabinSQLWORKAREA.TheCustomer_VWviewshouldcontainalltherecordsoftheCustomer_TBLtable.
CreatingaViewfromSelectedColumnsofaSingleTable
Ifyouwanttocreateaviewthatcontainsonlythecontactdetailsofthecustomer(CustomerName,CompanyNameandContactNo),thenyouwillselectcertaincolumnsfromtheCustomer_TBLtable.
1. Clickthe optionanddeleteeverythinginsidetheQUERYtab.Thentypethefollowinglinesofcode:
CREATEVIEWCustContactDeatails_VWASSELECTCustomerName,CompanyName,ContactNoFROM
Customer_TBL;Youneedtoprovideadifferentnameforthisnewview.SQLiteStudiowillnotallowyoutocreateanewviewwiththesamenameasanexistingview.
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnownoticethatthereisaCustContactDetails_VWviewundertheVIEWSsection,justontopoftheCustomer_VWview.TheVIEWSlistisalphabeticallyarrangedinascendingorder.
3. Tocheckthecontentofthisnewlycreatedview,double-click
CustContactDetails_VWintheleftpanethenclicktheDATAtabagain.Thisviewshouldcontainonlythreecolumns,namelyCustomerName,CompanyNameandContactNo,fromtheCustomer_TBLtable.
CreatingaViewfromMultipleTables
Whenyourequiremultipledatabasetablestocreatetheviewyouneed,ensurethatthetablesinvolvedwillhavetobejoinedbycolumnsthatarecommontothem.Forexample,youmayhaveanothertablethatcontainsinformationonthecustomers’orderssuchasthedatewhentheyordered,whatproducttheyordered,thequantityandmore.ThisnewtablewillbecalledtheORDERTABLEanditisrelatedtothefirstCUSTOMERTABLEbecauseeveryorderisassociatedtoaparticularcustomer.
Now,youwillcreateaviewfromtwotablesthatwillshowdatabaseuserstowhichcompanyandstateeachorderwasshippedtoordelivered.Thebasicsyntaxforcreatingaviewusingmultipletablesis:CREATEVIEWVIEW_NAMEAS
SELECTCOLUMN_LISTFROMTABLE_LISTWHERECONDITION;TocreatetheORDERTABLE:
1. UsingthedatavaluesinChapter2fortheORDERtable,create
anothertableusingtheSQLEditor.ClicktheoptionanddeleteeverythinginsidetheQUERYtab.TypethefollowinglinesofcodeforthenewORDERtable:
CREATETABLEOrder_TBL
(OrderIDINTEGERNOTNULLPRIMARYKEY,OrderDateDATENOTNULL,CustomerIDINTEGERNOTNULL,ProductIDINTEGERNOTNULL,OrderQtyBIGINTEGERNOTNULL);
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnowhavetheOrder_TBLtableundertheTABLES
listintheleftpane.
3. Double-clicktheOrder_TBLintheleftpanethenclickonDATAtabattheleft.YouwillpopulatethistablewithdatavaluesinGRIDVIEWmode.
4. ClicktheINSERTROWbutton andthenselectthefirstoption–INSERTMULTIPLEROWS.
5. Enter“4”intheNUMBEROFROWSTOINSERTinputbox(sincethereare4recordsintheORDERTABLEfromChapter2)thenclickOK.
6. TheOrder_TBLtablewillnowhave4rowsand5columns.InsteadofusingSQLstatementstopopulatethistable,youwillenterthevaluesdirectlyintothetable(checkthedatavaluesinChapter2).
+
7. ClicktheCOMMITbutton tosaveallthedatavaluesoftheOrder_TBLtable.
Tocreatetheviewthatwilltellyoutowhichcompanyandstateeveryorderwasshippedtoordelivered:
1. Clickthe option,emptyQUERYtabandthentypethefollowinglinesofcode:
CREATEVIEWOrderDelivery_VWASSELECTOrder_TBL.OrderID,Customer_TBL.CompanyNameASCompanyDeliveredTo,Customer_TBL.USStateASStateDestination,Order_TBL.OrderQtyFROMCustomer_TBL,Order_TBLWHEREOrder_TBL.CustomerID=
Customer_TBL.CustomerID;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnowhaveanewviewnamedOrderDelivery_VW.
3. Tocheckthecontentofthisview,double-clickOrderDelivery_VWintheleftpanethenclicktheDATAtabattheright.
Inthisview,twocolumnswereselectedandrenamedfromtheCustomer_TBLtable-CompanyNamechangedtoCompanyDeliveredToandUSStatechangedtoStateDestination.TheothertwowerefromOrder_TBLtable—OrderIDandOrderQty(theoriginalcolumnnameswereretained).TherowsretrievedfrombothtablesarethoserecordswheretheCustomerIDoftheCustomer_TBLtablematchestheCustomerIDoftheOrder_TBLtable.
DroppingViewsTheDROPVIEWcommandisthestatementusedtodestroyanexistingviewfromthedatabase.Thebasicsyntaxis:DROPVIEWVIEW_NAME;TodropordeletetheentireCustomer_VWview:
1. Clickthe option,emptyQUERYtabandthentypethefollowinglinesofcode:
DROPVIEWCustomer_VW;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnoticethattheCustomer_VWviewisalreadydeletedfromtheViewslist.
InthischapteryouhavelearntthedefinitionandimportanceofdatabaseviewsinSQL.Youhavealsoperformedcommonoperationsinmanipulatingviews,suchascreatinganddroppingthem.Inthenextchapteryouwilllearnmorein-depthconceptsindesigningdatabasesinSQL–primaryandforeignkeys,indexesandnormalizeddatabases.
ChapterTen:EnhancingDatabaseDesigns
Inthischapteryouwillgainmorein-depthknowledgeonenhancingdatabasedesignswiththeuseofprimaryandforeignkeys,indexesandnormalizationtechniques.Havingabetterunderstandingofdesigningdatabaseswillprovidethesoftwareapplicationyouareusinganedgebyperformingqueriesmoreeffectivelyandmaintainingdataintegrityatalltimes.
AssigningPrimaryandForeignKeysItisoneofthebestpracticestoassignaprimarykeywhenyoudefineadatabasetable.Inarelationaldatabase,theprimarykeyisaspecialfieldorcombinationoffieldsthatmakeeachrecordinthetableunique.Sincethepresenceoftheprimarykeydoesnotpermittheduplicationofvaluesonthecolumntowhichitwasassigned,thendataintegrityisguaranteed.Also,fieldsthataredesignatedasprimarykeyscannotcontainnullvalues.Definingaprimarykey,whetheritisexplicitorimplied,occursduringtablecreation.Normally,thetableswithprimarykeysareregardedasparenttables,meaningthesetablesprovideinformationtoanothertableorwhatistermedasthechildtable.Consequently,childtablesaredependentontheparenttable.
Inthepreviouschapters,youhavebeendealingwiththeCUSTOMERtableandtheORDERTable.WhatifyouhaveanothertablecalledthePRODUCTTablethatcontainsthefollowingfieldsorcolumns:ProductID,ProductNameandPriceperUnit?Youwillhavethefollowingrelationshipfrom
thesethreetables:
Fromthefigureabove,theCUSTOMER_TBLandthePRODUCT_TBLaretheparenttablesofthechildtableORDER_TBL(thisdescribesaparent-childrelationshipindatabasedesign).Asyoucansee,thefieldsnamedCustomerIDandProductIDaretheprimarykeysoftheparenttables.Thesetwofieldsarealsopresentinthechildtable.TheynowbecomeforeignkeysoftheORDER_TBLtable.Inotherwords,aforeignkeyisacolumnorfieldpresentinthechildtablethatreferencestotheprimarykeyofitsparenttable.
Unliketheprimarykey,aforeignkeydoesnotneedtobeuniqueallthetime.Inaddition,thenameoftheforeignkeycouldbedifferentfromthenameoftheprimarykeythatitreferencesto.Furthermore,theProductIDoftheparenttable(PRODUCT_TBL)canneverhaveduplicateentries,butnotthecorrespondingProductIDinthechildtable(ORDER_TBL).However,youshouldnotdefineandcreateaforeignkeyvalueifthereisnomatchingprimarykeyvalue.
UnderstandingIndexes
Whenadatabasestartstoslowdown,specificallyitsSQLqueries,youcan
createandimplementindexestoimproveitsperformance.Suchindexesareimportantobjectsthatserveaspointersassociatedtothedataofaparticulartable.Theprimaryfunctionofanindexistodeterminetheexactphysicallocationofthedatawhenaqueryisexecutedtoimproveitsretrievalprocess.Itworkslikeabook’salphabeticallyarrangedindexthathelpsyoufindtheinformationyouneedinamucheasierwayusingitspagenumbers.Thus,timeissaved,sinceyoudonotneedtoscanonerowatatime(mostespeciallyinextremelylargedatabases)andjustgodirectlytotherequiredrecord.
Thestoragespacesofanindexandthetablefromwhichitwascreatedareseparate.Suchallocatedphysicalspacecanalsoincreasetremendously,evenlargerthanthetableitreferences.Thatiswhystoragerequirementsaretakenintoconsiderationwhendesigningdatabases.Justliketablesandviews,indexescanalsobecreatedordropped.Whendesignedcorrectly,theyactuallyspeedupSELECTqueriesbutcouldslowdownDELETE,UPDATEandINSERTstatements.Forenormousdatabases,dataretrievalwilldefinitelyconsumesomuchtime.However,suchindextransactionshavenoeffectonthetable’sdata.
CreatingIndexes
Anindexisassociatedtoaparticularcolumnwhenitiscreated.Itthenholdsthelocationofthedatavaluesofthetablethatcontainsthatparticularindexedcolumn.Whenevernewdataisaddedtothetable,itwillalsobeaddedtotheindex.Let’ssayyouexecuteaSELECTstatementwithacertainconditionspecifiedintheWHEREclausethatchecksthecolumnthatisindexed.Thefirstthingthatwillhappenisthattheindexisfirstsearchedandwillonlyreturntheexactlocationifthedatavalueisfound.
Forexample,youwantedtoselectalltherecordsfromtheORDERtablewheretheCustomerIDmatchesto1.Youwillthenissuethefollowingquery:SELECT*
FROMOrder_TBLWHERECustomerID=1;IftheORDER_TBLtableisindexedon
theCustomerIDcolumn,thentherecordswillbearrangedinanascendingorderbasedonthatcolumn.Thus,theCustomerIDindexmakesiteasierforthesearchprocesstotakeplaceandfinallyresolvesthelocationofallthedatawiththematchingCustomerID.Oncethelocationisdetermined,thecorrespondingrowsofdatawillberetrievedfromtheORDER_TBLtable.Withouttheexistenceoftheindex,afullscanwillbeperformed,whichwillnotbeefficientifthetablecontainshundredsoreventhousandsofrecords.
Thebasicsyntaxisforcreatinganindexis:CREATEINDEXINDEX_NAMEONTABLE_NAME[(COLUMN_NAME)];Thisstatementcanvarybyaddingspecificationssuchasthecolumnnametobeindexed,ordering(whetherascendingordescending)andmanymore.Now,tocreatetheColumnIDindexoftheORDER_TBLtableinSQLiteStudio:
1. Clickthe optionandmakesuretheQUERYtabisempty.Thentypethefollowing:
CREATEINDEXCustomerID_IDXONOrder_TBL
(CustomerID);
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnowhaveCustomerID_IDXundertheINDEXESlistintheOrder_TBLtable.
DroppingIndexes
Justlikedroppingatableoraview,youwillusethefollowingbasicsyntax:DROPINDEXINDEX_NAME;Rememberthatyoucanre-
createtheindexafterithasbeendeleted,butmakesureyoutakeextraprecautionwhenperformingsuchtransactions.Also,whenyoudeleteatable,youwillalsobedeletingallthecorrespondingindexeswithit.Sometimesyoumayonlyneedtodeletetheindexandretainthetable.Suchimplementationhappenswhenyouonlywanttofixanindexproblemtooptimizethedatabaseperformanceandreducefragmentation.
Todroptheindexthatwehavecreatedpreviously:
1. Clickthe optionandmakesuretheQUERYtabisempty.Thentypethefollowing:
DROPINDEXCustomerID_IDX;
2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnownoticethattheCustomerID_IDXindexhasbeendeletedfromtheIndexeslist.
NormalizingDatabases
Whydoyouneedtonormalizeadatabase?Thisisbecauseindesigningadatabaseyouneedtoensurethatinformationiswellorganized,easilymanaged,alwaysaccurateandthereisnounnecessaryduplication.Basically,normalizationistheprocessofdesigningandredesigningadatabasebyreducingonebigtableintotwosmallertables,wherethesametypeofdataaregroupedtogether.Forexample,ifyouonlyhaveonetablebymergingthecustomerinformationoftheCUSTOMER_TBLtablewiththeORDER_TBLtable,thenyouwillgetatablethatisnotnormalized:ORDER
IDORDERDATE
CUSTOMERID
NAME POSITION COMPANY STATE CONTACTNO
PRODUCTID
1 2016-05-23
1 KathyAle
President TileIndustrial
TX 3461234567 4
2 2016-09-09
1 KathyAle
President TileIndustrial
TX 3461234567 5
3 2016-02-17
3 KimAsh
`Director CarWorld CA 5101234567 2
4 2016-05-12
2 KevinLord
VP BestTooling
NY 5181234567 2
Asyoucansee,thereisaredundancyofdataonthepartofstoringthecustomerinformation.Thatiswhyitiswaybettertodividethistableintotwo
smalleronesthroughthenormalizationprocess.Alwaysbearinmindtokeepdataredundancytoaminimum,ifpossible,tosavestoragespaceandavoidinformationconfusion.Ifyouhavecustomerinformationforeverytableandonetabledoesnotmatchsuchinformationwithanother,thenhowwillyoubeabletoverifywhichoneiscorrect?Ifyouhavetoupdateacustomeraddress,thenyouarerequiredtoupdatethedatainallofthetableswhereitisincluded.Thus,timeandeffortinmanagingthedatabaseiswasted.
Thewayofmeasuringthedepthorleveltowhichadatabasehasbeennormalizediscalledanormalform.Therearethreecommonnormalforms,whereeachformisdependentonthepreviousnormalizationstepsperformedonthedatabase.
FirstNormalForm(1NF)
Givenasetofbasedata,thefirstnormalform(1NF)aimstodividethisintologicalunitsortablesofrelatedinformationwithanassignedprimarykey.Everycellcontainedinanyofthe2-dimensionaltablesshouldonlyhaveasinglevalue.Eachrowofaparticulartablereferstoacertainrecordofinformationandmustalwaysbeunique.Asforthecolumn,itisgivenauniquenameandconsistsofdatavaluesofthesametype,whichpertainstoasingleattributeoftheinformationcontainedinthetable.Moreover,thereisnoparticularorderthatthecolumnsnortherowsshouldbearranged.
ModifyingthegivendatabaseinChapter2byaddingemployeeinformation,youwillhavethefollowingbasedataforthecompany:
Basedfromthefigureabove,theentirecompanydatabasewasdividedintotwosmallertables–EMPLOYEE_TBLandCUSTOMER_TBL.TheprimarykeyforthesetablesareEmployeeIDandCustomerIDrespectively.Inthisway,itiseasiertoreadandmanagetheinformationascomparedtoonebigtablewithsomanycolumnsandrows.Thedatavaluesstoredineachtablerefertotwoseparateentities,meaningthosepiecesofinformationdescribingthecompany’semployeesareonlypresentintheEMPLOYEE_TBLtablewhilethosethatonlypertaintothecustomersarestoredintheCUSTOMER_TBLtable.
SecondNormalForm(2NF)
Afteryouaredonewiththefirstnormalform,thenextstepisderivingthesecondnormalform(2NF).Thisprocessfocusesonfunctionaldependencythatdescribestherelationshipsbetweenattributes.Whenanattributedeterminesthevalueofanother,thenthereisfunctionaldependencybetweenthem.Inthiscase,youwillstoredatavaluesfromtheEmployeeandCustomertablesthatarepartlydependentontheirprimarykeysintoseparatetables.
ThefigureaboveshowsthatthoseattributesthatarepartlydependentontheEmployeeIDprimarykeyhavebeenremovedfromEMPLOYEE_TBLandstoredinanewtablecalledEMPLOYEE_SALARY_TBL.Theattributesthatwereretainedintheoriginaltablearefullydependentontheprimarykey–meaningthatforeveryrecordoflastname,firstname,addressandcontractnumberthereisacorrespondingparticularemployeeID.UnliketheEMPLOYEE_SALARY_TBL,aparticularemployeeIDdoesnotreferenceauniqueemployeepositionnorsalaryrate.Therecouldbemorethanoneemployeewiththesameposition(EmpPosition),payrate(Payrate)andbonus(Bonus).
FortheCUSTOMER_TBLtable,customer’sorderinformationdoesnotdirectlydependonthegeneralcustomerinformationfoundintheoriginaltable.Thatiswhyfourattributes(OrderID,OrderDate,ProductIDandOrderQty)weremovedtoaseparatetablecalledORDER_TBL.
ThirdNormalForm(3NF)
Withthethirdnormalform(3NF),youwillhavetoseparatepiecesofinformationfromthetablethatarecompletelynotdependentontheprimarykey.GoingbacktotheCUSTOMER_TBL,thejobposition(JobPosition)anditsdescription(JobDescription)aretotallyindependentoftheCustomerIDprimarykey.Thisisbecause,ingeneral,anyjobpositionwillhavethesamedutiesandresponsibilitiesregardlessofwhothecustomeris.Thus,wewillseparatetheJobPositionandJobDescriptionattributesintoanothertablecalledPOSITION_TBL.
Inthischapteryouhavelearntthattherearedesignpracticesthatyoucanapplytoboosttheperformanceofyourdatabases.Duplicatedatavaluesareavoidedbyassigningprimaryandforeignkeysintables.Searchqueriesareheightenedthroughtheimplementationoftableindexes.Dataconsistencyandsecurityareimprovedbecauseofthenormalizationprocess.Thus,overalldatabaseorganizationisenhanced.InthenextchapteryouwilllearnsomeadvancetopicsinSQLdesignthatincludescursors,triggersanderrors.
ChapterEleven:DatabaseAdvanceTopics
InthischapteryouwillbeintroducedtosomeadvancetopicsinSQLthatgoesbeyondbasicdatabasetransactions.Evenifthissectiononlyincludesanoverviewofcursors,triggersanderrors,suchknowledgecouldpossiblyhelpyouextendthefeaturesofyourSQLimplementations.
Cursors
Generally,SQLcommandsmanipulatedatabaseobjectsusingset-basedoperations.Thismeansthattransactionsareperformedonagrouporblockofdata.Acursor,ontheotherhand,processesdatafromatableonerowatatime.Itiscreatedusingacompoundastatementanddestroyeduponexit.Thestandardsyntaxfordeclaringacursoris(whichmaydifferforeveryimplementation):
DECLARECURSORCURSOR_NAMEIS{SELECT_STATEMENT}
Youcanperformoperationsonacursoronlyafterithasbeendeclaredordefined.
OpenaCursor
Oncedeclared,youperformanOPENoperationtoaccessthecursorandthenexecutethespecifiedSELECTstatement.TheresultsoftheSELECTquerywillbesavedinacertainareainthememory.Thestandardsyntaxforopeningacursoris:
OPENCURSOR_NAME;
FetchDatafromaCursor
TheFETCHstatementisperformedifyouwanttoretrievethequeryresultsorthedatafromthecursor.Thestandardsyntaxforfetchingdatais:
FETCHNEXTFROMCURSOR_NAME[INTOFETCH_LIST]
InSQLprogramming,theoptionalstatementinsidethesquarebracketswillletyouassignthedataretrievedintoacertainvariable.
CloseaCursor
ThereisacorrespondingCLOSEstatementtobeexecutedwhenyouopenaparticularcursor.Oncethecursorisclosed,allthenamesandresourcesusedwillbedeallocated.Thus,thecursorisnolongeravailablefortheprogramtouse.Thestandardsyntaxforclosingacursoris:
CLOSECURSOR_NAME
Triggers
ThereareinstanceswhenyouwantcertainSQLoperationsortransactionstooccurafterperformingsomespecificactions.ThisscenariodescribesanSQLstatementthattriggersanotherSQLstatementtotakeplace.Essentially,atriggerisanSQLprocedurethatiscompiledinthedatabasethatexecutecertaintransactionsbasedonothertransactionsthathavepreviouslyoccurred.SuchtriggerscanbeperformedbeforeoraftertheexecutionofDMLstatements
(INSERT,DELETEandUPDATE).Inaddition,triggerscanvalidatedataintegrity,maintaindataconsistency,undotransactions,logoperations,modifyandreaddatavaluesindifferentdatabases.
CreateaTrigger
Thestandardsyntaxforcreatingatriggeris:
CREATETRIGGERTRIGGER_NAMETRIGGER_ACTION_TIMETRIGGER_EVENT
ONTABLE_NAME[REFERENCINGOLD_OR_NEW_VALUE_ALIAS_LIST]TRIGGERED_ACTION
TRIGGER_NAME-theuniqueidentifyingnameforthisobject
TRIGGER_ACTION_TIMETRIGGER_EVENT-thespecifiedtimethatthesetoftriggeredactionswilloccur(whetherbeforeorafterthetriggeringevent).
TABLE_NAME–thetableforwhichtheDMLstatementshavebeenspecified
TRIGGERED_ACTION–specifiestheactionstobeperformedonceaneventistriggered
Onceatriggerhasbeencreated,itcannotbealteredanymore.Youcanjust
eitherre-createorreplaceit.Howatriggerworksdependswhatconditionsyouspecify–whetheritwillfireatoncewhenaDMLstatementisperformedoritwillfiremultipletimesforeverytablerowaffectedbytheDMLstatement.YoucanalsoincludeathresholdvalueoraBooleancondition,thatwhensuchconditionismetwilltriggeracourseofaction.
DropaTrigger
Thebasicsyntaxfordroppingatriggeristhesameasdroppingatableoraview:
DROPTRIGGERTRIGGER_NAME;
Errors
Anerror-freedesignorimplementationisoneoftheultimategoalsinanyprogramminglanguage.Youcancommiterrorsbysimplynotfollowingnamingconventions,improperlywritingtheprogrammingcodes(syntaxortypoerrorslikeamissingapostropheorparenthesis)orevenwhenthedataentereddoesnotmatchthedatatypedefined.
Tomakethingseasier,SQLhasdevisedawaytoreturnerrorinformationsothatprogrammerswillbeawareofwhatisgoingonandbeabletoundertaketheappropriateactionstocorrectthesituation.Someoftheseerror-handlingmechanismsarethestatusparameterSQLSTATEandtheWHENEVERclause.
SQLSTATE
ThestatusparameterorhostvariableSQLSTATEisanerror-handlingtoolthatincludesawideselectionofanomalouscondition.Itisastringthatconsistsoffivecharacters(uppercaselettersfromAtoZandnumeralsfrom0to9),wherethefirsttwocharactersrefertotheclasscodewhilethenextthreeisthesubclasscode.TheclasscodeidentifiesthestatusafteranSQLstatementhasbeencompleted–whetheritissuccessfulornot(ifnotsuccessful,thenoneofthemajortypesoferrorconditionsarereturned).SupplementaryinformationabouttheexecutionoftheSQLstatementisalsoindicatedinthesubclasscode.
TheSQLSTATEisupdatedaftereveryoperation.Ifthevalueis‘00000’(fivezeroes),itmeansthattheexecutionwassuccessfulandyou
canproceedtothenextoperation.Ifitcontainsafive-characterstringotherthan‘00000’,thenyouhavetocheckyourprogramminglinestorectifytheerrorcommitted.TherearenumerouswaysonhowtohandleacertainSQLerror,dependingontheclasscodeandsubclasscodespecifiedintheSQLSTATE.
WHENEVERClause
TheWHENEVERclauseerror-handlingmechanismfocusesonexecutionexceptions.Withthis,anerrorisacknowledgedandgivestheprogrammertheoptiontocorrectit.Thisisbetterthannotbeingabletodosomethingifanerroroccurs.Ifyoucannotrectifyorreversetheerrorthatwascommitted,thenyoucanjustgracefullyterminatetheapplicationprogram.
TheWHENEVERclauseiswrittenbeforetheexecutableSQLcode,specificallyintheSQLdeclarationsection.Thebasicsyntaxis:
WHENEVERCONDITIONACTION;
CONDITION–valuecaneitherbeSQLERROR(returnsTRUEifSQLSTATEclasscodeisotherthan00,01or02)orNOTFOUND(returnsTRUEifSQLSTATEis02000)
ACTION–valuecaneitherbeCONTINUE(executionoftheprogramiscontinuednormally)orGOTOaddress(executionofadesignatedprogramaddress)
Inthischapteryouhavelearnttheprimaryroleofcursors,howtriggersworkandtheimportanceofhandlingerrorsinSQLprogramming.LearningtheseadvancetopicsisonestepcloserinmaximizingthepotentialsofyourSQLimplementations.
ChapterTwelve:Exercises
Exercise#1
CreateaninvoicetablenamedOrderInvoice_TBLinSQLiteStudiowiththefollowingfields:InvoiceID–primarykey,integerdatatypeCustomerID–integerdatatypeOrderID–integerdatatypeTaxAmt–decimaldatatypewithaprecisionof9andascaleof2
TotalSaleAmt–decimaldatatypewithaprecisionof9andascaleof2
ShippingFee–decimaldatatypewithaprecisionof9andascaleof2
Exercise#2
AftercreatingtheOrderInvoicetable,populatethefieldsusingtheINSERTstatementwiththefollowingdatavalues:
InvoiceID CustomerID
OrderID TaxAmount
TotalSales
ShippingFee
2016001 1 1005
$523.80 $198023.05
$1981.78
2016002 3 1006
$302.83 $198302.03
$2005.10
2016003 3 1007
$217.02 $20021.70
$1983.12
2016004 2 1008
$909.00 $200009.09
$19827.22
Exercise#3
CreateaviewnamedOrderLargeSales_VWfromOrderInvoicetablewherethetotalsalesisgreaterthan$150,000.00andthetaxamountislessthan$600.Theviewwillonlyconsistofthefollowingfields:CustomerID,OrderID,TaxAmountandTotalSales.
Exercise#4
DeletetheOrderInvoice_TBLtableandtheOrderInv_VWviewusingtheDMLcommandDROP.
ExerciseAnswers
AnswersforExercise#1
1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.
2. ClicktheQUERYtabattherightandtypethefollowingprogramminglines:CREATETABLEOrderInvoice_TBL(InvoiceIDINTEGERPRIMARYKEY,CustomerIDINTEGER,OrderIDINTEGER,TaxAmtDECIMAL(9,2),TotalSaleAmtDECIMAL(9,2),ShippingFeeDECIMAL(9,2));
3. ClicktheEXECUTEQUERYbutton .
AnswersforExercise#2
1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.
2. ClicktheQUERYtabattherightandtypethefollowingprogramminglines:INSERTINTOOrderInvoice_TBLVALUES(2016001,1,1005,523.80,198023.05,1981.78),(2016002,3,1006,302.83,198302.03,2005.10),(2016003,3,1007,217.02,20021.70,1983.12),(2016004,2,1008,909.00,200009.09,19827.22);
3. ClicktheEXECUTEQUERYbutton .
AnswersforExercise#3
1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.
2. ClicktheQUERYtabattherightandtypethefollowingprogramminglines:CREATEVIEWOrderInv_VWAS
SELECTCustomerID,OrderID,TaxAmt,TotalSaleAmtFROMOrderInvoice_TBLWHERETotalSaleAmt>150000ANDTaxAmt<600;
AnswersforExercise#4
1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.
2. ClicktheQUERYtabattherightandtypethefollowingprogramming
linestodeletethetable:DROPTABLEOrderInvoice_TBL;
3. ClicktheEXECUTEQUERYbutton .
4. Todeletetheview,typethefollowingprogramminglinesandthen
clicktheEXECUTEQUERYbutton .DROPVIEWOrderInv_VW;
Hereisaquickrecapofwhatwecoveredincaseyouneedarefresheronacertainstep:
1. YounowhaveanunderstandingofthehistoryandusesoftheSQL
language.2. Youlearnthowtodescriberelationaldatabasesanddatabasemanagement
systems.3. YoulearnthowtousethedifferentSQLcommandtypesandinstall
SQLiteStudio.4. Youlearnthowtodefineandusethevariousdatatypes.5. YoulearnthowtousetheCREATE,ALTERandDROPstatements.6. YoulearnthowtousetheINSERT,UPDATEandDELETEstatements.7. YoulearnthowtousetheSELECT,WHERE,ORDERBYandGROUP
BYstatements.8. YoulearnthowtousetheCOMMIT,ROLLBACKandSAVEPOINT
commands.9. Youalsolearnthowtodefine,createanddropviews.
10.Youlearnthowtoassignprimaryandforeignkeys,createindexesandnormalizedatabases.11.Youlearnthowtousecursors,triggersanderrors.
FinalWords
IhopethatyouhavetrulyenjoyedlearningtheessentialsofSQLprogramminganddatabasemanagementusingSQLiteStudiothroughthiseBook.IhadmadesurethatyouwilltremendouslybenefitfromreadingthisbymeetingyourgoalsinunderstandingwhatSQLdatabaseisatanaffordableprice.IamsurethatwiththeknowledgeyouhavegainedthroughtheguidelinesofthiseBook,youcannowplan,designandcreateyourveryowndatabasesinSQLiteStudio.
Youmayalsoconsiderlearningotherprogramminglanguages,yourknowledgeofSQLProgrammingwillgiveyouatremendousadvantageifyouwishtolearnotherlanguages.YoucanfindotherpopularprogrammingbooksHERE.
Bytheway,Iwouldgreatlyappreciateifyoucanprovideanyconstructivefeedbackorreviewsthatwillfurtherimprovemyskillsasawriter.Pleasefeelfreetosendmeanemail,especiallyifyouhaveanythingtoclarifyorask(evenifyoujustwanttodropbyandsayhello!)[email protected].
Again,thankyouandGodblessalways!
FelixAlvaro