Sql basics

743 views

Published on

Published in: Technology
  • Be the first to comment

Sql basics

  1. 1. SQL BasicsSQL BasicsIntroduction toIntroduction toStandard Query LanguageStandard Query Language
  2. 2. SQLSQL –– What Is It?What Is It?Structured Query LanguageStructured Query LanguageCommon Language For Variety ofCommon Language For Variety ofDatabasesDatabasesANSI Standard BUTANSI Standard BUT……..Two Types of SQLTwo Types of SQLDMLDML –– Data Manipulation Language (SELECT)Data Manipulation Language (SELECT)DDLDDL –– Data Definition Language (CREATEData Definition Language (CREATETABLE)TABLE)
  3. 3. Where To UseWhere To UseSQL*PlusSQL*PlusTOADTOADSQL NavigatorSQL NavigatorODBC Supported ConnectionsODBC Supported ConnectionsExcelExcelAccessAccessLotus 1Lotus 1--22--33Heart of PL/SQLHeart of PL/SQL
  4. 4. Pros & Cons of SQLPros & Cons of SQLPros:Pros:Very flexibleVery flexibleUniversal (Oracle, Access, Paradox, etc)Universal (Oracle, Access, Paradox, etc)Relatively Few Commands to LearnRelatively Few Commands to LearnCons:Cons:Requires Detailed Knowledge of the StructureRequires Detailed Knowledge of the Structureof the Databaseof the DatabaseCan Provide Misleading ResultsCan Provide Misleading Results
  5. 5. Basic SQL ComponentsBasic SQL ComponentsSELECTSELECT schema.table.schema.table.columncolumnFROM tableFROM table aliasaliasWHERE [conditions]WHERE [conditions]ORDER BY [columns]ORDER BY [columns];;Defines the end of an SQL statementDefines the end of an SQL statementSome programs require it, some do not (TOAD DoesSome programs require it, some do not (TOAD DoesNot)Not)Needed only if multiple SQL statements run in a scriptNeeded only if multiple SQL statements run in a scriptOptional Elements
  6. 6. SELECT StatementSELECT StatementSELECT Statement Defines WHAT is to beSELECT Statement Defines WHAT is to bereturned (separated by commas)returned (separated by commas)Database Columns (From Tables or Views)Database Columns (From Tables or Views)Constant Text ValuesConstant Text ValuesFormulasFormulasPrePre--defined Functionsdefined FunctionsGroup Functions (COUNT, SUM, MAX, MIN, AVG)Group Functions (COUNT, SUM, MAX, MIN, AVG)““**”” Mean All Columns From All Tables In theMean All Columns From All Tables In theFROM StatementFROM StatementExample: SELECT state_code, state_nameExample: SELECT state_code, state_name
  7. 7. FROM StatementFROM StatementDefines the Table(s) or View(s) Used byDefines the Table(s) or View(s) Used bythe SELECT or WHERE Statementsthe SELECT or WHERE StatementsYou MUST Have a FROM statementYou MUST Have a FROM statementMultiple Tables/Views are separated byMultiple Tables/Views are separated byCommasCommas
  8. 8. ExamplesExamplesSELECT state_name, state_abbrSELECT state_name, state_abbrFROM statesFROM statesSELECT *SELECT *FROM agenciesFROM agenciesSELECTSELECT arithmetic_meanarithmetic_mean –– minimum_valueminimum_valueFROM annual_summariesFROM annual_summaries
  9. 9. WHERE ClauseWHERE ClauseOptionalOptionalDefines what records are to be included in the queryDefines what records are to be included in the queryUses Conditional OperatorsUses Conditional Operators=, >, >=, <, <=, != (<>)=, >, >=, <, <=, != (<>)BETWEEN x AND yBETWEEN x AND yIN (IN (listlist))LIKELIKE ‘‘%string%string’’ ((““%%”” is a wildis a wild--card)card)IS NULLIS NULLNOT {BETWEEN / IN / LIKE / NULL}NOT {BETWEEN / IN / LIKE / NULL}Multiple Conditions Linked with AND & OR StatementsMultiple Conditions Linked with AND & OR StatementsStrings Contained Within SINGLE QUOTES!!Strings Contained Within SINGLE QUOTES!!
  10. 10. AND & ORAND & ORMultiple WHERE conditions are Linked by AND /Multiple WHERE conditions are Linked by AND /OR StatementsOR Statements““ANDAND”” Means All Conditions are TRUE for theMeans All Conditions are TRUE for theRecordRecord““OROR”” Means at least 1 of the Conditions is TRUEMeans at least 1 of the Conditions is TRUEYou May Group Statements with ( )You May Group Statements with ( )BE CAREFUL MIXINGBE CAREFUL MIXING ““ANDAND”” && ““OROR”” ConditionsConditions
  11. 11. Examples with WHEREExamples with WHERESELECT *SELECT *FROM annual_summariesFROM annual_summariesWHERE sd_duration_code =WHERE sd_duration_code = ‘‘11’’SELECT state_nameSELECT state_nameFROM statesFROM statesWHERE state_population > 15000000WHERE state_population > 15000000
  12. 12. More ExamplesMore ExamplesSELECT state_name, state_populationSELECT state_name, state_populationFROM statesFROM statesWHERE state_name LIKEWHERE state_name LIKE ‘‘%NORTH%%NORTH%’’SELECT *SELECT *FROM annual_summariesFROM annual_summariesWHERE sd_duration_code IN (WHERE sd_duration_code IN (‘‘11’’,, ‘‘WW’’,, ‘‘XX’’))AND annual_summary_year = 2000AND annual_summary_year = 2000
  13. 13. Be Careful!Be Careful!SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_codeFROM annual_summariesFROM annual_summariesWHERE annual_summary_year = 2003WHERE annual_summary_year = 2003AND values_gt_pri_std > 0AND values_gt_pri_std > 0OR values_gt_sec_std > 0OR values_gt_sec_std > 0SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_codeFROM annual_summariesFROM annual_summariesWHERE annual_summary_year = 2003WHERE annual_summary_year = 2003AND (values_gt_pri_std > 0AND (values_gt_pri_std > 0OR values_gt_sec_std > 0)OR values_gt_sec_std > 0)
  14. 14. ORDER BY StatementORDER BY StatementDefines How the Records are to be SortedDefines How the Records are to be SortedMust be in the SELECT statement to beMust be in the SELECT statement to beORDER BYORDER BYDefault is to order in ASC (Ascending)Default is to order in ASC (Ascending)orderorderCan Sort in Reverse (Descending) OrderCan Sort in Reverse (Descending) Orderwithwith ““DESCDESC”” After the Column NameAfter the Column Name
  15. 15. ORDER BY ExampleORDER BY ExampleSELECT *SELECT *FROM agenciesFROM agenciesORDER BY agency_descORDER BY agency_descSELECT cc_cn_stt_state_code, site_idSELECT cc_cn_stt_state_code, site_idFROM sitesFROM sitesWHERE lut_land_use_type =WHERE lut_land_use_type = ‘‘MOBILEMOBILE’’ORDER BY cc_cn_stt_state_code DESCORDER BY cc_cn_stt_state_code DESC
  16. 16. Group FunctionsGroup FunctionsPerforms Common MathematicalPerforms Common MathematicalOperations on a Group of RecordsOperations on a Group of RecordsMust define what Constitutes a Group byMust define what Constitutes a Group byUsing the GROUP BY ClauseUsing the GROUP BY ClauseAll nonAll non--Group elements in the SELECTGroup elements in the SELECTStatement Must be in the GROUP BYStatement Must be in the GROUP BYClause (Additional Columns are Optional)Clause (Additional Columns are Optional)
  17. 17. Group By ExampleGroup By ExampleSELECT si_si_id, COUNT(mo_id)SELECT si_si_id, COUNT(mo_id)FROM monitorsFROM monitorsGROUP BY si_si_idGROUP BY si_si_idSELECT AVG(max_sample_value)SELECT AVG(max_sample_value)FROM summary_maximumsFROM summary_maximumsWHERE max_level <= 3WHERE max_level <= 3AND max_ind =AND max_ind = ‘‘REGREG’’GROUP BY ans_ans_idGROUP BY ans_ans_id
  18. 18. OK, I understand How to Get DataOK, I understand How to Get DataFrom 1 TableFrom 1 Table…… What aboutWhat aboutMultiple Tables?Multiple Tables?MONITORSMO_IDSI_SI_IDPA_PARAMETER_CODEPOCV_MONITOR_IDMO_IDAIRS_MONITOR_IDSTATE_CODECOUNTY_CODESITE_IDPARAMETER_CODEPOCPARAMETERSPARAMETER_CODEPARAMETER_DESC
  19. 19. Primary & Foreign KeysPrimary & Foreign KeysPrimary KeysPrimary Keys1 or More Columns Used to Uniquely Identify1 or More Columns Used to Uniquely Identifya record.a record.All Columns Defined as PKAll Columns Defined as PK’’s MUST bes MUST bepopulatedpopulatedForeign KeysForeign KeysValue on a table that references a PrimaryValue on a table that references a PrimaryKey from a different tableKey from a different table
  20. 20. V_MONITOR_IDMO_IDSTATE_CODECOUNTY_CODESITE_IDPARAMETER_CODEPOCPrimary & Foreign KeysPrimary & Foreign KeysMONITORSMO_ID%SI_SI_ID*PA_PARAMETER_CODE*POCPARAMETERSPARAMETER_CODE%PARAMETER_DESC* = Foreign Key% = Primary KeySITESSI_ID%SITE_LATITUDESITE_LONGITUDESTREET_ADDRESS
  21. 21. Joining TablesJoining TablesPARAMETERSParameter_Code Parameter_Desc44201 Ozone42101 CO42401 SO281102 PM10Default behavior is to show every possible combination between the two tables142401361442012518110224242101131421011214420111POCPA_PARAMETER_CODESI_SI_IDMO_IDMONITORS
  22. 22. Cartesian Join / Simple JoinCartesian Join / Simple JoinSELECT mo_id, poc, parameter_descFROM monitors, parametersPARAMETERSParameter_Code Parameter_Desc44201 Ozone42101 CO42401 SO281102 PM10MONITORSMO_ID SI_SI_ID PA_PARAMETER_CODE POC1 1 44201 12 1 42101 13 1 42101 24 2 81102 15 2 44201 16 3 42401 1
  23. 23. Joining TablesJoining TablesPARAMETERSParameter_Code Parameter_Desc44201 Ozone42101 CO42401 SO281102 PM10MONITORSMO_ID SI_SI_ID PA_PARAMETER_CODE POC1 1 44201 12 1 42101 13 1 42101 24 2 81102 15 2 44201 16 3 42401 1SELECT mo_id, poc, parameter_descFROM monitors, parametersWHERE pa_parameter_code = parameter_code
  24. 24. Joining TablesJoining TablesJoins Between Tables are Usually BasedJoins Between Tables are Usually Basedon Primary / Foreign Keyson Primary / Foreign KeysMake Sure Joins Between All Tables in theMake Sure Joins Between All Tables in theFROM Clause ExistFROM Clause ExistList Joins Between Tables Before OtherList Joins Between Tables Before OtherSelection ElementsSelection Elements
  25. 25. AliasesAliases““ShorthandShorthand”” for Table or Columnfor Table or ColumnReferencesReferencesSELECT Aliases Appear as ColumnSELECT Aliases Appear as ColumnHeaders in the OutputHeaders in the OutputAliases Cannot be KeywordsAliases Cannot be Keywords
  26. 26. Previous SQL With AliasesPrevious SQL With AliasesSELECT mo.mo_id, mo.poc, pa.parameter_desc parameterFROM monitors mo, parameters paWHERE mo.pa_parameter_code = pa.parameter_code
  27. 27. Why Use an Alias?Why Use an Alias?Saves TypingSaves TypingGood Internal DocumentationGood Internal DocumentationBetter HeadersBetter HeadersIf the same column name exists onIf the same column name exists onmultiple tables, SQL needs a way to knowmultiple tables, SQL needs a way to knowwhich element you are referencingwhich element you are referencing(MO_MO_ID for example)(MO_MO_ID for example)
  28. 28. RecapRecapBasic Structural ElementsBasic Structural ElementsSELECTSELECTFROMFROMWHEREWHEREORDER BYORDER BYGROUP BYGROUP BYSelecting From Multiple TablesSelecting From Multiple TablesJoin Multiple Tables via Primary & Foreign KeysJoin Multiple Tables via Primary & Foreign KeysAliasesAliases

×