SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning...

140

Transcript of SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning...

Page 1: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database
Page 2: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

SQL

EasySQLProgramming&DatabaseManagementForBeginners.YourStep-By-StepGuideToLearningTheSQLDatabase.

FelixAlvaro

Page 3: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Acknowledgments

Firstly,IwanttothankGodforgivingmetheknowledgeandinspirationtoputthisinformativebooktogether.Ialsowanttothankmyparents,mybrothersandmypartnerSilviafortheirsupport.

Page 4: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 5: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

©Copyright2016byD.A.Alvaro-Allrightsreserved.Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.Itisnotlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibited.

Page 6: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 7: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Tostartyourjourneyinthisfieldofdatabaseprogrammingandmanagement,letthiseBookserveasyourinitialguideineducatingyourselfwiththebasicsofSQL.Iwillprovideyouanoverviewofhowthelanguagestarted,thevariousfeaturesofthesoftwareanditsenvironment,thedifferentcommandsandfunctions,theavailableerror-handlingtools,someadvancedtopicsandmanymore!MyultimateaimisforyoutoappreciatethepotentialsofSQLandgrasptheprogrammingconceptsinacoolway.Sowhatareyouwaitingfor?Letusgetstarted!

Page 8: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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).

Page 9: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 10: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 11: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 12: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 13: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

complexstructures.

RelationalDatabaseFundamentalsTakingthediscussionfurtherintoamoretechnicalaspect,arelationaldatabaseisanentityconsistingoflogicalunitsknownastables.ThisrelationaldatabasemodelwasfirstformulatedbyDr.E.F.Coddin1970.Howthetablesarerelatedtoeachotherdefinestheirrelationships.Inthisscenario,dataissimplifiedintosmalleryetmorelogicalandmanageableunitsthatoptimizethedatabaseperformance.Thefollowingfigureshowsanillustrationonhowthevariouscomponentsofarelationaldatabaseareconnectedtoeachother.

Atableconsistsofrowsandcolumnsthatstoredata.Inarelationaldatabase,thesetablesarerelatedtooneanotherimprovingthedataretrievalprocesswhenaqueryissubmittedbytheuser.Foryoutoclearlypictureoutthisidea,converttheinformationfoundonthecallingcardholderintoaspreadsheetlikeaMicrosoftExcelfile.Assumethattheseareyourcontactsfromcompaniesthathaveorderedproductsandservicesfromyourbusiness.YouwillhaveatleastaCUSTOMERTABLE(containingallimportantinformationaboutyourcontacts)similartothefollowing:

Page 14: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 15: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 16: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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).

Page 17: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Inthischapteryouhavelearnttheessentialfeaturesofadatabaseandhowittransformstobecomearelationaldatabase.Also,youhadanoverviewofthehistoryandcharacteristicsofdatabasemanagementsystems.InthenextchapteryouwilllearnthefundamentalstructureoftheSQLlanguageanditscomponents.

Page 18: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 19: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 20: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 21: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 22: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 23: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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,

Page 24: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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,

Page 25: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 26: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 27: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

3. Afterdownloadingthesoftware,gotothefolderwheretheapplicationwassaved(usuallytheDownloadsFolderinWindows).ClickontheExtracttabontopthenchoosetheExtractalloption.

4. YouwillgettheExtractCompressed(Zipped)Foldersdialogbox.ChangethedestinationfoldertoC:\SQLthenclicktheExtractbutton.ThiswillbethefolderwhereallyourSQLitefileswillbesaved.

Page 28: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

5. Onceallthefileshavebeenextracted,youwillhavetheSQLiteStudiosubfolder.

6. FindtheapplicationprogramnamedSQLiteStudioinsidethesubfolder.Tocreateashortcutonyourdesktop(soyoucanquicklylaunchtheapplication),right-clickthefilename,selectSendtooptionthenchooseDesktop(createshortcut).

Page 29: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

7. Whenyoudouble-clicktheSQLiteStudioicononyourdesktop,

8. youshouldgetthefollowingscreen:

Page 30: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

TheDatabaseNavigator(leftpane)showsallthelogicalunitsofthedatabasesuchastablesandviews.ThegraypaneattherightistheSQLWorkAreawhereyouwillwriteyourquerystatements.Youwillhaveabetterunderstandingofthisprogram’sgraphicaluserinterfaceinthesucceedingchapters.

InthischapteryouhavelearntthefundamentalfeaturesoftheSQLdatabaselanguage,whichincludesprogramflow,syntaxcharacteristic,reservedwordslist,schema,domain,constraintandmore.ThemaincategoriesofSQLcommandswerealsointroduced,thatgovernthevariousfunctionsoftheprogramminglanguage.YouwerealsogivenaguideonhowtodownloadandinstallSQLiteandSQLiteStudioforyourapplicationsoftware.InthenextchapteryouwilllearnthedefinitionofdataanditsvarioustypessupportedbythedifferentSQLimplementations.

Page 31: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 32: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 33: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 34: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 35: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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”.

Page 36: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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:

Page 37: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

CREATETABLEAmericaInvoice(InvoiceIDINTEGERPRIMARY

KEY,CustomerIDINTEGER,OrderIDINTEGER,TotalSaleAmtUSDollar,ShippingFeeUSDollar

);

CREATETABLEUnitedKingdomInvoice(InvoiceIDINTEGERPRIMARY

KEY,CustomerIDINTEGER,OrderIDINTEGER,TotalSaleAmtUSDollar,ShippingFeeUSDollar

);

InthischapteryouhavelearntthecharacteristicsofthevariousdatatypesavailableintheSQLlanguage.Youwerealsoabletounderstandtheneedtocreateuser-defineddatatypestomakeyourdatabaselesscomplicatedandmoreportable.InthenextchapteryouwilllearnhowtousethedifferentDataDefinitionLanguagestatementsincreatingdatabaseobjectsusingSQLiteStudio.

Page 38: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 39: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 40: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

4. YouwillnowhavetheSample_DBobjectinsidetheDatabase

Navigatorpane.

CreateaNewTable

1. ClicktheTOOLSmenuthenselectOPENSQLEDITOR.YouwillhavetheSQLeditorareaattherightpane.Ifyoudouble-clickSample_DB,youwillseeTABLESandVIEWSunderthedatabaseobject.Rightnow,therearenotablesnorviewspresentsoyouwillcreateoneusingtheSQLEditorpane.

Page 41: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. UndertheQUERYTab,typethefollowinglinesofcode

CREATETABLECustomer_TBL(CustomerIDINTEGERNOTNULLPRIMARYKEY,

CustomerNameVARCHARNOTNULL,JobPositionVARCHAR,CompanyNameVARCHARNOTNULL,USStateVARCHARNOTNULL,ContactNoBIGINTEGERNOTNULL);

3. ClicktheEXECUTEQUERYbutton ontopoftheQUERYTaborpressF9onthekeyboard.YouwillnowhavetheCustomer_TBLtablewith6columns.

Page 42: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 43: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

CompanyAddVARCHAR;

2. AfterclickingtheEXECUTEQUERYbutton ,theCompanyAddcolumnisaddedaftertheContactNocolumn.Thisfieldcontainsvaluesofstringdatatype.

DROPStatementYouusetheSQLDROPstatementifyouwanttodelete

Page 44: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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;

Page 45: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. ClicktheEXECUTEQUERYbutton andinstantlytheCustomer_TBLtableisdeleted.

InthischapteryouhavelearnthowtoencodeprogramminglinesusingthecommonDDLcommandstatementsincreating,alteringanddroppingdatabasetablesinSQL.InthenextchapteryouwilllearnthedifferentDMLcommandsthatwillallowyoutomanipulateinformationcontainedindatabasetables.

Page 46: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 47: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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)

Page 48: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. ClicktheEXECUTEQUERYbutton andyouwillgetthefollowingscreen(thereshouldbenoerrorsintheStatusArea):

3. Tocheckiftherecordofdatawasinsertedinthetable,double-clickCustomer_TBLattheleftpane.ClicktheDATAtabattherightpane,whichisinbetweenSTRUCTUREandCONSTRAINTStabs.Yourtableshouldbesimilartowhatisshowninthescreenbelow:

Page 49: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

4. Clickthe optionatthebottomleftcornerofthescreen.Toaddanotherrecordwithoutspecifyingthecolumnnames,deletetheprogrammingcodesinsidetheQUERYtabandtypethefollowinglines:

INSERTINTOCustomer_TBLVALUES(2,‘KevinLord’,‘VP’,‘BestTooling’,‘NY’,5181234567)

5. ClicktheEXECUTEQUERYbutton andprovidedthattheorderofthevaluescorrespondsexactlytotheorderoftheCustomer_TBLtable’scolumns,thenthereshouldbenoerrorsintheStatusArea.

Page 50: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

6. ClicktheCUSTOMER_TBL(SAMPLE_DB)option

atthebottomleftcornerofthescreen.UndertheGRIDVIEWtab,click

theREFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldseethenewrecordaddedtothetable.

MultipleRowsataTime

Page 51: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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 .

Page 52: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

3. Gotothe

option.Makesuretoclickthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldnowseetwomorerecordsinsertedtothedatabasetable.

Page 53: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 54: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 55: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Fromthepreviousdiscussion,youaddedarecordofcustomerinformationwithoutprovidingdatafortheJobPositionfield.Ifincaseyouhavelearnedthatthecontactpersonisthevice-presidentofthecompany,thenyoucanmodifythisexistingrecord.

1. GobacktotheSQLEDITORbyclickingtheoption.Enterthefollowinglinesofcode:UPDATECustomer_TBL

SETJobPosition=‘VP’WHERECustomerName=‘MikeArmhs’;

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.

Page 56: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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’;

Page 57: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.

3. Clickthe optionthenclickthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Youshouldnowseethattheprevious‘VP’valuehasbeenchangedto‘Vice-President’.

AllRecordsataTime

Ifyouwanttogivemoreemphasistothecustomernamebychangingittouppercaseletters,thenyoucanmodifyalltherecordsofthedatabasetableatonetime.Inthiscase,youwillnotbeneedingtheWHEREclauseanymore.

Page 58: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

1. Clickthe optionatthebottomleftcornerofthescreenandthenenterthefollowingprogramminglines:

UPDATECustomer_TBL

SETCustomerName=UPPER(CustomerName)

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.

3. Clickthe optionthenclickthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Noticethattheformatofthecustomernameforalltherecordsinthetablehavebeenchangedtocapitalletters.

Page 59: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 60: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

1. GototheDATABASENAVIGATORthenright-clickonCustomer_TBL.ChooseCREATEASIMILARTABLE.

2. Youwillbeaskedtoprovideanameforyourtable.TypeCustomer_TBL2insidetheTABLENAMEinputbox.

3.Clickonthe

Page 61: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

COMMITSTRUCTURECHANGESbutton undertheSTRUCTUREtab.Youwillgetthescreenbelow.

4. ClickontheOKbuttonandanewCustomer_TBL2tablewillbecreated.ThiswillbethetablethatyouwillworkaroundtodemonstratetheDELETEcommand.

Page 62: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

AtthispointintimeCustomer_TBL2tableisempty,soyouhavetocopytherecordsfromCustomer_TBLtable.Todothis,followthestepsbelow:

1. Clickthe optionthenclickthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Thiswillensurethatyourdatainthedatabasetableisupdated.

2. Clickontopofthefirstrow,justbeforetheCustomerIDcolumnheading.Thiswillhighlightalltherecordsinthetable.

Page 63: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

3. Tocopythevalues,right-clickonthefirsthighlightedcell(justundertheCustomerIDcolumn)thenchooseCOPY.

4. Double-clickonCustomer_TBL2locatedintheleftpane.ClicktheDATAtabandmakesurethatyouareontheGRIDVIEWtab.Youwillseethesamecolumnsasintheoriginaltable,whichyouwillbepopulatingwiththedatayoucopiedfromtheCustomer_TBLtable.

Page 64: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

5. ClickthedropdownarrowbesidetheINSERTROWbutton(justbelowtheGRIDVIEWtab).SelectINSERTMULTIPLEROWSoption.

Page 65: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

6. InsidetheNUMBEROFROWSTOINSERTinputboxtype5.ClickOK.

7. Yourtablewillnowhave5rowsofdatathatcontainNULLvalues.ThisiswhereyouwillinsertthevaluesthatyoucopiedfromtheCustomer_TBLtable.

8. Right-clickonthefirstcellthenchoosethePASTEoption.

Page 66: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

9. AllthedatavaluesfromtheCustomer_TBLtablewillbeinsertedtotheCustomer_TBL2table,whichyouwillmanipulatetodemonstratetheDELETEcommand.

10.ClickontheCOMMITSTRUCTURECHANGESbutton

Page 67: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

tosavethedatainthetable.

SingleRecord

TodeleteonlyonerecordofdatafromtheCustomer_TBL2tablewherethecustomer’snamematchesto‘KATHYALE’:

1. Clickthe option,typethefollowinglinesofcodeintheQUERYtabandthenclicktheEXECUTEQUERYbutton

.

DELETEFROMCustomer_TBL2

WHERECustomerName=‘KATHYALE’;

2. Tocheckiftherecordhasbeendeleted,gototheCustomer_TBL2tablebyclickingon

Page 68: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

.Thenclickonthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.Youwillnoticethattherecordhasbeendeletedalready.

MultipleRecords

Todelete2recordsofdatafromtheCustomer_TBL2tablewherethecustomer’spositionmatchesto‘Vice-President’:

1. Clickthe option,typethefollowinglinesof

codeandthenclicktheEXECUTEQUERYbutton .

DELETEFROMCustomer_TBL2

WHEREJobPosition=‘Vice-President’;

Page 69: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. Tocheckiftherecordhasbeendeleted,gotothe

Customer_TBL2tablebyclickingon

.Thenclickonthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.Youwillnoticethatthetworecordshavebeendeletedalready.

WholeTable

TodeletealltheremainingrecordsfromtheCustomer_TBL2tableatonetime:

1. Clickthe option,typethefollowinglinesofcodeintheQUERYtabandthenclicktheEXECUTEQUERY

Page 70: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

button .

DELETEFROMCustomer_TBL2

2. Tocheckiftherecordhasbeendeleted,gotothe

Customer_TBL2tablebyclickingon

.ThenclickontheREFRESH

TABLEDATAbutton orpressF5onyourkeyboardtoupdatethevalues.YouwillnoticethatexecutingthesingleDELETEcommandhasdeletedalltherecordsfromthetable.

InthischapteryouhavelearnthowtoencodeprogramminglinesusingthemostcommonlyusedDMLcommandstatementsininserting,updatinganddeletingrecordsfromdatabasetablesinSQL.InthenextchapteryouwilllearnthedifferentDQLcommandsthatwillallowyoutoretrievevaluableinformationcontainedindatabasetables.

Page 71: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 72: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

ToselectallthedatarowsfromtheCustomer_TBLtable:

1. Clickthe optionandthentypethefollowinglinesofcode:

SELECT*FROMCustomer_TBL;

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

TheresultbasicallyshowstheentiredataoftheCustomer_TBLtablesincethecodeinstructsthedatabasetoselectalltherowsandcolumnsofthesaidtable.

Page 73: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

WHEREStatement

Whenyouwanttobemorespecificinselectingrowsofdatafromyourdatabasetablesthenyouneedtoaddabitofcomplexitytoyourprogramminglines.Atthispoint,youneedthefunctionoftheWHEREclause,whichmeansthattheSELECToperationwillbeperformedoncethestatedconditioninsidesuchclauseistrue.ThesyntaxoftheSELECTstatementwiththeWHEREclauseisasfollows:SELECTCOLUMN_LIST

FROMTABLE_NAMEWHERECONDITION;

ToselectonlytherowsofdatawherethejobpositionofthecustomerisVice-President:

1. Clickthe optionandthentypethefollowinglinesofcode:

SELECT*FROMCustomer_TBLWHEREJobPosition=‘Vice-President’;

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

Page 74: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

TheresultshowstherecordsofthetwocustomersnamedKevinLordandMikeArmhswhoarebothVice-Presidentsoftheirrespectivecompanies.

Whatifyouonlywanttoselectcertaincolumnsofthetable,maybejustthefullnameandcompanyofthecustomer?Youwillnowmodifyyourlinesofcodeintothefollowing:

1. IntheQUERYtab,changethewildcardcharacter*(asterisksign)intoCustomerNameandCompanyNamebytypingthefollowing:

SELECTCustomerName,CompanyNameFROMCustomer_TBLWHEREJobPosition=‘Vice-President’;

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

Page 75: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Byspecifyingthecolumnsyouwanttoselect,youaretryingtocustomizewhatdatayouwanttoretrieveandhowyouwantthemtobedisplayed.Inthepreviousexample,youonlywantedtoknowthecustomer’snameandhiscompanywherethejobpositionisvice-president.

ORDERBYandGROUPBYStatements

Whenyouwantthedatayouretrievetobedisplayedandsortedinsomeway,thenyouneedtoincludetheORDERBYorGROUPBYoperatorattheendofyourSQLstatement.TheprimaryfunctionoftheORDERBYstatementisbasicallytoarrangedatausingaspecificorder,whetherascendingordescending.Ontheotherhand,theGROUPBYstatementisusedtoputidenticaldatatogetherandarrangethequeryoutputintogroups.

ThestandardsyntaxfortheORDERBYclauseis:SELECTCOLUMN_LIST

Page 76: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

FROMTABLE_NAMEORDERBYCOLUMN_LIST[ASC|DESC];Bydefault,ORDER

BYsortsindividualrowsinascendingorder.IfyouwanttoarrangeyourrecordsindescendingorderthenyouhavetoindicatetheDESCoperatorattheendoftheORDERBYclause.

ToretrieveallcustomerrecordsfromtheCustomer_TBLtableanddisplaytheminascendingorderbyUSstate:

1. Clickthe optionandthentypethefollowinglinesofcode:

SELECT*FROMCustomer_TBLORDERBYUSState;

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

Page 77: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Sinceyoudidnotspecifyhowtherecordswillbesorted,thedatarowswerearrangedalphabetically(inanascendingorder)usingtheUSStatecolumn.Ifyouwanttosortyourrecordsindescendingorder:

1. InsidetheQUERYtab,addDESCafterUSStateintheORDERBYclause.

SELECT*FROMCustomer_TBLORDERBYUSStateDESC;

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

Page 78: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Ifyouwanttodeterminesomethingaboutagroupofrecordsorneedtocombinecolumnswithduplicatevaluesinalogicalway,thenitistimetousetheGROUPBYclause.Othertermssimilartogroupingareaggregating,summarizingandrollingup.Toillustratethis,ifyouwanttoknowhowmanycustomersarethereforeveryjobpositionintheCustomer_TBLtablethenweneedtocountthenumberofrecordsanddisplaythetotalnumberofcustomersperjobposition.

1. Clickthe optionandthentypethefollowinglinesofcode:

SELECTJobPosition,COUNT(*)ASnumber_of_recordFROMCustomer_TBL

GROUPBYJobPosition;

Page 79: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2. ClicktheEXECUTEQUERYbutton .TheresultofthisSELECTcommandisdisplayedinsidetheGRIDVIEWtab.

Intheexampleabove,theCOUNTfunctionwasintroducedtoarrangethedataingroups.ThefollowingisasummaryofthecommonaggregatefunctionsusedtogetherwiththeGROUPBYstatement(xdenotesthecolumnnamewhereyouwanttoperformthefunction):

AVG(x)–computestheaverageofallthecolumnvalues(nullvaluesremoved)COUNT(x)–countsthenumberofnon-nullvaluesinthecolumn

COUNT(*)–countsthenumberofrecords

MAX(x)–computesthemaximumvalueinthecolumn(nullvaluesremoved)

Page 80: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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;

Page 81: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

InthischapteryouhavelearnthowtoencodeprogramminglinesusingthemostcommonlyusedDQLcommandstatementsinselecting,orderingandgroupingrecordsfromdatabasetablesinSQL.Inthenextchapteryouwilllearnthedifferenttransactionalcontrolcommandsthatwillallowyoutomanageseveralrelationaldatabasetransactions.

Page 82: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 83: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

transactionscurrentlyrunninginthedatabase,typethefollowingprogramminglineintheQUERYtabthenclicktheEXECUTEQUERY

button :

ENDTRANSACTION;

2. Double-clickCustomer_TBLundertheTABLESlistintheDATABASENAVIGATORpane.ClicktheDATAtabattherightandmakesurethattheGRIDViewisdisplayed.YouwillseealltherecordsoftheCustomer_TBLtable.

3. Clickthefirstcolumnofthelastrowofthetable,whichisCustomerID5.

Page 84: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

4. Clickthedrop-downarrowbesidetheINSERTROW(INS)buttonandselectPLACENEWROWSBELOWSELECTEDROWoption.

5. ThistimeclicktheINSERTROW(INS)buttonandyouwillseeanewemptyrowaddedtothetable.

6. Addthefollowingdatavaluesinthenewrecord:

Page 85: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

CustomerID:6CustomerName:JOHNDEPPJobPosition:PresidentCompanyName:RockersMineCompanyUSState:TXContactNo:3467654321

7. ClicktheCOMMITbutton topermanentlysavethenewdatavaluesaddedtothetable.

ROLLBACKCommand

IftheCOMMITcommandsavesallthechangestothedatabase,theROLLBACKcommandisthereversewherealltheunsavedchangeswillbediscarded.However,youcanonlyundotransactionssincethelastCOMMITorROLLBACKstatementexecuted.Thestandardsyntaxforthistransactionalcontrolcommandis:

ROLLBACK[WORK];

Also,beforeyoucanperformaROLLBACKcommand,makesurethattransactionshavestarted.Thismeansthatyouneedtoexecutethefollowingprogrammingstatementattheverybeginning:

Page 86: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

BEGINTRANSACTION;

TodemonstratehowaROLLBACKstatementworks,youwillmodifytheDROPTABLEcommandinSQLiteStudio:

1. Clickthe option.IntheQUERYtab,typethefollowing

programmingstatementandclicktheEXECUTEQUERYbutton :

BEGINTRANSACTION;

2. Clickthe optionandcleartheQUERYtab.Typethe

followingandthenclicktheEXECUTEQUERYbutton .YouwillnoticethattheCustomer_TBLtableisnowremovedfromtheTableslist.

Page 87: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

DROPTABLECustomer_TBL;

3. Clickthe optionagainandcleartheQUERYtab.Type

thefollowingandthenclicktheEXECUTEQUERYbutton :

ROLLBACK;

4. TocheckiftheROLLBACKcommandreversedthedeletionoftheCustomer_TBLtable,right-clickanywhereinsidetheDATABASENAVIGATORpane.ChooseREFRESHALLDATABASESCHEMASoption.

Page 88: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

5. ClicktheTABLElistattheleftpane.YoushouldnowseethattheCustomer_TBLtableisbackundertheTABLElist.

SAVEPOINTCommand

Whenyouwanttoreversethetransactionjustbacktoacertainpointand

nottheentiretransaction,thenyouhavetoexecutetheSAVEPOINTcommandbeforeperformingaROLLBACKaction.ThisishowyoumanageseveraltransactionsintosmallergroupsofSQLcommands.Thestandardsyntaxforthistransactionalcontrolcommandis:

SAVEPOINTSAVEPOINT_NAME;

Page 89: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

WhenusingtheSAVEPOINTandtheROLLBACKcommandstogether,thesyntaxis:

ROLLBACKTOSAVEPOINT_NAME;

Asavepointnamecanbethesameasthedatabaseobject’snametowhichyouwillbeperformingtheSQLtransactions.However,youshouldremembertomakethemunique,differentfromthegroupoftransactionsthatyouwanttobreakdownintoseveralpointsorsegments.

TodemonstratehowaSAVEPOINTwithaROLLBACKcommandworks,youwilldeletecertainrecordsfromtheCustomer_TBLtableandreversethistransaction.

1.Clickthe option.IntheQUERYtab,typethefollowingprogrammingstatementandclicktheEXECUTEQUERY

button :

BEGINTRANSACTION;

Page 90: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

2.Clickthe optionagainandcleartheQUERYtab.Thentypethefollowing:

SAVEPOINTCustomer_SP1;

ClicktheEXECUTEQUERYbutton .AsavepointsectioniscreatedbeforedeletingthelastrecordoftheCustomer_TBLtable.

3.TodeletethelastrecordoftheCustomer_TBLtable,clickthe

optionandcleartheQUERYtab.Typethefollowingand

thenclicktheEXECUTEQUERYbutton :

DELETEFROMCustomer_TBLWHERECustomerID=6;

Page 91: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

4.Tocheckiftherecordwasdeleted,double-clickCustomer_TBLundertheTABLESlistintheDATABASENAVIGATORpanethenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clickthe

REFRESHTABLEDATAbutton orpressF5onyourkeyboard.Yourtableshouldbethesameasthefollowing:

5.Tocreatethesecondsavepointsection,clickthe optionagain.CleartheQUERYtabandthentypethefollowing:

SAVEPOINTCustomer_SP2;

Page 92: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

ClicktheEXECUTEQUERYbutton .ThistimeasavepointsectioniscreatedbeforedeletingtherecordwheretheCustomerIDisequalto5.

6.TodeletetherecordwheretheCustomerIDisequalto5,clickthe

optionagainandcleartheQUERYtab.Typethefollowing

andclicktheEXECUTEQUERYbutton :

DELETEFROMCustomer_TBLWHERECustomerID=5;

7.Tocheckiftherecordwasdeleted,clickthe

Page 93: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

optionatthebottomleftcornerofthescreenthenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clicktheREFRESHTABLE

DATAbutton orpressF5.Yourtableshouldbethesameasthefollowing:

8.Toreversethelasttransactiondone,clickthe optionagainandcleartheQUERYtab.Typethefollowingandthenclickthe

EXECUTEQUERYbutton :

ROLLBACKTOCustomer_SP2;

Page 94: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

9.Tocheckiftherecorddeletionwasreversed,clickthe

optionandthenclicktheDATAtabattheright.Under

theGRIDVIEWtab,clicktheREFRESHTABLEDATAbutton orpressF5.Yourtableshouldbethesameastheonebelow:

10.Toundothefirstrecorddeleted,clicktheoptionagainandcleartheQUERYtab.Typethefollowingandthenclick

theEXECUTEQUERYbutton :

ROLLBACKTOCustomer_SP1;

Page 95: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

1.Tocheckiftherecorddeletionwasreversed,clickthe

optionandthenclicktheDATAtabattheright.UndertheGRIDVIEWtab,clicktheREFRESHTABLEDATAbutton

orpressF5.Yourtableshouldbethesameastheonebelow:

InthischapteryouhavelearnttheprimaryfunctionsofthethreetransactionalcontrolcommandsinsavingordiscardingchangesinanSQLdatabase.InthenextchapteryouwilllearntheimportanceofviewsandhowtomanipulatethemusingCREATE,UPDATEandDROPcommands.

Page 96: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 97: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 98: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

3. Tocheckthecontentoftheview,double-clickCustomer_VWintheleftpanethentheDATAtabinSQLWORKAREA.TheCustomer_VWviewshouldcontainalltherecordsoftheCustomer_TBLtable.

CreatingaViewfromSelectedColumnsofaSingleTable

Ifyouwanttocreateaviewthatcontainsonlythecontactdetailsofthecustomer(CustomerName,CompanyNameandContactNo),thenyouwillselectcertaincolumnsfromtheCustomer_TBLtable.

1. Clickthe optionanddeleteeverythinginsidetheQUERYtab.Thentypethefollowinglinesofcode:

Page 99: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 100: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 101: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

listintheleftpane.

3. Double-clicktheOrder_TBLintheleftpanethenclickonDATAtabattheleft.YouwillpopulatethistablewithdatavaluesinGRIDVIEWmode.

4. ClicktheINSERTROWbutton andthenselectthefirstoption–INSERTMULTIPLEROWS.

Page 102: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

5. Enter“4”intheNUMBEROFROWSTOINSERTinputbox(sincethereare4recordsintheORDERTABLEfromChapter2)thenclickOK.

6. TheOrder_TBLtablewillnowhave4rowsand5columns.InsteadofusingSQLstatementstopopulatethistable,youwillenterthevaluesdirectlyintothetable(checkthedatavaluesinChapter2).

Page 103: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

+

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.

Page 104: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

3. Tocheckthecontentofthisview,double-clickOrderDelivery_VWintheleftpanethenclicktheDATAtabattheright.

Inthisview,twocolumnswereselectedandrenamedfromtheCustomer_TBLtable-CompanyNamechangedtoCompanyDeliveredToandUSStatechangedtoStateDestination.TheothertwowerefromOrder_TBLtable—OrderIDandOrderQty(theoriginalcolumnnameswereretained).TherowsretrievedfrombothtablesarethoserecordswheretheCustomerIDoftheCustomer_TBLtablematchestheCustomerIDoftheOrder_TBLtable.

DroppingViewsTheDROPVIEWcommandisthestatementusedtodestroyanexistingviewfromthedatabase.Thebasicsyntaxis:DROPVIEWVIEW_NAME;TodropordeletetheentireCustomer_VWview:

Page 105: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

1. Clickthe option,emptyQUERYtabandthentypethefollowinglinesofcode:

DROPVIEWCustomer_VW;

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnoticethattheCustomer_VWviewisalreadydeletedfromtheViewslist.

InthischapteryouhavelearntthedefinitionandimportanceofdatabaseviewsinSQL.Youhavealsoperformedcommonoperationsinmanipulatingviews,suchascreatinganddroppingthem.Inthenextchapteryouwilllearnmorein-depthconceptsindesigningdatabasesinSQL–primaryandforeignkeys,indexesandnormalizeddatabases.

Page 106: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 107: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 108: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 109: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 110: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

(CustomerID);

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnowhaveCustomerID_IDXundertheINDEXESlistintheOrder_TBLtable.

DroppingIndexes

Justlikedroppingatableoraview,youwillusethefollowingbasicsyntax:DROPINDEXINDEX_NAME;Rememberthatyoucanre-

Page 111: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

createtheindexafterithasbeendeleted,butmakesureyoutakeextraprecautionwhenperformingsuchtransactions.Also,whenyoudeleteatable,youwillalsobedeletingallthecorrespondingindexeswithit.Sometimesyoumayonlyneedtodeletetheindexandretainthetable.Suchimplementationhappenswhenyouonlywanttofixanindexproblemtooptimizethedatabaseperformanceandreducefragmentation.

Todroptheindexthatwehavecreatedpreviously:

1. Clickthe optionandmakesuretheQUERYtabisempty.Thentypethefollowing:

DROPINDEXCustomerID_IDX;

2. ClicktheEXECUTEQUERYbutton ontopoftheQUERYtab.YouwillnownoticethattheCustomerID_IDXindexhasbeendeletedfromtheIndexeslist.

Page 112: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 113: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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:

Page 114: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Basedfromthefigureabove,theentirecompanydatabasewasdividedintotwosmallertables–EMPLOYEE_TBLandCUSTOMER_TBL.TheprimarykeyforthesetablesareEmployeeIDandCustomerIDrespectively.Inthisway,itiseasiertoreadandmanagetheinformationascomparedtoonebigtablewithsomanycolumnsandrows.Thedatavaluesstoredineachtablerefertotwoseparateentities,meaningthosepiecesofinformationdescribingthecompany’semployeesareonlypresentintheEMPLOYEE_TBLtablewhilethosethatonlypertaintothecustomersarestoredintheCUSTOMER_TBLtable.

SecondNormalForm(2NF)

Afteryouaredonewiththefirstnormalform,thenextstepisderivingthesecondnormalform(2NF).Thisprocessfocusesonfunctionaldependencythatdescribestherelationshipsbetweenattributes.Whenanattributedeterminesthevalueofanother,thenthereisfunctionaldependencybetweenthem.Inthiscase,youwillstoredatavaluesfromtheEmployeeandCustomertablesthatarepartlydependentontheirprimarykeysintoseparatetables.

Page 115: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

ThefigureaboveshowsthatthoseattributesthatarepartlydependentontheEmployeeIDprimarykeyhavebeenremovedfromEMPLOYEE_TBLandstoredinanewtablecalledEMPLOYEE_SALARY_TBL.Theattributesthatwereretainedintheoriginaltablearefullydependentontheprimarykey–meaningthatforeveryrecordoflastname,firstname,addressandcontractnumberthereisacorrespondingparticularemployeeID.UnliketheEMPLOYEE_SALARY_TBL,aparticularemployeeIDdoesnotreferenceauniqueemployeepositionnorsalaryrate.Therecouldbemorethanoneemployeewiththesameposition(EmpPosition),payrate(Payrate)andbonus(Bonus).

Page 116: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 117: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Inthischapteryouhavelearntthattherearedesignpracticesthatyoucanapplytoboosttheperformanceofyourdatabases.Duplicatedatavaluesareavoidedbyassigningprimaryandforeignkeysintables.Searchqueriesareheightenedthroughtheimplementationoftableindexes.Dataconsistencyandsecurityareimprovedbecauseofthenormalizationprocess.Thus,overalldatabaseorganizationisenhanced.InthenextchapteryouwilllearnsomeadvancetopicsinSQLdesignthatincludescursors,triggersanderrors.

Page 118: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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:

Page 119: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 120: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

(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

Page 121: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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

Page 122: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 123: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

ChapterTwelve:Exercises

Exercise#1

CreateaninvoicetablenamedOrderInvoice_TBLinSQLiteStudiowiththefollowingfields:InvoiceID–primarykey,integerdatatypeCustomerID–integerdatatypeOrderID–integerdatatypeTaxAmt–decimaldatatypewithaprecisionof9andascaleof2

TotalSaleAmt–decimaldatatypewithaprecisionof9andascaleof2

ShippingFee–decimaldatatypewithaprecisionof9andascaleof2

Page 124: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Exercise#2

AftercreatingtheOrderInvoicetable,populatethefieldsusingtheINSERTstatementwiththefollowingdatavalues:

InvoiceID CustomerID

OrderID TaxAmount

TotalSales

ShippingFee

2016001 1 1005

Page 125: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$523.80 $198023.05

Page 126: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$1981.78

2016002 3 1006

Page 127: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$302.83 $198302.03

Page 128: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$2005.10

2016003 3 1007

Page 129: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$217.02 $20021.70

Page 130: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$1983.12

2016004 2 1008

Page 131: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$909.00 $200009.09

Page 132: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

$19827.22

Page 133: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Exercise#3

CreateaviewnamedOrderLargeSales_VWfromOrderInvoicetablewherethetotalsalesisgreaterthan$150,000.00andthetaxamountislessthan$600.Theviewwillonlyconsistofthefollowingfields:CustomerID,OrderID,TaxAmountandTotalSales.

Page 134: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

Exercise#4

DeletetheOrderInvoice_TBLtableandtheOrderInv_VWviewusingtheDMLcommandDROP.

Page 135: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

ExerciseAnswers

AnswersforExercise#1

1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.

2. ClicktheQUERYtabattherightandtypethefollowingprogramminglines:CREATETABLEOrderInvoice_TBL(InvoiceIDINTEGERPRIMARYKEY,CustomerIDINTEGER,OrderIDINTEGER,TaxAmtDECIMAL(9,2),TotalSaleAmtDECIMAL(9,2),ShippingFeeDECIMAL(9,2));

3. ClicktheEXECUTEQUERYbutton .

Page 136: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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 .

Page 137: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

AnswersforExercise#3

1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.

2. ClicktheQUERYtabattherightandtypethefollowingprogramminglines:CREATEVIEWOrderInv_VWAS

SELECTCustomerID,OrderID,TaxAmt,TotalSaleAmtFROMOrderInvoice_TBLWHERETotalSaleAmt>150000ANDTaxAmt<600;

Page 138: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

AnswersforExercise#4

1. LaunchSQLiteStudio.ClickonTOOLSmenuandthenchooseOPENSQLEDITORoption.

2. ClicktheQUERYtabattherightandtypethefollowingprogramming

linestodeletethetable:DROPTABLEOrderInvoice_TBL;

3. ClicktheEXECUTEQUERYbutton .

4. Todeletetheview,typethefollowingprogramminglinesandthen

clicktheEXECUTEQUERYbutton .DROPVIEWOrderInv_VW;

Page 139: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

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.

Page 140: SQL: Easy SQL Programming & Database Management For Beginners, Your Step-By-Step Guide To Learning The SQL Database

FinalWords

IhopethatyouhavetrulyenjoyedlearningtheessentialsofSQLprogramminganddatabasemanagementusingSQLiteStudiothroughthiseBook.IhadmadesurethatyouwilltremendouslybenefitfromreadingthisbymeetingyourgoalsinunderstandingwhatSQLdatabaseisatanaffordableprice.IamsurethatwiththeknowledgeyouhavegainedthroughtheguidelinesofthiseBook,youcannowplan,designandcreateyourveryowndatabasesinSQLiteStudio.

Youmayalsoconsiderlearningotherprogramminglanguages,yourknowledgeofSQLProgrammingwillgiveyouatremendousadvantageifyouwishtolearnotherlanguages.YoucanfindotherpopularprogrammingbooksHERE.

Bytheway,Iwouldgreatlyappreciateifyoucanprovideanyconstructivefeedbackorreviewsthatwillfurtherimprovemyskillsasawriter.Pleasefeelfreetosendmeanemail,especiallyifyouhaveanythingtoclarifyorask(evenifyoujustwanttodropbyandsayhello!)[email protected].

Again,thankyouandGodblessalways!

FelixAlvaro