SQLSQL BasicsBasics PartPart IIII
JonathanJonathan MillerMiller LearningLearning SQLSQL SeriesSeries
1 ItemsItems ToTo bebe CoveredCovered
Review of SQL Basics I Join Types Inner & Outer Joins Self-Joins Working With Multiple Queries UNION, INTERSECT, MINUS Subqueries & Correlated Subqueries EXISTS & NOT EXISTS Functions Group String Date Number Participants Questions & Answers (hopefully!)
2 ReviewReview ofof SQLSQL BasicsBasics II
StructureStructure ofof aa SQLSQL StatementStatement SELECTSELECT column(scolumn(s FROMFROM table(stable(s )) WHEREWHERE )) ORDERORDERcondition(s condition(s BYBY column(scolumn(s)) )) OptionalOptional ElementsElements
3 CartesianCartesian // SimpleSimple JoinJoin SELECT mo_id, poc, parameter_desc FROM monitors, parameters
MONITORS PARAMETERS
MO_ID SI_SI_ID PA_PARAMETER_CODE POC
Parameter_Code Parameter_Desc 1 1 44201 1
44201 Ozone 2 1 42101 1 3 1 42101 2 42101 CO 4 2 81102 1
42401 SO2 5 2 44201 1
81102 PM10 6 3 42401 1 4 PrimaryPrimary && ForeignForeign KeysKeys
PrimaryPrimary KeyKey (s)(s) ColumnsColumns onon aa TableTable thatthat UniquelyUniquely IdentifyIdentify aa RecordRecord onon thethe TableTable CanCan bebe composedcomposed ofof 11 oror moremore columnscolumns ForeignForeign KeyKey (s)(s) ColumnColumn onon aa tabletable thatthat referencesreferences thethe PrimaryPrimary KeyKey ofof anotheranother TableTable CanCan bebe composedcomposed ofof oneone oror moremore columnscolumns
5 InnerInner JoinJoin BetweenBetween 22 TablesTables SELECT mo_id, poc, parameter_desc FROM monitors, parameters WHERE pa_parameter_code = parameter_code
MONITORS PARAMETERS
MO_ID SI_SI_ID PA_PARAMETER_CODE POC
Parameter_Code Parameter_Desc 1 1 44201 1
44201 Ozone 2 1 42101 1 3 1 42101 2 42101 CO 4 2 81102 1
42401 SO2 5 2 44201 1
81102 PM10 6 3 424016 1 JoiningJoining TablesTables TogetherTogether
JoinsJoins BetweenBetween TablesTables areare UsuallyUsually BasedBased onon PrimaryPrimary // ForeignForeign KeysKeys MakeMake SureSure JoinsJoins BetweenBetween AllAll TablesTables inin thethe FROMFROM ClauseClause ExistExist ListList JoinsJoins BetweenBetween TablesTables BeforeBefore OtherOther SelectionSelection ElementsElements
7 AliasesAliases
““ShorthandShorthand”” forfor TableTable oror ColumnColumn ReferencesReferences SELECTSELECT AliasesAliases AppearAppear asas ColumnColumn HeadersHeaders inin thethe OutputOutput AliasesAliases CannotCannot bebe KeywordsKeywords (SELECT,(SELECT, FROM,FROM, WHERE,WHERE, etc)etc)
8 JoinJoin TypesTypes andand PuttingPutting MultipleMultiple SQLSQL SelectSelect StatementsStatements TogetherTogether
QUALIFIER_ SITES RAW_DATA DETAILS
MONITOR_ MONITORS PROTOCOLS
9 JoinJoin TypesTypes
SimpleSimple Join:Join: No links made between multiple tables RESULT: Cartesian Product InnerInner JoinJoin TABLE1.Foreign Key = TABLE2.Primary Key RESULT: 1 record for each match between the 2 tables OuterOuter JoinJoin TABLE1.Foreign Key = TABLE2.Primary Key(+) RESULT: 1 record for each match between the 2 tables AND 1 record for each where the record only exists in TABLE1
10 jm1
OuterOuter JoinsJoins
PlacePlace aa ““(+)(+)”” NextNext toto thethe ColumnColumn NameName inin thethe WHEREWHERE clauseclause ofof thethe SHORTER tabletable WhereWhere toto Use:Use: WhenWhen youyou havehave nullnull valuesvalues inin aa columncolumn thatthat youyou areare joiningjoining onon WhenWhen aa parentparent recordrecord maymay notnot havehave aa childchild recordrecord AA TableTable CanCan OnlyOnly BeBe OuterOuter JoinedJoined toto OneOne OtherOther TableTable withinwithin aa GivenGiven QueryQuery
11 OuterOuter JoinJoin ExamplesExamples
12 SelfSelf JoinsJoins
Parent Record A
Parent Record B
Parent Record C
Parent Record D
13 WhatWhat isis ItIt
SpecialSpecial CaseCase ofof anan InnerInner JoinJoin UseUse WhenWhen YouYou needneed ““RowsRows”” ofof aa ChildChild RecordRecord toto AppearAppear asas ““ColumnsColumns”” SpecifySpecify thethe SameSame TableTable MultipleMultiple TimesTimes inin thethe ““FROMFROM”” ClauseClause GiveGive EachEach InstanceInstance anan AliasAlias InIn thethe ““WHEREWHERE”” Clause,Clause, SpecifySpecify thethe SpecificSpecific ValueValue DesiredDesired
14 SelfSelf JoinJoin ExampleExample
15 Union,Union, Intersection,Intersection, MinusMinus
A B C
16 WhatWhat DoesDoes itit Do?Do?
ProcessesProcesses thethe ResultsResults ofof SeparateSeparate QueriesQueries IntoInto aa SingleSingle ReturnReturn UNIONUNION:: EverythingEverything fromfrom QueryQuery 11 ++ EverythingEverything fromfrom QueryQuery 22 INTERSECTION:INTERSECTION: OnlyOnly recordsrecords wherewhere thethe resultsresults betweenbetween QueryQuery 11 andand QueryQuery 22 areare thethe samesame MINUS:MINUS: EverythingEverything fromfrom QueryQuery 11 –– MatchingMatching RecordsRecords fromfrom QueryQuery 22
17 WhatWhat WouldWould bebe Returned?Returned?
132 A 5 B 4 6
QUESTION: C ANSWER: 1. A UNION B 7 1, 2, 3, 4, 5, 6 2. A MINUS B 1, 4 3. A INTERSECT (B MINUS C) 2
4. C UNION (B INTERSECT A) 2, 4, 5, 6,18 7 RulesRules forfor TheseThese QueriesQueries
EachEach QueryQuery MustMust ContainContain thethe samesame NumberNumber ofof andand TypeType ofof DataData ElementsElements Select arithmetic_mean From Annual_Summaries Union Select max_value From Summary_Maximums OnlyOnly UniqueUnique OccurrencesOccurrences ofof thethe RecordsRecords willwill bebe RetunedRetuned UnlessUnless youyou SpecifySpecify thethe ““ALLALL”” KeywordKeyword SELECT ALL arithmetic_mean FROM Annual_Summaries Union SELECT max_value FROM Summary_Maximums IfIf youyou wantwant thethe DataData Sorted,Sorted, MustMust bebe ReferencedReferenced byby ColumnColumn PositionPosition
19 UNION,UNION, INTERSECT,INTERSECT, MINUSMINUS ExamplesExamples
20 SubqueriesSubqueries && CorrelatedCorrelated SubqueriesSubqueries
21 SubqueriesSubqueries
AA SubquerySubquery isis SimplySimply aa QueryQuery WithinWithin AnotherAnother QueryQuery Used as a Filtering Mechanism Additional Queries Appear in the WHERE Clause Can be Nested up to 16 Levels AA CorrelatedCorrelated SubquerySubquery isis aa SubquerySubquery WhenWhen thethe 22nd QueryQuery ReferencesReferences aa columncolumn FromFrom thethe PrimaryPrimary QueryQuery
22 SubquerySubquery ExamplesExamples
23 ExistsExists AndAnd NOTNOT EXISTSEXISTS
24 EXISTSEXISTS andand NOTNOT EXISTSEXISTS
SpecialSpecial SubquerySubquery UsedUsed inin thethe WHEREWHERE ClauseClause LooksLooks forfor thethe ExistenceExistence ofof ANYANY RecordRecord inin thethe SubquerySubquery CanCan bebe MuchMuch FasterFaster thanthan UsingUsing anan ““ININ”” ClauseClause SinceSince itit OnlyOnly NeedsNeeds toto FindFind 11 RecordRecord toto SatisfySatisfy thethe ConditionCondition
25 EXISTSEXISTS andand NOTNOT EXISTSEXISTS ExampleExample
26 FunctionsFunctions
27 WhatWhat isis aa Function?Function?
StoredStored SoftwareSoftware thatthat ManipulatesManipulates SubmittedSubmitted ElementsElements andand ReturnsReturns SomeSome ValueValue MayMay byby aa SQLSQL StandardStandard FunctionFunction (SUBSTR)(SUBSTR) CouldCould bebe ApplicationApplication SpecificSpecific (GET_METHOD)(GET_METHOD) GenerallyGenerally TwoTwo CategoriesCategories CreationCreation ofof NewNew ObjectsObjects FromFrom OldOld OnesOnes DescriptionsDescriptions ofof ObjectsObjects
28 FunctionFunction NotationNotation
FUNCTION(parameterFUNCTION(parameter {{datatypedatatype},}, [optional[optional parameters])parameters]) DatatypesDatatypes VARCHAR2VARCHAR2 ((‘‘AppleApple’’,, ‘‘SampleSample TextText **’’,, ‘‘12341234’’)) NUMBERNUMBER (1,(1, 1.03,1.03, --15)15) DATEDATE –– WeWe’’llll talktalk aboutabout thisthis oneone laterlater……
29 TypesTypes ofof FunctionsFunctions
StringString FunctionsFunctions MathematicalMathematical FunctionsFunctions SingleSingle--ValueValue FunctionsFunctions GroupGroup--ValueValue FunctionsFunctions ListList FunctionsFunctions ConversionConversion // TransformationTransformation FunctionsFunctions DateDate FunctionsFunctions
30 WhereWhere CanCan II UseUse Functions?Functions?
SELECTSELECT StatementStatement SELECTSELECT INITCAP(agency_descINITCAP(agency_desc)) FROMFROM agenciesagencies WHEREWHERE StatementStatement SELECT * FROM sites WHERE SUBSTR(lut_land_use_type, 1) = ‘MOBILE’
31 DUALDUAL TableTable
RealReal OracleOracle TableTable WithWith aa SingleSingle RowRow UsedUsed WhenWhen AllAll ElementsElements inin thethe SELECTSELECT andand WHEREWHERE ClausesClauses dodo notnot ReferenceReference AnyAny TablesTables
SELECTSELECT ‘‘AA’’ FROMFROM DUALDUAL Result:Result: ““AA””
32 CommonCommon StringString FunctionsFunctions
|||| INITCAP(StringINITCAP(String)) INSTR(StringINSTR(String,, setset [,[, startstart [,[, occurrence]occurrence] ])]) LENGTH(StringLENGTH(String)) LOWER(StringLOWER(String)) // UPPER(StringUPPER(String)) LPAD(String, Length [, ‘set’]) / RPAD(String, Length [, ‘set’]) LTRIM(StringLTRIM(String [,[, ‘‘setset’’])]) // RTRIM(StringRTRIM(String [,[, ‘‘setset’’])]) SUBSTR(StringSUBSTR(String,, StartStart [,count])[,count])
33 ConcatenateConcatenate (||)(||)
GluesGlues twotwo StringsStrings TogetherTogether
SELECTSELECT ‘‘GoGo’’ |||| ‘‘ WOLFPACKWOLFPACK’’ FROMFROM DUALDUAL
Results:Results:““GoGo WOLFPACKWOLFPACK””
34 INITCAP,INITCAP, UPPER,UPPER, LOWERLOWER
Deals with the Capitalization of Strings INITCAP – Capitalizes first letter of a string as well as after spaces, periods. Lower case for all other letters UPPER – All Upper Case LOWER – All Lower Case
SELECT INITCAP(‘gO woLFpack’), UPPER (‘gO woLFpack’), LOWER(‘gO woLFpack’) FROM dual
RESULTS: “Go Wolfpack”, “GO WOLFPACK”, “go wolfpack”
35 ““InIn StringString”” -- INSTRINSTR
Finds the Position of a String Within a String
SELECT INSTR(‘Go Wolfpack’, ‘ac’) FROM dual Results: 9
Optionally can tell it Where to Start and What Occurrence to Find
SELECT INSTR(‘Go Wolfpack’, ‘o’, 1, 2) FROM dual Results: 5
36 LENGTHLENGTH
TellsTells youyou HowHow LongLong aa StringString IsIs (Spaces(Spaces Count)Count)
SELECTSELECT LENGTH(LENGTH(‘‘GoGo WolfpackWolfpack’’)) FROMFROM dualdual Result:Result: 1111
37 LPADLPAD // RPADRPAD
“Pads” Out a String To a Given Length Defaults to Pad with a Space You May Optionally Specify What Character to Use
SELECT LPAD(‘Carrot’,10) FROM dual Result: “ Carrot”
SELECT RPAD(‘Carrot’,10, ‘x’) FROM dual Result: “Carrotxxxx”
38 LTRIMLTRIM // RTRIMRTRIM
Trims off a Set of Characters from Either the Left (LTRIM) or Right (RTRIM) of a String Keeps Trimming Until No More of the SET of Characters are Found
SELECT RTRIM(‘Go Wolfpack’, ‘k’) FROM DUAL Results: “Go Wolfpac”
SELECT LTRIM(‘Go Wolfpack’, ‘oGfW’) FROM dual Results: “lfpack”
39 SubstringSubstring -- SUBSTRSUBSTR
Clips out a Portion of a String May Tell it How Many Characters to Clip (Default is to clip to end of the string)
SELECT SUBSTR(‘Go Wolfpack’, 7) FROM dual Results: “pack”
SELECT SUBSTR(‘Go Wolfpack’, 7,3) FROM dual Results: “pac”
40 MathematicMathematic FunctionsFunctions
ABSABS –– AbsoluteAbsolute ValueValue SQRTSQRT –– SquareSquare RootRoot CEILCEIL // FLOORFLOOR –– TRUNCTRUNC –– TruncateTruncate SmallestSmallest IntegerInteger ListList FunctionsFunctions AboveAbove // BelowBelow ValueValue GREATEST (List) MODMOD –– ModulusModulus LEAST (List) POWERPOWER GroupGroup FunctionsFunctions ROUNDROUND AVG, COUNT, MAX, MIN, STDDV, SUM, VARIANCE
41 GroupGroup FunctionsFunctions By Size 7 11 4 2 1 1 Total Count By Color 1 3 5 3 24 By Color & Size
42 GroupGroup FunctionsFunctions ExampleExample
WhenWhen youyou useuse thethe GROUPGROUP functions,functions, youyou mustmust specifyspecify thethe breakingbreaking elementselements inin aa GROUPGROUP BYBY clauseclause TheseThese mustmust includeinclude allall nonnon--groupgroup functionfunction itemsitems inin youryour SELECTSELECT statementstatement SelectSelect thethe maximummaximum arithmeticarithmetic meanmean perper yearyear
SELECT annual_summary_year, MAX(annual_arithmetic_mean) FROM annual_summaries GROUP BY annual_summary_year
43 TransformationTransformation FunctionsFunctions
NVLNVL –– NullNull ValueValue FunctionFunction Default value to return if the column value is NULL DECODEDECODE –– SQLSQL versionversion ofof anan ““IFIF”” StatementStatement TypeType ConversionsConversions TO_DATE – Convert a String to a Date TO_NUMBER – Convert a String to a Number TO_CHAR – Convert a Date or Number to a String
44 NVLNVL && DECODEDECODE ExampleExample
HowHow dodo youyou selectselect aa TribalTribal SiteSite ID?ID? IFIF aa TribalTribal CodeCode existsexists forfor aa site,site, UseUse ““TTTT”” forfor thethe statestate code,code, thethe TribalTribal CodeCode forfor thethe countycounty andand thethe sitesite id.id. OtherwiseOtherwise useuse thethe StateState Code,Code, CountyCounty CodeCode andand SiteSite IDID
SELECT DECODE(ta_tribal_code, NULL, cn_stt_state_code, ‘TT’) || ‘-’ || NVL(ta_tribal_code, cc_cn_county_code) || ‘-’ || site_id “AIRS Site ID” FROM sites 45 OracleOracle DatesDates
DatesDates storedstored inin OracleOracle asas aa numbernumber January 1, 4712 BC – December 31, 4712 AD Use the TO_CHAR function to display the way you want it System default is usually DD-MON-YY Format Dates are stored down to the second ““SYSDATESYSDATE”” == RightRight nownow (down(down toto thethe second)second)
46 DateDate ComparisonsComparisons
IfIf youyou comparecompare twotwo datedate values,values, thethe valuesvalues mustmust matchmatch downdown toto thethe secondsecond TO_DATE(TO_DATE(‘‘2004111620041116’’,, ‘‘YYYYMMDDYYYYMMDD’’)) == sysdatesysdate isis notnot aa truetrue statement.statement. YouYou cancan performperform anyany arithmeticarithmetic comparisoncomparison betweenbetween 22 datesdates >> ,, << ,, =,=, !=,!=, BETWEENBETWEEN
47 DateDate FunctionsFunctions
YouYou cancan convertconvert aa stringstring toto aa datedate (TO_DATE)(TO_DATE) andand aa datedate toto aa stringstring (TO_CHAR)(TO_CHAR) TO_DATE(‘2004-NOV-02’, ‘YYYY-MON-DD’) TO_CHAR(sysdate, ‘YYYYMMDD’) YouYou cancan truncatetruncate aa datedate (TRUNC)(TRUNC) toto makemake comparisonscomparisons easiereasier TRUNC(SYSDATE) = Midnight of today’s date TRUNC(SYSDATE, ‘YYYY’) = January 1 of the current year TRUNC(SYDATE, ‘MM’) = Day 1 of the current month
48 DateDate ComparisonComparison ExampleExample
SelectSelect thethe MO_IDsMO_IDs,, ReportingReporting AgencyAgency Codes,Codes, andand yearyear forfor monitorsmonitors thatthat reportedreported datadata
SELECT ans.mo_mo_id, ar.sa_ag_agency_code, ans.annual_summary_year year FROM annual_summaries ans, agency_roles ar WHERE ans.mo_mo_id = ar.mo_mo_id AND ar.rol_role = ‘REPORTING’ AND TO_DATE(ans.annual_summary_year|| ‘0101’, ‘YYYYMMDD’) BETWEEN TRUNC(ar.agency_role_begin_date, ‘YYYY’) AND NVL(ar.agency_role_end_date, sysdate)
49 DateDate ArithmeticArithmetic
IfIf youyou subtractsubtract oneone datedate fromfrom anotheranother youyou getget thethe numbernumber ofof daysdays betweenbetween thethe twotwo datesdates IfIf youyou addadd oror subtractsubtract aa numbernumber toto aa datedate youyou getget aa datedate thatthat manymany daysdays inin thethe futurefuture (+)(+) oror pastpast ((--))
50 MoreMore DateDate FunctionsFunctions
ADD_MONTHSADD_MONTHS –– MoveMove aa datedate xx monthsmonths intointo thethe futurefuture LAST_DAYLAST_DAY –– ReturnsReturns thethe datedate thatthat isis thethe lastlast dayday ofof thethe monthmonth forfor thethe suppliedsupplied monthmonth MONTHS_BETWEENMONTHS_BETWEEN –– NumberNumber ofof monthsmonths betweenbetween 22 datesdates ROUNDROUND –– LikeLike TRUNC,TRUNC, butbut willwill givegive youyou thethe higherhigher formattedformatted valuevalue ifif moremore thanthan ½½ ofof thethe periodperiod hashas expiredexpired
51 DateDate ArithmeticArithmetic && FunctionFunction ExampleExample
Select the time right now (Hour, minute, second), the number of days since the first of the year, the number of days until the end of the year, the number of days until the end of the month, number of hours left in the day
SELECT TO_CHAR(sysdate, ‘HH24:MI:SS’) right_now, TRUNC(sysdate) – TRUNC(sysdate, ‘YYYY’) first_of_year, TRUNC(ADD_MONTHS(sysdate,12), ‘YYYY’) – TRUNC(sysdate) end_of_year, TRUNC(ADD_MONTHS(sysdate,1), ‘MON’) – TRUNC(sysdate) end_of_month, ROUND((TRUNC(sysdate+1) – sysdate) * 24) FROM DUAL
52 SummarySummary
FunctionsFunctions areare prepre--writtenwritten programsprograms thatthat maymay taketake variablesvariables andand returnsreturns aa valuevalue OracleOracle hashas severalseveral builtbuilt--inin functionsfunctions StringString MathMath DateDate TranslationTranslation FunctionsFunctions cancan bebe usedused inin combinationcombination
53 SummarySummary (Continued)(Continued)
AA functionfunction maymay havehave multiplemultiple meaningsmeanings basedbased onon thethe typetype ofof informationinformation providedprovided (TRUNC(TRUNC forfor example)example) OracleOracle DatesDates BeBe carefulcareful youyou knowknow whatwhat timetime youyou havehave DateDate arithmeticarithmetic DateDate functionsfunctions
54 AnyAny Questions?Questions?
55