SlideShare a Scribd company logo
1 of 28
Download to read 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

More Related Content

What's hot

Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
Achmad Solichin
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
Nalina Kumari
 

What's hot (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
 

Viewers also liked (9)

Sql basics
Sql basicsSql basics
Sql basics
 
Introduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdminIntroduction to MySQL and phpMyAdmin
Introduction to MySQL and phpMyAdmin
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
 
MS Sql Server: Joining Databases
MS Sql Server: Joining DatabasesMS Sql Server: Joining Databases
MS Sql Server: Joining Databases
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
College management system ppt
College management system pptCollege management system ppt
College management system ppt
 
Database management system presentation
Database management system presentationDatabase management system presentation
Database management system presentation
 
Ms excel 2007
Ms excel 2007Ms excel 2007
Ms excel 2007
 

Similar to Sql basics

MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
Marcus Davage
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
Tony Wong
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 

Similar to Sql basics (20)

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
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
 

More from Kumar

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Sql basics

  • 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