SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
SQL BasicsSQL Basics
Introduction toIntroduction to
Standard Query LanguageStandard Query Language
SQLSQL –– What Is It?What Is It?
Structured Query LanguageStructured Query Language
Common Language For Variety ofCommon Language For Variety of
DatabasesDatabases
ANSI Standard BUTANSI Standard BUT……..
Two Types of SQLTwo Types of SQL
DMLDML –– Data Manipulation Language (SELECT)Data Manipulation Language (SELECT)
DDLDDL –– Data Definition Language (CREATEData Definition Language (CREATE
TABLE)TABLE)
Where To UseWhere To Use
SQL*PlusSQL*Plus
TOADTOAD
SQL NavigatorSQL Navigator
ODBC Supported ConnectionsODBC Supported Connections
ExcelExcel
AccessAccess
Lotus 1Lotus 1--22--33
Heart of PL/SQLHeart of PL/SQL
Pros & Cons of SQLPros & Cons of SQL
Pros:Pros:
Very flexibleVery flexible
Universal (Oracle, Access, Paradox, etc)Universal (Oracle, Access, Paradox, etc)
Relatively Few Commands to LearnRelatively Few Commands to Learn
Cons:Cons:
Requires Detailed Knowledge of the StructureRequires Detailed Knowledge of the Structure
of the Databaseof the Database
Can Provide Misleading ResultsCan Provide Misleading Results
Basic SQL ComponentsBasic SQL Components
SELECTSELECT schema.table.schema.table.columncolumn
FROM tableFROM table aliasalias
WHERE [conditions]WHERE [conditions]
ORDER BY [columns]ORDER BY [columns]
;;
Defines the end of an SQL statementDefines the end of an SQL statement
Some programs require it, some do not (TOAD DoesSome programs require it, some do not (TOAD Does
Not)Not)
Needed only if multiple SQL statements run in a scriptNeeded only if multiple SQL statements run in a script
Optional Elements
SELECT StatementSELECT Statement
SELECT Statement Defines WHAT is to beSELECT Statement Defines WHAT is to be
returned (separated by commas)returned (separated by commas)
Database Columns (From Tables or Views)Database Columns (From Tables or Views)
Constant Text ValuesConstant Text Values
FormulasFormulas
PrePre--defined Functionsdefined Functions
Group 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 the
FROM StatementFROM Statement
Example: SELECT state_code, state_nameExample: SELECT state_code, state_name
FROM StatementFROM Statement
Defines the Table(s) or View(s) Used byDefines the Table(s) or View(s) Used by
the SELECT or WHERE Statementsthe SELECT or WHERE Statements
You MUST Have a FROM statementYou MUST Have a FROM statement
Multiple Tables/Views are separated byMultiple Tables/Views are separated by
CommasCommas
ExamplesExamples
SELECT state_name, state_abbrSELECT state_name, state_abbr
FROM statesFROM states
SELECT *SELECT *
FROM agenciesFROM agencies
SELECTSELECT arithmetic_meanarithmetic_mean –– minimum_valueminimum_value
FROM annual_summariesFROM annual_summaries
WHERE ClauseWHERE Clause
OptionalOptional
Defines what records are to be included in the queryDefines what records are to be included in the query
Uses Conditional OperatorsUses Conditional Operators
=, >, >=, <, <=, != (<>)=, >, >=, <, <=, != (<>)
BETWEEN x AND yBETWEEN x AND y
IN (IN (listlist))
LIKELIKE ‘‘%string%string’’ ((““%%”” is a wildis a wild--card)card)
IS NULLIS NULL
NOT {BETWEEN / IN / LIKE / NULL}NOT {BETWEEN / IN / LIKE / NULL}
Multiple Conditions Linked with AND & OR StatementsMultiple Conditions Linked with AND & OR Statements
Strings Contained Within SINGLE QUOTES!!Strings Contained Within SINGLE QUOTES!!
AND & ORAND & OR
Multiple 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 the
RecordRecord
““OROR”” Means at least 1 of the Conditions is TRUEMeans at least 1 of the Conditions is TRUE
You May Group Statements with ( )You May Group Statements with ( )
BE CAREFUL MIXINGBE CAREFUL MIXING ““ANDAND”” && ““OROR”” ConditionsConditions
Examples with WHEREExamples with WHERE
SELECT *SELECT *
FROM annual_summariesFROM annual_summaries
WHERE sd_duration_code =WHERE sd_duration_code = ‘‘11’’
SELECT state_nameSELECT state_name
FROM statesFROM states
WHERE state_population > 15000000WHERE state_population > 15000000
More ExamplesMore Examples
SELECT state_name, state_populationSELECT state_name, state_population
FROM statesFROM states
WHERE state_name LIKEWHERE state_name LIKE ‘‘%NORTH%%NORTH%’’
SELECT *SELECT *
FROM annual_summariesFROM annual_summaries
WHERE sd_duration_code IN (WHERE sd_duration_code IN (‘‘11’’,, ‘‘WW’’,, ‘‘XX’’))
AND annual_summary_year = 2000AND annual_summary_year = 2000
Be Careful!Be Careful!
SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_code
FROM annual_summariesFROM annual_summaries
WHERE annual_summary_year = 2003WHERE annual_summary_year = 2003
AND values_gt_pri_std > 0AND values_gt_pri_std > 0
OR values_gt_sec_std > 0OR values_gt_sec_std > 0
SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_code
FROM annual_summariesFROM annual_summaries
WHERE annual_summary_year = 2003WHERE annual_summary_year = 2003
AND (values_gt_pri_std > 0AND (values_gt_pri_std > 0
OR values_gt_sec_std > 0)OR values_gt_sec_std > 0)
ORDER BY StatementORDER BY Statement
Defines How the Records are to be SortedDefines How the Records are to be Sorted
Must be in the SELECT statement to beMust be in the SELECT statement to be
ORDER BYORDER BY
Default is to order in ASC (Ascending)Default is to order in ASC (Ascending)
orderorder
Can Sort in Reverse (Descending) OrderCan Sort in Reverse (Descending) Order
withwith ““DESCDESC”” After the Column NameAfter the Column Name
ORDER BY ExampleORDER BY Example
SELECT *SELECT *
FROM agenciesFROM agencies
ORDER BY agency_descORDER BY agency_desc
SELECT cc_cn_stt_state_code, site_idSELECT cc_cn_stt_state_code, site_id
FROM sitesFROM sites
WHERE 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
Group FunctionsGroup Functions
Performs Common MathematicalPerforms Common Mathematical
Operations on a Group of RecordsOperations on a Group of Records
Must define what Constitutes a Group byMust define what Constitutes a Group by
Using the GROUP BY ClauseUsing the GROUP BY Clause
All nonAll non--Group elements in the SELECTGroup elements in the SELECT
Statement Must be in the GROUP BYStatement Must be in the GROUP BY
Clause (Additional Columns are Optional)Clause (Additional Columns are Optional)
Group By ExampleGroup By Example
SELECT si_si_id, COUNT(mo_id)SELECT si_si_id, COUNT(mo_id)
FROM monitorsFROM monitors
GROUP BY si_si_idGROUP BY si_si_id
SELECT AVG(max_sample_value)SELECT AVG(max_sample_value)
FROM summary_maximumsFROM summary_maximums
WHERE max_level <= 3WHERE max_level <= 3
AND max_ind =AND max_ind = ‘‘REGREG’’
GROUP BY ans_ans_idGROUP BY ans_ans_id
OK, I understand How to Get DataOK, I understand How to Get Data
From 1 TableFrom 1 Table…… What aboutWhat about
Multiple Tables?Multiple Tables?
MONITORS
MO_ID
SI_SI_ID
PA_PARAMETER_CODE
POC
V_MONITOR_ID
MO_ID
AIRS_MONITOR_ID
STATE_CODE
COUNTY_CODE
SITE_ID
PARAMETER_CODE
POC
PARAMETERS
PARAMETER_CODE
PARAMETER_DESC
Primary & Foreign KeysPrimary & Foreign Keys
Primary KeysPrimary Keys
1 or More Columns Used to Uniquely Identify1 or More Columns Used to Uniquely Identify
a record.a record.
All Columns Defined as PKAll Columns Defined as PK’’s MUST bes MUST be
populatedpopulated
Foreign KeysForeign Keys
Value on a table that references a PrimaryValue on a table that references a Primary
Key from a different tableKey from a different table
V_MONITOR_ID
MO_ID
STATE_CODE
COUNTY_CODE
SITE_ID
PARAMETER_CODE
POC
Primary & Foreign KeysPrimary & Foreign Keys
MONITORS
MO_ID%
SI_SI_ID*
PA_PARAMETER_CODE*
POC
PARAMETERS
PARAMETER_CODE%
PARAMETER_DESC
* = Foreign Key
% = Primary Key
SITES
SI_ID%
SITE_LATITUDE
SITE_LONGITUDE
STREET_ADDRESS
Joining TablesJoining Tables
PARAMETERS
Parameter_Code Parameter_Desc
44201 Ozone
42101 CO
42401 SO2
81102 PM10
Default behavior is to show every possible combination between the two tables
14240136
14420125
18110224
24210113
14210112
14420111
POCPA_PARAMETER_CODESI_SI_IDMO_ID
MONITORS
Cartesian Join / Simple JoinCartesian Join / Simple Join
SELECT mo_id, poc, parameter_desc
FROM monitors, parameters
PARAMETERS
Parameter_Code Parameter_Desc
44201 Ozone
42101 CO
42401 SO2
81102 PM10
MONITORS
MO_ID SI_SI_ID PA_PARAMETER_CODE POC
1 1 44201 1
2 1 42101 1
3 1 42101 2
4 2 81102 1
5 2 44201 1
6 3 42401 1
Joining TablesJoining Tables
PARAMETERS
Parameter_Code Parameter_Desc
44201 Ozone
42101 CO
42401 SO2
81102 PM10
MONITORS
MO_ID SI_SI_ID PA_PARAMETER_CODE POC
1 1 44201 1
2 1 42101 1
3 1 42101 2
4 2 81102 1
5 2 44201 1
6 3 42401 1
SELECT mo_id, poc, parameter_desc
FROM monitors, parameters
WHERE pa_parameter_code = parameter_code
Joining TablesJoining Tables
Joins Between Tables are Usually BasedJoins Between Tables are Usually Based
on Primary / Foreign Keyson Primary / Foreign Keys
Make Sure Joins Between All Tables in theMake Sure Joins Between All Tables in the
FROM Clause ExistFROM Clause Exist
List Joins Between Tables Before OtherList Joins Between Tables Before Other
Selection ElementsSelection Elements
AliasesAliases
““ShorthandShorthand”” for Table or Columnfor Table or Column
ReferencesReferences
SELECT Aliases Appear as ColumnSELECT Aliases Appear as Column
Headers in the OutputHeaders in the Output
Aliases Cannot be KeywordsAliases Cannot be Keywords
Previous SQL With AliasesPrevious SQL With Aliases
SELECT mo.mo_id, mo.poc, pa.parameter_desc parameter
FROM monitors mo, parameters pa
WHERE mo.pa_parameter_code = pa.parameter_code
Why Use an Alias?Why Use an Alias?
Saves TypingSaves Typing
Good Internal DocumentationGood Internal Documentation
Better HeadersBetter Headers
If the same column name exists onIf the same column name exists on
multiple tables, SQL needs a way to knowmultiple tables, SQL needs a way to know
which element you are referencingwhich element you are referencing
(MO_MO_ID for example)(MO_MO_ID for example)
RecapRecap
Basic Structural ElementsBasic Structural Elements
SELECTSELECT
FROMFROM
WHEREWHERE
ORDER BYORDER BY
GROUP BYGROUP BY
Selecting From Multiple TablesSelecting From Multiple Tables
Join Multiple Tables via Primary & Foreign KeysJoin Multiple Tables via Primary & Foreign Keys
AliasesAliases

Mais conteúdo relacionado

Mais procurados (17)

Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |Thrissur
 
Sql
SqlSql
Sql
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
BIS05 Introduction to SQL
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQL
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
SQL
SQLSQL
SQL
 
Database testing
Database testingDatabase testing
Database testing
 
SQL
SQLSQL
SQL
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
MY SQL
MY SQLMY SQL
MY SQL
 
Chapter 08
Chapter 08Chapter 08
Chapter 08
 
Sql
SqlSql
Sql
 
Sql Tags
Sql TagsSql Tags
Sql Tags
 
Proc sql tips
Proc sql tipsProc sql tips
Proc sql tips
 
Sql commands
Sql commandsSql commands
Sql commands
 

Semelhante a Sql General

Semelhante a Sql General (20)

Sql basics
Sql basicsSql basics
Sql basics
 
Sql basics
Sql basicsSql basics
Sql basics
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
JDBC
JDBCJDBC
JDBC
 
Dbms
DbmsDbms
Dbms
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfSQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdf
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 
How sqlite works
How sqlite worksHow sqlite works
How sqlite works
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 

Último

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Último (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Sql General

  • 1. SQL BasicsSQL Basics Introduction toIntroduction to Standard Query LanguageStandard Query Language
  • 2. SQLSQL –– What Is It?What Is It? Structured Query LanguageStructured Query Language Common Language For Variety ofCommon Language For Variety of DatabasesDatabases ANSI Standard BUTANSI Standard BUT…….. Two Types of SQLTwo Types of SQL DMLDML –– Data Manipulation Language (SELECT)Data Manipulation Language (SELECT) DDLDDL –– Data Definition Language (CREATEData Definition Language (CREATE TABLE)TABLE)
  • 3. Where To UseWhere To Use SQL*PlusSQL*Plus TOADTOAD SQL NavigatorSQL Navigator ODBC Supported ConnectionsODBC Supported Connections ExcelExcel AccessAccess Lotus 1Lotus 1--22--33 Heart of PL/SQLHeart of PL/SQL
  • 4. Pros & Cons of SQLPros & Cons of SQL Pros:Pros: Very flexibleVery flexible Universal (Oracle, Access, Paradox, etc)Universal (Oracle, Access, Paradox, etc) Relatively Few Commands to LearnRelatively Few Commands to Learn Cons:Cons: Requires Detailed Knowledge of the StructureRequires Detailed Knowledge of the Structure of the Databaseof the Database Can Provide Misleading ResultsCan Provide Misleading Results
  • 5. Basic SQL ComponentsBasic SQL Components SELECTSELECT schema.table.schema.table.columncolumn FROM tableFROM table aliasalias WHERE [conditions]WHERE [conditions] ORDER BY [columns]ORDER BY [columns] ;; Defines the end of an SQL statementDefines the end of an SQL statement Some programs require it, some do not (TOAD DoesSome programs require it, some do not (TOAD Does Not)Not) Needed only if multiple SQL statements run in a scriptNeeded only if multiple SQL statements run in a script Optional Elements
  • 6. SELECT StatementSELECT Statement SELECT Statement Defines WHAT is to beSELECT Statement Defines WHAT is to be returned (separated by commas)returned (separated by commas) Database Columns (From Tables or Views)Database Columns (From Tables or Views) Constant Text ValuesConstant Text Values FormulasFormulas PrePre--defined Functionsdefined Functions Group 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 the FROM StatementFROM Statement Example: SELECT state_code, state_nameExample: SELECT state_code, state_name
  • 7. FROM StatementFROM Statement Defines the Table(s) or View(s) Used byDefines the Table(s) or View(s) Used by the SELECT or WHERE Statementsthe SELECT or WHERE Statements You MUST Have a FROM statementYou MUST Have a FROM statement Multiple Tables/Views are separated byMultiple Tables/Views are separated by CommasCommas
  • 8. ExamplesExamples SELECT state_name, state_abbrSELECT state_name, state_abbr FROM statesFROM states SELECT *SELECT * FROM agenciesFROM agencies SELECTSELECT arithmetic_meanarithmetic_mean –– minimum_valueminimum_value FROM annual_summariesFROM annual_summaries
  • 9. WHERE ClauseWHERE Clause OptionalOptional Defines what records are to be included in the queryDefines what records are to be included in the query Uses Conditional OperatorsUses Conditional Operators =, >, >=, <, <=, != (<>)=, >, >=, <, <=, != (<>) BETWEEN x AND yBETWEEN x AND y IN (IN (listlist)) LIKELIKE ‘‘%string%string’’ ((““%%”” is a wildis a wild--card)card) IS NULLIS NULL NOT {BETWEEN / IN / LIKE / NULL}NOT {BETWEEN / IN / LIKE / NULL} Multiple Conditions Linked with AND & OR StatementsMultiple Conditions Linked with AND & OR Statements Strings Contained Within SINGLE QUOTES!!Strings Contained Within SINGLE QUOTES!!
  • 10. AND & ORAND & OR Multiple 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 the RecordRecord ““OROR”” Means at least 1 of the Conditions is TRUEMeans at least 1 of the Conditions is TRUE You May Group Statements with ( )You May Group Statements with ( ) BE CAREFUL MIXINGBE CAREFUL MIXING ““ANDAND”” && ““OROR”” ConditionsConditions
  • 11. Examples with WHEREExamples with WHERE SELECT *SELECT * FROM annual_summariesFROM annual_summaries WHERE sd_duration_code =WHERE sd_duration_code = ‘‘11’’ SELECT state_nameSELECT state_name FROM statesFROM states WHERE state_population > 15000000WHERE state_population > 15000000
  • 12. More ExamplesMore Examples SELECT state_name, state_populationSELECT state_name, state_population FROM statesFROM states WHERE state_name LIKEWHERE state_name LIKE ‘‘%NORTH%%NORTH%’’ SELECT *SELECT * FROM annual_summariesFROM annual_summaries WHERE sd_duration_code IN (WHERE sd_duration_code IN (‘‘11’’,, ‘‘WW’’,, ‘‘XX’’)) AND annual_summary_year = 2000AND annual_summary_year = 2000
  • 13. Be Careful!Be Careful! SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_code FROM annual_summariesFROM annual_summaries WHERE annual_summary_year = 2003WHERE annual_summary_year = 2003 AND values_gt_pri_std > 0AND values_gt_pri_std > 0 OR values_gt_sec_std > 0OR values_gt_sec_std > 0 SELECT mo_mo_id, sd_duration_codeSELECT mo_mo_id, sd_duration_code FROM annual_summariesFROM annual_summaries WHERE annual_summary_year = 2003WHERE annual_summary_year = 2003 AND (values_gt_pri_std > 0AND (values_gt_pri_std > 0 OR values_gt_sec_std > 0)OR values_gt_sec_std > 0)
  • 14. ORDER BY StatementORDER BY Statement Defines How the Records are to be SortedDefines How the Records are to be Sorted Must be in the SELECT statement to beMust be in the SELECT statement to be ORDER BYORDER BY Default is to order in ASC (Ascending)Default is to order in ASC (Ascending) orderorder Can Sort in Reverse (Descending) OrderCan Sort in Reverse (Descending) Order withwith ““DESCDESC”” After the Column NameAfter the Column Name
  • 15. ORDER BY ExampleORDER BY Example SELECT *SELECT * FROM agenciesFROM agencies ORDER BY agency_descORDER BY agency_desc SELECT cc_cn_stt_state_code, site_idSELECT cc_cn_stt_state_code, site_id FROM sitesFROM sites WHERE 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. Group FunctionsGroup Functions Performs Common MathematicalPerforms Common Mathematical Operations on a Group of RecordsOperations on a Group of Records Must define what Constitutes a Group byMust define what Constitutes a Group by Using the GROUP BY ClauseUsing the GROUP BY Clause All nonAll non--Group elements in the SELECTGroup elements in the SELECT Statement Must be in the GROUP BYStatement Must be in the GROUP BY Clause (Additional Columns are Optional)Clause (Additional Columns are Optional)
  • 17. Group By ExampleGroup By Example SELECT si_si_id, COUNT(mo_id)SELECT si_si_id, COUNT(mo_id) FROM monitorsFROM monitors GROUP BY si_si_idGROUP BY si_si_id SELECT AVG(max_sample_value)SELECT AVG(max_sample_value) FROM summary_maximumsFROM summary_maximums WHERE max_level <= 3WHERE max_level <= 3 AND max_ind =AND max_ind = ‘‘REGREG’’ GROUP BY ans_ans_idGROUP BY ans_ans_id
  • 18. OK, I understand How to Get DataOK, I understand How to Get Data From 1 TableFrom 1 Table…… What aboutWhat about Multiple Tables?Multiple Tables? MONITORS MO_ID SI_SI_ID PA_PARAMETER_CODE POC V_MONITOR_ID MO_ID AIRS_MONITOR_ID STATE_CODE COUNTY_CODE SITE_ID PARAMETER_CODE POC PARAMETERS PARAMETER_CODE PARAMETER_DESC
  • 19. Primary & Foreign KeysPrimary & Foreign Keys Primary KeysPrimary Keys 1 or More Columns Used to Uniquely Identify1 or More Columns Used to Uniquely Identify a record.a record. All Columns Defined as PKAll Columns Defined as PK’’s MUST bes MUST be populatedpopulated Foreign KeysForeign Keys Value on a table that references a PrimaryValue on a table that references a Primary Key from a different tableKey from a different table
  • 20. V_MONITOR_ID MO_ID STATE_CODE COUNTY_CODE SITE_ID PARAMETER_CODE POC Primary & Foreign KeysPrimary & Foreign Keys MONITORS MO_ID% SI_SI_ID* PA_PARAMETER_CODE* POC PARAMETERS PARAMETER_CODE% PARAMETER_DESC * = Foreign Key % = Primary Key SITES SI_ID% SITE_LATITUDE SITE_LONGITUDE STREET_ADDRESS
  • 21. Joining TablesJoining Tables PARAMETERS Parameter_Code Parameter_Desc 44201 Ozone 42101 CO 42401 SO2 81102 PM10 Default behavior is to show every possible combination between the two tables 14240136 14420125 18110224 24210113 14210112 14420111 POCPA_PARAMETER_CODESI_SI_IDMO_ID MONITORS
  • 22. Cartesian Join / Simple JoinCartesian Join / Simple Join SELECT mo_id, poc, parameter_desc FROM monitors, parameters PARAMETERS Parameter_Code Parameter_Desc 44201 Ozone 42101 CO 42401 SO2 81102 PM10 MONITORS MO_ID SI_SI_ID PA_PARAMETER_CODE POC 1 1 44201 1 2 1 42101 1 3 1 42101 2 4 2 81102 1 5 2 44201 1 6 3 42401 1
  • 23. Joining TablesJoining Tables PARAMETERS Parameter_Code Parameter_Desc 44201 Ozone 42101 CO 42401 SO2 81102 PM10 MONITORS MO_ID SI_SI_ID PA_PARAMETER_CODE POC 1 1 44201 1 2 1 42101 1 3 1 42101 2 4 2 81102 1 5 2 44201 1 6 3 42401 1 SELECT mo_id, poc, parameter_desc FROM monitors, parameters WHERE pa_parameter_code = parameter_code
  • 24. Joining TablesJoining Tables Joins Between Tables are Usually BasedJoins Between Tables are Usually Based on Primary / Foreign Keyson Primary / Foreign Keys Make Sure Joins Between All Tables in theMake Sure Joins Between All Tables in the FROM Clause ExistFROM Clause Exist List Joins Between Tables Before OtherList Joins Between Tables Before Other Selection ElementsSelection Elements
  • 25. AliasesAliases ““ShorthandShorthand”” for Table or Columnfor Table or Column ReferencesReferences SELECT Aliases Appear as ColumnSELECT Aliases Appear as Column Headers in the OutputHeaders in the Output Aliases Cannot be KeywordsAliases Cannot be Keywords
  • 26. Previous SQL With AliasesPrevious SQL With Aliases SELECT mo.mo_id, mo.poc, pa.parameter_desc parameter FROM monitors mo, parameters pa WHERE mo.pa_parameter_code = pa.parameter_code
  • 27. Why Use an Alias?Why Use an Alias? Saves TypingSaves Typing Good Internal DocumentationGood Internal Documentation Better HeadersBetter Headers If the same column name exists onIf the same column name exists on multiple tables, SQL needs a way to knowmultiple tables, SQL needs a way to know which element you are referencingwhich element you are referencing (MO_MO_ID for example)(MO_MO_ID for example)
  • 28. RecapRecap Basic Structural ElementsBasic Structural Elements SELECTSELECT FROMFROM WHEREWHERE ORDER BYORDER BY GROUP BYGROUP BY Selecting From Multiple TablesSelecting From Multiple Tables Join Multiple Tables via Primary & Foreign KeysJoin Multiple Tables via Primary & Foreign Keys AliasesAliases