computer hacking: the ultimate guide to learn computer ... · protect, break in to or save ... this...

67

Upload: buiquynh

Post on 09-Jul-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

ComputerHackingTheUltimateGuidetoLearnComputerHackingandSQL(computerprogramming,hacking,

hackingexposed,hackingthesystem,databaseprogramming)

ComputerHacking

TheEssentialHackingGuideforBeginners

MATTBENTON

ContentsIntroduction–WhatisHacking?

Chapter1–HackingandtheInfluenceofCyberpunk

Chapter2–TheDifferentTypesofHackers

Chapter3–ComputerSecurity

Chapter4–HackingTechniques

Conclusion

Introduction–WhatisHacking?

Hackingistheactofgainingunauthorizedaccesstoacomputersystem,andcanincludeviewingorcopyingdata,orevencreatingnewdata.Oftenhackingisunderstoodtobeawayofmaliciouslydisruptingacomputersystem,copyinginformation,orleavingbehindavirusthatdestroysdata.

Therearemanydifferentreasonswhyhackingtakesplace,andthesereasonsrangefromwantingtodisruptasystemduetoideology(sohackingasameansofprotesting);wantingtogainprofitforexampleinordertocommitcreditcardfraud;orsimplyhackingforthesakeofenjoymentandamusement.

Thereissomecontroversyaboutthedefinitionoftheword‘hacker’becausethosethattrytopreventsuchbreaches insecurity fromtakingplace,orseek to recover lost files,canalsobeknownashackers.Thus,somepeoplebelievethatthecorrecttermformalicioussystemsecuritybreachesisinfact‘cracking’andthat‘hacking’isthecorrectwordtouseforthosewhofightagainstsuchmaliciousexploitationofcomputerweaknesses.

However, in the popular imagination and in general conversation, theword ‘hacker’ ismainlyunderstoodtorefertothe‘bad’methodofbreakingthroughcomputersecurity.Thetwoprocessessharemanycommonskills,asregardlessofmotivation(whethertostealorprotect, break in to or save, computer data) the same understanding of computers isrequired.

Hacking ismore than simply a pastime for thosewho are interested in technology, andmore than simply an illegal activity used for personal gain and with malicious intent,althoughbothofthesemotivationsdomakeupmuchofhackingactivity.Infact,hackingis its own subculture, and members of the community feel very strongly about theirideologies,techniquesandsocialrelationshipsinthecomputerunderworld.

There are many hacking groups and conventions, such as SummerCon, DEF CON,HoHoCon, ShmooCon, BlackHat, ChaosCommunication andHackerHalted, and localhacking communities take their entries into hacking competitions very seriously.Unsurprisinglytherearealsonumerousonlinegroupsandforumsdedicatedtothesubjectof hacking, and there is certainly a strong community spirit felt by those with similarhackingideologies.

Furthermore, hackers are often passionate about literary depictions of the hacking

community,andardentlyreadfictionalCyberpunkandfactualhackermagazines.

Thisbookwillserveasanintroductiontotheworldofhacking,andwillprovideinsightintosomeofthekeyinfluences,ideologies,groups,concepts,andtechniquesofhacking.

Thefirstchapterwillconsiderthebeginningsofhackingandtheinfluenceoftheliterarygenre,Cyberpunk.Thesecondchapterwilllookatthedifferenttypesofhackers,anddrawadistinctionbetweenethicalandunethicalhacking.Thethirdchapterwilllookattheissueofcomputersecurity,whichisvitaltoanunderstandingofhacking.

Thefinalchapterwillprovideanoverviewofthevariousdifferenttechniquesforhacking,includingautomatedandmanualapproachesaswellastheimportanceofthecyberconfidencetrickknownassocialengineering

Chapter1–HackingandtheInfluenceofCyberpunk

MichaelBruceSterling,theAmericansciencefictionauthor,helpedestablishthepopulargenreofCyberpunk.Cyberpunkisasubcategoryofsciencefictionthatfocusesontheroleoftechnologyinafuturesetting.Inthisliteraryandcinematicgenre,lower-classcitizensaredepicted,whohaveaccessto,andagreatunderstandingof,advancedtechnology.

Cyberpunkoftenexplorestheroleoftechnologyduringthebreakdownofsocialorder,inwhichthereisanoppressivegovernmentrestrictinganddamagingthelivesofthegeneralpopulation. Furthermore, artificial intelligence (such as robots or intelligent computers)also plays a significant part inCyberpunk stories, and theEarth is depicted in the nearfuture in a post-industrial dystopia (the opposite of utopia, and therefore a bleakworldcharacterizedbyoppressionandoftensocialunrest.)

The impact of Cyberpunk in the present-day understanding of hacking is considerable.Sciencefictionisparticularlyeffectivewhenwecanrecognizeourownworldwithinthefictional representation,andwithCyberpunkwecan recognizemanyof theconcernsofthe contemporary technological age. Lawrence Person (editor of the science fictionmagazineNovaExpress)describesthetypicalcharactersinCyberpunk:

“Classiccyberpunkcharactersweremarginalized,alienatedlonerswholivedontheedgeof society in generally dystropic futures where daily life was impacted by rapidtechnological change, an ubiquitous data sphere of computerized information, and

invasivemodificationofthehumanbody.”

Toacontemporaryreader,thisdescriptionofCyberpunkcharactersisreminiscentofhowhackers are thought of in the popular imagination, and depicted in books and in films.Therefore,theinterplaybetweenCyberpunkcharactersandhowweviewreal-lifehackersisconsiderable:inmanywaysourunderstandingofwhatahackerislikeisbasedonhowCyberpunkcharactersaredepicted in fiction.Oneexampleof this ishow inCyberpunkthecharactersoftenliveinfilthyconditions,workatnightandsleepallday,anddonothaveanysociallifebeyondchatrooms.

Inthepresent-dayimaginationwhenwethinkofhackerswewilloftenthinkofalonelyadolescent boy sitting in a darkened room behind a computer screen. In fact,MichaelBruceSterling,whowasoneofthefirstscience-fictionwriterswhodealtwithCyberpunk,hasalsoshownthemostinterestinunderstandingthedevelopmentofhacking.

Sterlinghas traced theemergenceofhacking,and theassociatedundergroundcomputernetwork, to the Yippies, a counterculture group who were active in the 1960s andpublished Technological Assistance Program, a newsletter that taught its readershiptechniquesforunauthorizedaccesstotelephones,knownasphreaking.

Manyoftheindividualswhowereinvolvedinthephreakingcommunityarealsoanactivepartoftheundergroundhackingcommunity,suggestingthattherelationshipbetweenthetwogroups.

Chapter2–TheDifferentTypesofHackers

The computer hacking underground contains variousdifferent subcategories of hackers. This is mainly due toconflicting ideologies, whereby certain groups callsthemselvesbyaspecificname,orcallothersaspecificname,in order to emphasize that they do not agree with theideologiesofothers.

The generic word ‘hacker’ therefore, although referring tothose who have technical knowledge and are able to gainunauthorizedaccesstocomputersystems,israthervagueanddoes not distinguish between those who use differentmethodsorbelievecertainthings.

Instead, separate names have emerged in order to distinguish between groups, and toindicate thatnotallhackers follow thesamerulesor ideologies.Oneway inwhich this

canbeseen,asdiscussedpreviously, is thedistinctionbetweenhackersandcrackers,asadvocatedbyEricS.RaymondinTheNewHacker’sDictionary.

InthisbookRaymondcompiledaglossaryofhackers’computerprogrammingjargon,butthose from thehackingcommunity feel that thisbook is toobiasedbyRaymond’sownviewofhackingasamaliciouspractice.

Rather than following the dichotomy of hacker/cracker that Raymond suggested, thegeneralhackingcommunity feels that this is too reductiveand insteadadvocateawiderlist of name to reflect the spectrum of beliefs and practices of the large hackingcommunity.

One subcategory of hackers is known as ‘white hat hackers’ and they break throughcomputersecuritywithoutamaliciousmotivation.Examplesofwhy thismightbedoneincludedoingsototestone’sownsecurityeffectiveness,orwhendoingworkdevelopingcomputersecuritysoftware.

These breaches of security can occur whilstperforming vulnerability assessments of computersoftware as part of a contractual agreement, and isthereforelegal.Inthisway,theslangterm‘whitehat’referencesanethicalhackerwhodoessoforpositivereasons,inordertoprotectratherthandestroy.Thereare recognized organizations, such as TheInternational Council of Electronic CommerceConsultants,whoprovidetrainingandcertificatesfor

thisareaofethicalhacking.

On the other hand, there are ‘blackhat hackers’whobreach computer security systemssimply to be malicious, or to gain profit. These hackers are the ones who are alsosometimesreferredtoascrackers.Thissubcategoryformtheclichéhackerswhoareoftendepictedinfilmsandtelevision,andrepresenttheelusiveandlittle-understoodcomputercriminalwhothepublicfears.

These types of hackers violate computer security in order to destroy, change or stealinformation,or topreventauthorizedusersfrombeingable toaccess thesystem.In thisway they can cause disruption, waste time, and cause distress, but they can also stealsignificantamountsofmoneyoraccessconfidentialinformation.

Generally a black hat hacker will spend time looking for and discovering faults inprograms, orweaknesses in computer systems, but rather than alert the public to theseproblemstheyexploitthemforpersonalgainorsimplyforfun.Oncetheyhaveaccessedacomputer system, they can consequentlymake adjustments that prevent somebodywithauthorizedaccessfromusingthesystemandthustheblackhathackersretaincontrol.

Lyingsomewherebetweenthetwo,notquiteawhitehathackerandnotquiteablackhathacker,isthegrayhathacker.ThisissomebodywhowithoutbeingaskedtosearchestheInternet for systems with a weakness or security flaw, and will then notify theadministratorandoffertorectifytheproblemforafee.

Inthiswaytheyarenotasgoodasawhitehathacker(becausetheyaredemandingafee,andtheirserviceswereneverrequested)buttheyarealsonotasbadasablackhathackerbecause theydonotexploit theseweaknesses inorder towreakdisruptionofstealdata.Another way inwhich gray hat hackersmight respond to their discovery of a securityweakness is topublish their findingsonline, so that thegeneralpublichasaccess to theinformation.

Inthiswaytheyarenotperformingmalicioushackingthemselves,buttheyarepublishingthe information, which leaves their subject at risk of a security breach. This type ofhacking is illegal andalso consideredunethical,whetherornot thegrayhathackerhasbreachedsecurityforpersonalgain,becausetheyhavegainedunauthorizedaccesstodataandhaveleftthesystemsusceptibletohackingbymaliciousblathathackergroups.

Aswellasthesethreemainclassificationsforhacking,whichdifferentiatehackersbasedon their motivation and what they do about the information they discover, there arevariousotherspecific typesofhacker.There isasocialhierarchyamongsthackers,whoarerecognizedbasedontheirskill.

The highest of these statuses is the elite hacker,andsometimesformintoelitegroupssuchas the‘Masters of Deception.’ On the other end of thescale is a script kiddie,who is still learning andhas not yet developed their skillswith breachingsecurity systems. A script kiddie uses automatedtool written by others, and is therefore simplyfollowing a code provided by a more skilled,

blackhathacker,andnothavingtoworkitout themselves.Usuallyascriptkiddiedoesnot really have any knowledge or understanding of the complicated underlying

technologicalconcepts,andsimplyfollowsaplanprovidedbyamoreexperiencedhacker.

Evenlessexperiencethanascriptkiddieisaneophyte,whoisacompletelynewhackerwhohasverylittleknowledgeofcomputertechnologiesorthelogicandconceptsbehindhacking.Abluehatreferstosomebodywhoisusedbycomputersecurityconsultingfirmsbutisnotactuallyapartofthecompany;thebluehatisusedtotestasystempriortoitslaunchtodeterminewhetherithassufficientsecurityorwillbesusceptibletohacking.

Ahacktivist(acombinationofthewords‘hacker’and‘activist’)isahackerwhousestheirknowledgeoftechnologyandtheirhackingskillsinordertobroadcastapolitical,socialorreligious message. Hacktivism itself has two subcategories: cyber terrorism (wherewebsites are damaged or services cannot be accessed) and freedom of information(making information available to the public that was previously either undisclosed orstoredinanencryptedformat.)

Groupsofhackersworkingcollectivelycanincludeorganizedcriminalgangs,andcyberwarfare of nation states. The different subcategories of hackers are indicative of thevariousideologies,motivationsandtechniquesthatarepresentinthehackingcommunity.

Chapter3–ComputerSecurity

Beforewecanbegintoexplorethekeyconceptsandtechniquesofhacking,itishelpfultofirstunderstandthebasicsofcomputersecurity.Ashackingistheactofbreakingthroughsecuritymeasuresofcomputersystems,anunderstandingofthesesystemsisvitaltoanyhacker who hopes to penetrate them. Computer security is applied to computers,smartphones, computer networks (public andprivate) and the entire Internet in order toprotectdevices,dataandservices.

Digital equipment is protected from unauthorizedaccessbycomputersecurity,toensurethatdataisnotstolen, changed or deleted and to maintain thesmooth running of systems. In present-day society,where digital culture forever growing, protectingthese systems is extremely important and thus thefield of computer security is forever growing anddeveloping. Part of computer security is protectingthephysicalequipmentfromtheft,whereastheother

part of computer security is information security, to protect the data itself (and this iswherehackingcomesintoplay.)

However, sometimes these two fields overlap because if there is a breach in physicalsecurity (e.g. if a laptop is stolen) then it becomes much easier for the individual tosucceedinabreachofinformationsecurity,sincetheyhavethepieceofequipmentanditisthereforeeasiertoaccessdatathanitisremotely.

Cybersecurityencompassesallsecuritymeasuresinplacetoprotectacomputer’sdata,andincludesprocedures such as awareness training,penetration testing, and the use of passwords toconfirmauthorizationinordertoprotectdatabothwhen it is in transit andwhen it is simplybeingstored.The financial cost of being a victimof acomputersecuritybreachisconsiderableandasa

consequencethereisalucrativemarketforanti-virusandcomputersecurityprotection.

Computer security is a huge field because of our present-day reliance on technology.Almosteveryindustryusescomputerstoagreaterorlesserextent,andthereforetheextentandvarietyofcomputersecuritymeasuresisvast.Therearesomeareas,however,wherecomputer security is particularly important because they are especially vulnerable tobreachesinsecurity.

One of these is the area of financial systems, because hackers can make a profit bystealingdata and consequently accessing funds.Anywebsite that requires somebody toenter their credit card numbers are often targeted because a hacker can immediatelytransfermoneytotheirownaccount,orspendthevictim’smoneyonline.

Evenifthehackerthemselvesdonotdirectlyusetheperson’sbankdetails,theymayalsoselltheinformationillegally,inordertodistancethemselvesfromthecrimeandattempttoavoidbeingcaught.It isnotonlyonlinethataperson’sdatacanbestolen; in-storecardmachinesandcashpointscanalsoberiggedtocollectpersonalinformationandthusgainaccesstofunds.

People are becoming increasingly aware of this risk when doing online shopping orenteringtheircarddetails,andthereforevariousmeasuresarebeingputinplaceincludingusingpasswordsandansweringsecurityquestions.Theaviationindustryisanotherfieldinwhichcomputersecurity isof theupmost importance,because theconsequencesofabreachinsecuritycanrangefromthepublicationofconfidentialinformation,tothelossofexpensiveequipmentandhumanlife.

There are various reasons why the aviation industrymay become subject to a computer security attack,depending on the motivation for the crime. Thesemotivations include sabotage and espionage in themilitary aviation industry, and industrial competitionand terrorism in the commercial aviation industry.Airtraffic control is one of the aviation industries mostvulnerablesystems,becauseanyattackcanbedifficultto trace, and are relatively simple because it only

requiresaspoofmessageontheradio.

Therearethosewhoseektoexploitcomputervulnerabilities(eitherduetothrillseeking,tomakeapolitical/socialstatementorforfinancialgain)andofcourseontheothersidethose who work to uphold computer security again such threats. Somebody withknowledge of technology, and the ability to hack into computer systems, can thereforeeitherbecomeinvolvedintheillegalandunethicalformofhacking(otherwiseknownascracking),orservetheothersidebyidentifyingthreats,improvingsecuritymeasuresandalertingcompaniestothevulnerabilitiesintheirsystems.

Forthosewhoseaimistoprotectcomputersecurity,therearevariouscountermeasurestoguard against damaging hacking, whereby the risk of being vulnerable to a breach ofcomputer security can beminimized or eliminated. These precautions vary in cost andcomplexity,butcaninclude:intrusiondetectionsystems(todetectthreatsandalsoanalyzeattacksafter theevent), theuseofaccountcontrols (passwordsandencryptionofdata);andtheinstallationoffirewalls(providingeitherhardwareorsoftwarepackagefilteringofcertainformsofattack.

Precautionsagainstacomputersystembeingcompromisedbyattackincludemakingstepstopreventattack,ensureanypotentialattacksaredetected,andtheabilitytorespondtoanattacktopreventfurtherdamage.

However,despitetherebeingarangeofcountermeasuresavailable,computersystemsstill

remainvulnerable toattackand it iscertainlynotuncommonforacomputer tohave itssecuritycompromised.Thefirstreasonwhyattemptedsecurityviolationsstilloccuristhatthepoliceareoftenunfamiliarwithcomputertechnologyandasaresultdonothaveeithertheskillortheinclinationtosolvethecrimesandapprehendthecriminalsresponsible.

Furthermore, any investigation of such mattersrequiresasearchwarrantinorderforanofficertoexaminetheentirenetworkandthiscanmaketheprocedure extremely time consuming. Anotherdifficultyinensuringcomputersecurityisthatintheageofglobalization,inwhichinformationcanbesharedthroughouttheworldusingtheinternet,andtechnologycanspreaddataextremelyeasily,

identifyingandapprehendingthoseresponsibleisparticularlydifficult.

The reason for this difficulty is that a hackermight be working from one jurisdiction,whilethesystemtheyarehackingintoisinadifferentjurisdiction.Furthermore,ahackercanusevarioustechniques(suchasatemporarydial-upinternet)inordertoensuretheiranonymity.Thethirdproblemisduetothehighnumberofattacksthatoccur.

Organizations can be subject tomany attacks and therefore are unable to pursue everysecurity threat. A computer userwould benefit from taking precautionarymeasures inordertoensuretheircomputersecurity,asonceabreachofsecurityhasoccurredthereisnotmuchthatcanbedonetorectifyit.

Chapter4–HackingTechniques

There are various techniques that canbeusedbyhackers in order to gainunauthorizedaccesstoacomputersystem,inordertowreakhavoc,stealmoneyordata,ortopreventthesystemfromoperatingas it issupposed to.The threemainmethods thatareused inorder to attack a system that is connected to the Internet are: network enumeration,vulnerabilityanalysisandexploitation.

Anetworkenumeratorisaprogramthatisusedinordertodiscover the usernames and other information fromnetworked computers. The program discovers anyweaknesses in the computer network’s security and thefindings are reported to a hacker who may then use thisinformation in order to access the network and causedamage(eitherbystealingdataorcorruptingthenetwork.)

Ontheotherhand,ethicalhackerscanusethesameprocesssimply to discover anyweaknesses in their system in order to tighten security.Anothermethod used is vulnerability analysis, which identifies any points of vulnerability in asystem; this information can then be used to either attack the system, or to remove theweakness.Vulnerabilityanalysiscanthenleadtoexploitation,wherethehackerusesthevulnerabilityinformationinordertobreachacomputerorsystem’ssecurity.

There are many specific techniques that can be used, but they all employ the mainconcepts and methods described above. The first more specific example of a hackingtechnique is a vulnerability scanner, which is a program used to check a network forsusceptibility to attack. A port scanner can also be used, which identifies avenues ofaccesstoacomputerandcanestablishhowtocircumnavigateafirewall.

As well as these mechanized devices, hackers can also find these vulnerabilities

themselves,whichcanbedonebymanuallysearchingthecodeofthecomputerandthentestingwhethertheyareright.Brute-forceattackisanothermethodbywhichahackercangainunauthorized entry to a computer network, and this involves for exampleguessingpasswords. Password cracking is another hacking technique that uses passwords, butratherthanguessingthepassword,thehackerrecoverspasswordinformationthathasbeenstoredinthecomputer,ortransmitted.

Aspoofingattack(otherwiseknownas phishing) is an enemy program,system or website that poses as atrusted one. By falsifying data thehacker is able to masquerade as atrusted system and thus fool aprogram or user into revealingconfidential information such aspasswords or bank details. Anotherhackingtechniquethatiscommonly

usedisarootkit,whichisaprogramthatmanagestotakeoverthecontrolofanoperatingsystembyemployinghardtodetectmethods.

ATrojanhorseisyetanothertechniquethatisaprogramwhichmanagestofoolsystemsandusers;itworksbyworkinginonewaywhileseemingtobedoingsomethingelse.Byusingthismethodahackerisabletogainunauthorizedaccesstoasystemandcreateanaccesspointsothattheycanre-enterviathatestablishedroutelateron.Acomputervirusisthemostwidelyrecognizedformofhacking,asitisthecomputerthreatthatmostofthepublicisawareof.

Thevirusworksbyself-replicatingandimplantingitselfintodocumentsandcode;whilesomecomputervirusesaremalicioussomearemerelyirritatingorharmless.Acomputerworm is similar in that it is self-replicating, but it is able to enter a computer programwithoutauserinadvertentlylettingitin,anditdoesnotneedtoinsertitselfintopresentprograms.

Finally,akeyloggerisatoolthatrecordseverykeystrokeonagivenmachine,whichcanlaterbeaccessedandviewedbythehacker.Thisisusuallytoenablethehackertoaccessconfidential information that has been typed by the victim. In fact, there are somelegitimate uses for such a technique, for example some companies use a keylogger inordertodetectanydishonestyorfraudcommittedbyanemployee.

Alargeareaofcomputerhacking involvesthe use of social engineering, whereby inorder to circumvent information security aperson is manipulated in order to revealconfidential informationor togrant accessto secure networks.This technique (whichincludesphishing)isusuallyonlypartofa

complexroutineinawiderfraudscheme,butit isalsoadangerousstepbecausehumanbeingsaremorelikelytobewonoverbyaconvincingtricksterthanamachineis.

Socialengineeringreliesonthepsychologicalactofdecision-making,andcanbethoughtofasoneofthemostsignificantvulnerabilitiesinacomputersecuritysystem.Therearemany different ways in which social engineering can be applied in order to gainunauthorized access to a computer system, and this includes criminals posing as ITtechnicianswhopretendthattheyarefixingthecompanycomputerswhilstinfactstealingdata.

Another examplewould be a trickster informing a company that the number of the IThelpdesk has changed, so that when employees phone the number they will willinglydisclosetheiraccountdetailsthinkingthattheyaretalkingtosomebodywhotheycantrustwith the information. These sorts of scenarios come under the category of ‘pretexting’because making up a believable scenario allows the criminal to access the requiredinformationandthisleadsthevictimtodisclosetheinformation.

Other professionals that a hacker involved in socialengineeringcouldposeasincludethepoliceorbankmanager,becausetheseareindividualswhowebelievehavetherighttobe granted any information that they request. Baiting is asubcategoryofsocialengineeringbecause it reliesonhumanpsychology in order to work. Baiting is where a victim’scomputer security is compromised when an infected disk,deviceorUSBstickisused.

An example of baiting would be for the criminal to post aUSBthroughsomebody’sdoorwithatemptingsoundinglabeland simply wait for the curious victim to plug it into their

laptop,atwhichpointmalwarewouldautomaticallyinstallandinfecttheircomputer.Thistechniquemakesthemostofthehumantendencytowardscuriosityandgreed,becauseifalabel promises erotic images,money or gossip then a victimmay find it hard to resisttakingalook.

KevinMitnick, a once computer criminal who later because a security consultant, has

pointedoutthatitismucheasierandquickertotrickapersonintodisclosingconfidentialinformation than it is to crack into the system using luck, brute force or technicalknowledge.ChristopherHadnagyhaswrittenabooktitledSocialEngineering:TheArtofHumanHacking,whichemphasizesthewayinwhichhumansarethemostvulnerablepartofanycomputersystem.

Conclusion

Thisbookhasprovidedanoverviewofsomeofthekeyconceptstodowithhacking.Wehave considered the beginnings of hacking and how it was influenced by the literarytraditionofCyberpunk. It is interesting tonote thatwhatwasoncedepicted in science-fictionasanimaginedactivityinadystopiansocietyhasbecomerealandhasgoneontopose a significant threat to computer security and a central concern of informationtechnologyexperts.

Here we can see the true beginnings of hacking and how what was once a fictionaltheoreticalconcepthasbecomea realitywithasignificant impacton thedigitalculture.Nextwelookedatthedifferenttypesofhackersandnotedthedistinctionbetweenethicalhackers, who perform hacking legally and in order to improve computer security(otherwise known as white hat hackers) and unethical hackers, who use their skillsillegally in order to wreak havoc, disrupt services, and steal information and data(otherwiseknownasblackhathackers.)

Withthisitisinterestingtonotehowtechnicalskillcanbeuseddifferentlydependingonmotivation, and how the hacking community is not united by a clear and consistentideology.Subsequentlywelookedatcomputersecurity inorder tobetterunderstand theconditionswithinwhich hacking takes place. By learning about computer security it ispossible to understand the challenges faced by hackers who come up against securitymeasures,aswellasthechallengesfacedbythoseseekingtomaintainthesecurityoftheircomputersystems.

Anyintroductiontohackingwouldnotbecompletewithoutthisexaminationofcomputersecurity because the value of maintaining computer security is what motivates ethicalhackers, and what unethical hackers are fighting against. Finally we looked at thenumerous different hacking techniques that can be utilized, including both automatedsoftware that finds and exploits vulnerabilities in computer systems, aswell asmanualmethodsforbreakingthroughsecuritymeasuressuchasdiscoveringapasswordthroughtrialanderror.

Inthischapterwealsoconsideredthevastareaofhackingthatissocialengineering,bywhichahacker isable toaccessasecurenetworkby illegallyobtaining the informationneeded.Intoday’sdigitalculturewearebecomingincreasinglyreliantontechnologyforeverythingthatwedo.

As technologyhas improvedour lives havebecomeeasier inmanyways, butwith thisblossomingindustrynewtypesofcriminalshavealsobeencreated.Acriminaldoesnownotevenneedtoleavethehouseinordertostealmoney,butcandososimplybyhackingintotheirvictim’scomputerandaccessingconfidentialdata.

Hackingisnotalwaysillegalthough,andthisbookhasalsolookedatthewaysinwhichthereisanincreasingdemandforcomputerexpertstobecomeethicalhackersinordertofurtherpromoteandprotectcomputersecurity.Thisintroductiontotheworldofhackinghas revealed that hacking is not a simple activity but a huge spectrum of differentbehaviorsthatinvolveawiderangeoftechniquesandmotivations.

Moreover,hackingisshowntobeanactivitythathasastrongsenseofcultaffiliation,inthe sense that hackers strongly feel part of the hacking community. As digital culturecontinuestogrow,itseemsthatbothethicalandunethicalhackingwillbecomemoreandmoreskilledanditsimpactevermoresignificant.

SQL

Beginner’sGuideforCodingSQL(sql,databaseprogramming,computer

programming,howtoprogram,sqlfordummies)

STEPHENHOFFMAN

CONTENTSIntroduction

TypesofDatabases

Chapter1–ACloserLookonRelationalModel

Tables,Columns,andRows

Keys

Chapter2–ExamplesofRelationalModels

Chapter3–SQLStatements

SQLFacts

SQLCommands

NamingValues

CreatingDatainSQL

DataTypes

CHAPTER4–CodinginMySQL

SELECTCommandAnatomy

FROMCommand

LimitingTheResults

Conclusion

IntroductionAdatabaseservesasacontainer.Itisastoragewhereprogrammerscanorganizedatainaconstructivemanner.Keep inmind that there isnoneed to create adatabase if youareonly dealing with few amounts of data. For instance, handling hundreds of Excelspreadsheetsrequireadatabasewhilefivespreadsheetscanbedealtwithevenwithoutadatabase.Inotherwords,organizingathresholdamountofdatainsideadatabasewillsaveyoufromcomplexdatamanagement.

ACloserLookOnDatabase

Organizingalldatainsideadatabaseallowsyoutoeasilyexecutetaskssuchasqueryingthedata,updating thedata, anddeletingpreviousdata.Mostof all, adatabasepreventsconflictsfromhavingmultiplecopiesofdata.

Let us say, for instance, that a company has to manage its overall financial expenses.Basically, there is a specific department to handle this and suchdepartment has severalpeopleinit.Nowifthesepeoplehavetheirowncopiesofthespreadsheets,thenitwillbesomewhat difficult to come up with non-conflicting data considering the possibility ofhumanerrors.

A database, on the other hand, will be able to store and organize the data with higheraccuracyandlesserconflicts.

Anotherexampletohelpyouunderstandwhatadatabaseis,isbylookingatyourphone’scontactlist.Eachcontactisadataandyoursmartphoneservesasthedatabase.Withjustatouchofafewbuttons,youcaneasilygetthecontactyouarelookingfor.Youcaneasilyeditthedetailsofeachcontactaswell.Thisadvancedatamanagementiswaybetterthanlistingeachcontactinapen-and-paperphonedirectory.

TypesofDatabases

Thedifferenttypesofdatabaseareasfollows:

RelationalDatabasesObject-OrientedDatabasesDocument-BasedDatabases

InthiseBook,Iwillmainlyfocusonrelationaldatabases.Nevertheless,Iwillnothesitatetoincludetheothertwotypesifdeemednecessary.

YoumighthavebeenintroducedtosomesortofnewdatabasetypesuchasNoSQL.Theyareconsideredtobeunderthecategoryofthedocument-baseddatabases.Thesedatabasesarenowbecomingpopularandyoumight thinkthat it isbetter tostudytheminsteadoflearningSQL.

Please do not consider the relational databases to be the things of the past. A lot ofdatabasesthatwestillhavetodayusetherelationalmodel.Moreover,SQLisusefulwhenit comes to relational data queries. Besides, the query language of newly popularizeddatabasesisstillsomehowrelatedtoSQLsincetheyweremostlydevelopedafterSQL.

Inotherwords, jumpinginto thenewtypeofdatabaseswithoutunderstandingSQLwillgiveyou tonsofchallengesalong theway.Hence,youhavemade the rightdecisionoflearningSQLfirstbeforemovingforwardtootherdatabaseslikeMongoDB.

Withoutfurtherado,letmenowbringyoutotheworldofSQL.

Chapter1–ACloserLookonRelationalModel

TheStructuredQueryLanguage,orSQL,wasoriginallydesignedforrelationalmodel.Itis the language used to define the relationships between multiple data. It is also thedatabaseprogramminglanguageusedtoquerydatainarelationalschema.

Sowhendidthisallbegan?

The first relational databasewas created in the 60s and the programming in thismodelwereprimarilydefinedbymathematics.Infact,thismodelofdatabasewasbasedonTupleRelationalCalculusandRelationalAlgebra.

Don’tworry,though,thereisnoneedforyoutojumpintoalgebraandcalculustohandlerelationaldatabases.SQLwillmakerelationaldatabaseprogrammingeasier.

Tables,Columns,andRows

Intherelationaldatabase,thedataisstoredinatable.Inthismodel,alltableshavenames.For instance, youmay name a table as “people”while youmay name another table as“sales”.Thesenamesrefertothekindofdatastoredinsidethetable.Inotherwords,thetablewecall“people”containsdataofpeoplewhilethetablewecall“sales”containsdataofsales.

Every table featuresasetofcolumns.Thesecolumnsdefine thedifferentpiecesofdatawithin the table. This what makes the relational model different from other types ofdatabases.Youwill notice that there are some databases that store data altogether. In arelationalmodel,however,alldataisseparatedbycolumnsandeachcolumnhasaname.Eachcolumncanalso restrict thecategoryandsizeofdata thatwillbeadded in it.Forinstance, some columns can only store strings while some columns can only storenumbers.Therestrictionassignedtoeachcolumndependsonthecreatorofthedatabase.

Columns are also categorized by being required and not required. A required columnmeansthateveryrowinthetablemusthaveadatawhichcorrespondstowhatthecolumnrequires.A not required column, on the other hand,means thatwe can assert aNULLvalueforeachrowunderthatcolumn.AsyougothroughSQL,youwillfindthatNULLhasalotusesindatabaseprogramming.

Theprimarypointofusingrowsistohaveretrievabledataandcontainerswhereyoucanstoredata.Whydowestoredata?Simplybecausewewant toget thatdataagainin the

futureandwesimplywantaplaceforittostayforthemeantime.Hence,thecoreideaofadatabase.

Keys

Oneofthevitalelementsofarelationaldatabasearekeys.Wenowknowthatatablehasseveralcolumnsandeachcolumnhasnames.Eachcolumnhasrelatedpropertiesaswell.Oneofthesepropertiesthatwecanassertinacolumnisakey.

Inarelationaldatabase,wealwaysassignaprimarykeyforeachrow.Thisspecialtypeofkey isused touniquelydeterminea specific row.Thismeans that thevalueof thatkeymust remain unique andmust not have any duplicateswithin the table. If, and only if,thereisanothertablewhichcontainsthatkeyinourrelationmodel;then,wemaymergethosetwotablestogether.

When merging two tables, there will always be primary keys that have no duplicates.Uponmerging, youwill notice that therewill be a new column in the tablewith thesekeys.ThesekeysarenowknownastheForeignkeys.Theyserveaslinkstotheprimarykeys of the second table, allowing you to conveniently link rows from two separatedtables.

Asidefromprimarykeysandforeignkeys,wealsohavethenaturalkeys.Naturalkeysareglobal.Thismeansthatyoucannotchangethemsincetheyareusedallovertheglobetoidentifyasingleentity.Publishedbooks,forinstance,alwayshavenaturalkeyswhichweknowasISBN.EachpublishedbookhasitsownuniqueISBNwhichyouneedtouseasprimarykeyswhenhandlingrelationaldatabaseforbooks.Thisisdifferentwhenhandlingdatabaseswith unnatural keys like emails, people,where you need to invent your ownprimarykeysforeachrow.

Let us use a database for people and their contact numbers as an example.We cannotconsiderthenameastheprimarykey.Wecannotconsidertheperson’sphonenumberastheprimarykeyaswell.Thisisbecauseitispossiblethattherearetwoormorepeopleintheglobe thathave the samecontact number, first name,or even last name.Hence,weshouldcreatetheprimarykeyourselves.Thisiswheretheidentitycolumncomesin.

The identity column serves as an auto-incrementing column that continues to generateuniquekeysasweadddatainthetable.Thekeycombinationdoesnotmattersincewhatweonlyneedisauniquekeyforeveryidentityinourdatabase.

Chapter2–ExamplesofRelationalModels

SinceIhavebeenusingthepeople’sdatabase in thepreviouschapter, Iwillnowgivetoyouacontactsdatabaseasaperfectexampleofarelationalmodel.

Asimpledatabaseforcontactstypicallylookslikethis:

FirstName LastName EmailAddress

John Doe [email protected]

Mae Lee [email protected]

In this table,wehave threecolumns thatare lookingforspecificdata.Thefirstcolumnrequests for the first name. The second for the last name and the third for the emailaddressoftheperson.

Our rows, excluding the first row, refers to a single entity. The row for our first entityrefers to thepersonwith thenameJohnDoeandhisemail is johndoe@email.com.TherowforoursecondentityreferstoMaeLeewithanemailaddressofmaelee@email.com.

Thisisanexampleofadatabasewithtwoentitiesdividedbythreecolumns.

LetussaythatJohnDoehastwoemailaddresseswhileMaeLeehasthree.Somepeoplewillendupaddingcolumnstoaddtheadditionaldata.Hence, thetablewillenduplikethis.

FirstName LastName Email1 Email2 Email3

John Doe johndoe@… johndoe2@… NULL

Mae Lee maelee@… maelee2@… maelee3@…

Thereisaproblemhereifweusethiskindofdatabasedesign.First,whatiftheproblemwehaveathandistofindhowmanyemailaddresseachpersonhas?Itisquitedifficult

andcumbersometogettheanswerweneed.Thisisthedisadvantageinusingacolumn-basedatabase.ThesecondproblemisthatwewillendupwithalotofNULLvaluesforthosepeoplethatonlyhaveoneemailaddress.Third,thisdesignisnotpracticalandyoudonotneedtobeadatabasespecialisttorealizethat.

Inordertoaddressthesethreeissues,hereishowwecandoit.

Key FirstName LastName

1 John Doe

2 Mae Lee

The first step is to create a table for the entity first. In this table,we assigned the firstcolumnfortheprimarykeys.Thesecondstepistocreateanothertablewherewecanstorethevaluesforthesepeople’semailaddresses.Thesecondtablewilllooklikethis.

Key Person’sKey EmailAddress

1 1 [email protected]

2 1 [email protected]

3 2 [email protected]

4 2 [email protected]

5 2 [email protected]

Inthistable,youwillseethattherearetwocolumnsforthekeys.Thefirstcolumnrefersto the primary key designated to each email address. The second column refers to theforeignkeysfromourfirsttable.Thisisanexampleofaone-to-manyrelationalmodel.

Inthismodel,weareabletoorganizethedatainthemostpracticalwaypossible.Itisnoweasierforustoansweraqueryonhowmanyemailseachpersonhasaswell.ThismethodisknownasNormalization.

There are differentways to design your database and efficient designs depend onwhatqueriesyouaretryingtoanswer.

Withallthatbeingsaid,youarenowreadytomeetSQL.

Chapter3–SQLStatementsSQL is a specific database language.We use this language to create statements. Thesestatements aremade up of validwords. Some of thewords should be defined by SQLwhilesomeofthewordsshouldbedefinedbyyou.Somewordsyouwillbeassertinginthesestatementsaretablenames,columnnames,andvariablesordatathatisinsideyourtables.

SQLFacts

Beforeweproceed,IwouldliketoshowyousomeimportantfactsaboutSQL.

ThefirstthingyouneedtoknowaboutSQListhatitisreadablesinceitiswrittenintheEnglish language. In other words, it is easier to learn SQL more than any otherprogramminglanguages.

Second is thatyoucandoa lotmoreusingSQL.This is incontrastwithmostpeople’simpressionsthatSQLisonlyusedfordataqueries.Thisiswrong.

Third is that a valid SQL statement should end with a semi-colon (;). Although somepeoplewilltellyouthatitisnolongerneeded,Isuggestaddingitinyourqueriesbecauseit is part of the ANSI standard. Furthermore, it works fine with both old and moderndatabases.Semi-colons allowyou to conveniently assertmultiple statements together inwhatwecallabatch.Thismethodworksevenwithmoderndatabases.

ThefourthisthatSQLisnotcase-sensitive.Youcanputyourvariablesinbothloweranduppercases.Bothwayswillworkoutjustfineinthestructuredquerylanguage.Onegoodway to practice this is to assert SQL-specific keywords in uppercases and user-definedkeywords in lowercases. This will allow you to efficiently and quickly identify thedifferentkeywordswithinastatement.

SQLCommands

It is important to keep in mind that all SQL statements begin with a command. Thecommandistypicallyaverbtosignifywhatthedatabaseneedstodo.OnegoodexampleofacommandusedinSQLstatementsisSELECT.

TheSELECTcommandtellsthedatabasetoselectasetofdata.Asyoucansee,itisanEnglish-basedwordandprettymuchobviousofwhatthesystemwilldo.ThisishowthecommandlookslikewhenusedinanSQLstatement.

SELECTVALUES

FROMTABLENAME;

TheexampleaboveisagenericexampleofanSQLstatementandIwilltalkaboutitpiecebypiecelateron.

Takenotethatthesetofvaluesorvariablesthatyouneedtoassertinastatementdependsuponwhatcommandyouaretryingtoexecute.Allthesevariablescomeinthestatementrightafterthecommand.

NamingValues

AswhatIhavealreadysaid,theSQLstatementismadeupofwordsthatarewithinSQLspecificationanduser-creatednames.Thismeansthatnamingvaluessuchaskeys, tablenames,columns,andetc.aresignificantinSQL.

ThereisnoabsoluteruleinnamingthingsinSQL.Peoplehavetheirownwaystonamevariables, but I suggest you follow the method I use in this book for the sake ofconsistency.HerearetwonamingrulesthatIwillbeimplementinginthisbook:

Alltablenamesmustbeinsingularform.(e.g.person,email,phone,user,etc.)

Columnnamesshouldneverberepeatedinthedatabase.

Therearesomepeoplewhoprefer tousepluralnamesfor their tablenames.This isnotwrong.Nevertheless, I ammorecomfortablewhenusingsingular form tablenames.Asfor the column names, there will always be a time when two or more columns fromseparatedtableshavethesamename.Hence,whatIdoistouniquelynameeachcolumnfor disambiguation purposes. For instance, instead of using ID as the columnname forprimarykeysinboththeusertableandemailtable;Iwouldratherusethenamesuser_IDandemail_IDforeachcolumn.

You should also takenote that names inSQLare scoped.Thismeans that thedatabaseitself must have a name. The tables within the database must have names too. Thecolumns insideevery tablemustbenamedaswell.Whencallingfor the table, itsnamemustbescopedthroughthedatabasenamewiththeuseofperiod(.)toseparatethenames.Hence,thisishowtheyaregoingtolooklikewhenassertedinanSQLstatement:

Database.TableTable.Column

CreatingDatainSQL

Ihavenointentiontoteachyouhowtocreateadatabasefromscratch.Asbeginners,yourtasksshouldonlycirclearoundaddingorupdatingvaluestoanalreadyexistingdatabase.However,IhaveafeelingthatsomeofyoustillhavethateagernesstolearnSQLinordertocreatetheentireapplicationincludingthedatabaseitself.Andso,IwillintroducethatpartofSQL,butjustenoughtohelpyoujumpstart.

TheSQLkeyword tocreateanewdatabase is thestatementCREATEDATABASEandthis falls under ANSI specification. Let us say you want to create a new database forcontactnumbersofpeopleandyouwanttonamethisnewdatabaseasContacts.Hereishowyouaregoingtodoit.

CREATEDATABASEContact;

Inorderforyoutoworkonthatdatabase,youneedtouseitfirst.ThekeywordweneedhereistheUSEDATABASEcommand.Thisishowwearegoingtoexecuteit.

USEDATABASEContact;

IfyouwanttocreateatableinsidetheContactdatabase,thenwhatyouneedtoexecuteistheCREATETABLEcommandandhereisyoudoit.

CREATETABLEContacts.User(…);

Afterthat,youcannowputallcolumnnames,types,anddefinitions.

DataTypes

Datatypesareimportantbecauseitfollowscolumnrestrictions.Eachcolumnhasaruleonwhichtypeofdatayoucanstoreinit.

Herearesomeofthemajordatatypesandtheirshortdescriptions.

DataType Description

CHARACTER

Usedtodefinethenumberofcharactersallowedinthecolumn.Nomore,noless.

CHARACTERVARYING

Usedtodefinethemaximumnumberofcharactersallowedinthecolumn.Canbelessbutnotmorethanthespecificvalue.

BINARY

Usedtodedicatethecolumnforhexadecimaldata.

SMALLINT

Usedtostorenumericaldatarangingfrom-32,768to32,767.

INTEGER

Usedtostorenumericaldatarangingfrom-2,147,483,648to2,147,483,647.

BIGINT

Usedtostorenumericaldatarangingfrom-9,223,372,036,854,775,808to9,223,372,036,854,775,807.

BOOLEAN

UsedtostoreeitherTRUEorFALSEvalues.

DATE

UsedtostoreDAY,MONTH,andYEARinthefollowingformat:YYYY-MM-DD.

TIME

UsedtostoreSECOND,MINUTE,andHOURinthefollowingformat:HH:MM:SS.

TIMESTAMP

UsedtostorebothTIMEandDATE.

There are other data types supported that you can use formore complex numbers, forinstance. There is also specific data type for UNICODE characters against regularcharacters. Now these are just a few of the flavors that you can use in databaseprogramming.

CHAPTER4–CodinginMySQL

IwillteachyouhowtocodeSQLdatabaseusingMySQL.WhyMySQL?Firstisbecauseitisanopen-sourceplatformandyoucangetitforfree.Secondisbecauseitiscompatiblewithallmajoroperatingsystems:Linux,OSX,andWindows.ThirdisbecauseitfeaturesANSImodewhichenforcesANSIspecificationstoyourdatabase.NotallRDMshavethiskindoffeature.

Inthischapter,Iwill teachyouhowtoefficientlyusetheSELECTcommand.Thiswillallowyoutoeffectivelyusethiscommandtocreateinterestingandefficientdataqueries.

SELECTCommandAnatomy

You should have learned by now that we have the SQL keyword SELECTwhich is acommandtogetspecificdatafromourdatabase.AftertheSELECTkeyword,whatshouldfollowisthelistofitemswewanttohavefromourdatabase.Wecallitthe“selectlist”.Ifthe select list only contains variables, then you can simply write the statement in thismanner:

SELECT‘[Variable]’,’[Variable]’;

Most of the time, the select list contains the names of the columns.When it does, it isimportant to define which table can we find these columns. This is where the FROMcommandcomesin.

Forinstance,ourselectlistcontainsUser(columnA)andEmail(columnB)andwecanfind thesecolumns inside the tablenamedasContact. Inorder todefinewhich table tolookfor,weshouldincludetheFROMcommandbydoingthis.

Format:

SELECT [COLUMN_NAME], [COLUMN_NAME] FROM[TABLE_NAME];

Example:

SELECTUser,EmailFROMContact;

But,what if Ihavea lotofcolumnsin the tableandIwant toselect themall,youask?Well,thisiswherethepoweroftheasterisk(*)comesin.Thisisknownasthewildcardsymbol in SQL statement. To select all columns inside a table, you need to execute a

statementinthisformat.

SELECT*FROM[TABLE_NAME];

As you can see, thewildcard symbol comes after the SELECT command.Now this isusefulwhenselectingall thecolumns.Ifyoudonotneedtoselectall thecolumns,thenusingthewildcardsymbolmaybecomedangerousandinefficient.

There are different ways to quickly assert multiple columns in an SQL statementdependingupontheplatformthatyouareusing.Ipersonallyrecommendthatyouavoidusing the wildcard command since the inefficient use of this syntax may also breakapplications.

FROMCommand

Selecting a single table is fairly easy towrite an SQL statement.As you can see frompreviousexamples,itonlyfollowsasimpleformat.

FROM[TABLE_NAME]

InFROMclause,youcanshortenthenameofyourtablebycreatinganaliasforthetablename.Letussaythatyourtablenameis“telecommunication”andyouarelookingforthelistofownernamesthatcanbefoundunder the“owner”columnofour table.Typingitwiththeuseofthegenericformatwillgiveyouthis.

SELECTtelecommunication.ownerFROMtelecommunication;

Whydoweneed to type the tablenamebefore the columnname inour format above?This isbecausewemustqualify thecolumnbyusing the tablename.Furthermore, thiswill save you from name collisions in the future if there will be columnswith similarnames.Isuggestyoumakethisahabit.

Goingbacktothetopic,doingsoistoomuchofinconvenience.WecanshortenthetablenamebyassigninganaliasintheFROMclause.Here’stheformat.

SELECT [TABLE_NAME_ALIAS].[COLUMN_NAME] FROM[TABLE_NAME][TABLE_NAME_ALIAS];

Using theownercolumnand telecommunication table,ournewstatementwill look likethis.

SELECTt.ownerFROMtelecommunicationt;

Asyoucansee,Iassignedtheletter“t”tobethealiasofthetablename.Thisiseasiertowrite thanrepeatingthecompletenameoverandoveragain.Keepinmindthat it isnotnecessarytousethefirstcharacterofyourtablenameasanalias.Youcanassignanyaliastothetablenameanditcanalsobeacombinationofcharacters.Justmakesurethatyouareconsistentwiththealiasyouuse.

LimitingTheResults

WheneveryouexecuteaSELECTquery,thedatabasewillgiveyoualltherowsunderthecolumnyouspecified.Thismeansthatifyourtablehas20,000rows,thenitwillreturn20,000valuestoansweryourstatement.

Therearetwowaystoaddressthisissue.OneistoassertadditionalclauseaftertheFROMclause.TheotherisbyaddingtheDISTINCTqualifierbeforetheselectlist.Thisshowninthisformat.

SELECTDISTINCT[SELECTLIST]FROM[TABLE_NAME];

Thisformatwillonlygiveyoudistinctvaluesinreturninsteadofprovidingyouwithallthe values under the specified column. This is the perfect way to have all the uniquevalues under that column. For example, you have a table for your contacts and someentitieswereassertedinseveralrowsbecausetheyownmultiplephonenumbers.

Relyingonthegenericformatwillgiveyouduplicatedresults.Thisisnotefficientifyouonly want to know who are your contacts, right? Using the DISTINCT qualifier willpreventyoufromreceivingmultiplerowsforthesameentity.

Hereisourtelecommunicationtablewhichhasthecolumnforownersandanothercolumnforthetelecomcompany.

Key Owner Company

1 JeanGrey AT&T

2 LukeSkywalker Comcast

3 MaeLee AT&T

4 StanLee AT&T

Let us say we want to find the list of telecom companies in our database. Using thegeneric format will give us three results for AT&T which is unnecessary. With theDISTINCTqualifier,however,wewillgetonlytworesults–oneforComcastandanotherforAT&Twhichiswhatwereallyneed.

AsidefromDISTINCTqualifier,youcanaddtheWHEREclauseaftertheFROMclauseto limit the results as well. TheWHERE clause serves as a search enginewith higherprecision.Thisisdonebyusingthefollowingformat.

SELECT [SELECT LIST] FROM [TABLE_NAME] WHERE[EXPRESSION];

Togiveyouasimpleexample, letususeanothertableforpeople’sfirstandlastnames.Letusnamethistable“person”.

Key First Last

1 Lee Mortis

2 Mae Lee

3 John Doe

4 Stan Lee

5 Bruce Lee

LetussayimaginethatthisisourdatabaseforourcustomersandwewouldliketoknowhowmanycustomersdowehavethathaveLeeastheirfamilyname.Inordertodothat,weneedtotheexecutetheWHEREclausecommand.

SELECTp.lastFROMpersonpWHEREp.last=‘Lee’;

ThiswilladdressthedatabasetolookspecificallyunderthelastnamecolumnandmerelyfocusonrowswithLeevalueunderthatcolumn.ItwillignoretherowswithnoLeevalueunderthatcolumn.Inotherwords,youwillonlygettherowsofyourcustomersthathaveLeeastheirlastnames.

ThesecretinunderstandingtheWHEREclauseisbytakingnoteofthedifferentoperatorsyou can use for WHERE expressions. These operators are similar to mathematicaloperators.Thismeansthatitiseasytorememberthem.Incontrastwithmathematics,theoperatorsweusehere alsoworks fornon-numericaldata such as the equal (=) signwehaveusedinourWHEREclauseabove.HereisthelistofthesimpleoperatorsthatyoucanusefortheWHEREclause.

Operators Name&Description

= Equalto–givesTRUEvalueifdataonbothsidesareequaltooneanother.

<>

Not equal to – gives TRUE value if data on bothsidesarenotequaltooneanother.

>

Greaterthan–givesTRUEvalueifdataontheleftsideisgreaterthanthedataontherightside.

<

Less than – gives TRUE value if data on the leftsideislessthanthedataontherightside.

>=

Greaterthanorequalto–givesTRUEvalueifthedataontheleftiseithergreaterthanorequaltothedataontheright.

<=

Less than or equal to – gives TRUE value if thedata on the left is either less than or equal to thedataontheright.

ThesearetheoperatorsthatwillgiveyouBooleanvalueswhenhandlingWHEREclausesforyourSQLqueries.

Conclusion

Atthispoint,youarenowfamiliarhowrelationaldatabasesworkandhowefficientSQLinqueryingdatafromdatabasesthatutilizerelationalmodels.

It is important to takenoteofhow todesignate restrictions to columnsandhow to callthemspecificallyusingSELECTstatements.Youhavealso learnedthatSQLstatementscontainbothSQL-definedkeywordsanduser-definedkeywords.Thesekeywordsarenotcase sensitive, but organizing andwriting the statements in a visual-friendlymanner ishighly recommended.Doing sowill notonlygiveyouconveniencewhenviewingyourSQLcodingbut other people aswell.This is a best practice if you areworkingwith ateam.

It is also significant toqualifycolumnnamesusing tablenameswhenwritingSELECTstatements. This will prevent future issues when there are different tables with similarcolumnnames.Youjustlearnedhowtoshortenthetablenamesusinganalias.

Youcanalsospecifydataextractionof theSELECTstatementbyusingclausessuchasFROM.Using theFROMclauseallowsyou tospecifywhich table to lookatwheneveryourSQLstatementlooksforcolumns.Asidefromthat,FROMclausealsoallowsyoutoassignanaliasforthetablename.

YoualsolearnedhowtolimitthenumberofansweredvalueswiththeuseofDISTINCTqualifierandtheWHEREclause.Keepinmindthatyouhavetoavoidusingthewildcardsymbol since it is an inefficientway to extract data from your database. TheWHEREclause,ontheotherhand,isapowerfulcommandthatyouneedtomasterasabeginner.Familiarizethedifferentoperatorsandtrythemoutonanalreadybuiltdatabase.

Iamawarethatthisbookisbasic,butit isenoughtoprepareyouinmovingforwardtoadvancedstudiesinthestructuredquerylanguage.Asabeginner,thereisnoneedforyouto rush immediatelyonhowtocreateyourowndatabase. It is important to learnwhichdatabasemodeldoesSQLfunctionsfirst.Byunderstandingtherelationalmodel,youwilleasilygrasp theconceptofSQL togetherwith thestatements thatyoucandousing thislanguage.

IfyouwanttocontinuelearningaboutSQL,thenIsuggestthatyoutakeadvantageofthebook’ssequelwhereyouwillbeintroducedtodeeperclausesofSELECTstatements.ThesecondpartalsotacklesaboutJOINS,handlingdata,andtablecreation.

Thankyouforreading.Ihopeyouenjoyit.Askyoutoleaveyourhonestfeedback.