SQL Functions

SQL Functions

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 condition(scondition(s)) ORDERORDER 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”

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    55 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us