SlideShare a Scribd company logo
1 of 64
SQL302




               Intermediate SQL Programming
                Based on SQL Clearly Explained by Jan Harrington and
            Microsoft SQL Server2008 T-SQL Fundamentals by Itzik Ben-gan



     Module 1 – Relational Database Background, CASE,
       Cast & Convert, Subqueries, Table Expressions
Bookstore                         SQL302 Module 1                          1
Note on SQL302 Slides
    • Many of these slides were originally designed to
      support a single SQL course which was used for any
      of MS Access, MySQL, Oracle and SQL Server.
    • As such you may see here slides developed in any
      one of the above products.
    • We are in the process of migrating the vendor
      specific slides out into their own slide sets.




Bookstore2               SQL302 Module 2                   2
Warning!
• Below are some table name changes to be
  aware of in doing queries. We have created
  synonyms so either name should work.

        New Name              Old Name
        Orders                Order_filled
        Order_Lines           Orderlines


Bookstore2             SQL302 Module 2         3
SQL302 Contact Information



             P.O. Box 6142
             Laguna Niguel, CA 92607
             949-489-1472
             http://www.d2associates.com
             slides.1@dhdursoassociates.com
             Copyright 2001-2012. All rights reserved.


Bookstore2                            SQL302 Module 2    4
SQL302 Resources
• Bookstore database scripts found on
  box.com at
      http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
      http://www.slideshare.net/OCDatabases
• Follow up questions?
      sql.support@dhdursoassociates.com

Bookstore              SQL302 Module 1        5
SQL Programming
• Course focus is SQL language
• Widely used for:
      – Database administration
      – Enterprise application development
      – Data driven web sites
• A foundation skill for eBusiness and
  almost all major business applications that
  use relational databases
Bookstore              SQL302 Module 1          6
SQL302
• Students should have taken SQL202 or
  have equivalent experience. It is assumed
  students know basic SQL.
• We will use the Management Studio in this
  class, but the focus will be on SQL
  scripting


Bookstore        SQL302 Module 1              7
Relational Database Evolution
• Based on Codd’s paper
• Early commercial efforts focused on Unix
• First mainframe implementation by IBM -
  precursor to today’s DB2
• First PC implementation in early 80’s by
  Oracle


Bookstore        SQL302 Module 1             8
Relational Database Basics
•   Storage                •   Indexes
•   Databases              •   Views
•   Tables                 •   Cursors
•   Rows                   •   Application interfaces
•   Columns




Bookstore         SQL302 Module 1                       9
Relational Database Table




Bookstore               SQL302 Module 1   10
Constraints
• Database                        • Other Business Rule
      – Domain                         – Triggers
      – Uniqueness                     – Stored Procedures
      – Relationship
        Cardinality
            • 1 to 1
            • 1 to N




Bookstore                SQL302 Module 1                     11
Relational Database with constraints




Bookstore                SQL302 Module 1      12
Database Management Systems

                   Positioning Chart


    Cost                           VLDB
                            Enterprise
                       Workgroup
                 Single user
            Spreadsheet
                                   # Users
Bookstore              SQL302 Module 1       13
System Architecture

 File Server
 Architecture
                                    Access
                                    MDB



                Access



Bookstore         SQL302 Module 1            14
System Architecture

 Client/Server
 Architecture
                                              Oracle
            SQL                             DB



             Visual                        Access
             Basic App


Bookstore                SQL302 Module 1               15
System Architecture

 Web
 Architecture
                      Web                 Oracle
                      Server              DB


                                        SQL
            Browser



Bookstore             SQL302 Module 1              16
Approaching SQL
• Relatively simple
• Two main environments
      – Interactive (This course)
      – Embedded
            • Static (Compiled)
            • Dynamic




Bookstore                   SQL302 Module 1   17
SQL Standardization
ANSI standardization
      –     First standard in 1986
      –     SQL 89
      –     SQL 92
      –     SQL 99
• Various vendor extensions
      – Microsoft/Sybase: T-SQL
      – Oracle: PL/SQL

Bookstore                   SQL302 Module 1   18
SQL Conformance
•   Entry
•   Intermediate
•   Advanced
•   Most are at least entry level




Bookstore            SQL302 Module 1   19
SQL Statements

• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Definition Language (DDL)

• Note: SQL 99 changes these to seven types
  including DQL Data Query Language



Bookstore           SQL302 Module 1           20
SQL DDL
• Data definition language (DDL)

      – Create, alter, drop, etc.
      – Frequently implemented via various CASE
        tools: Visio, Embarcadero, ERWin, etc.
      – But very useful for database administration



Bookstore               SQL302 Module 1               21
SQL DCL
• Data Control Language (DDL)

      –     Grant
      –     Revoke
      –     Deny
      –     Constraints



Bookstore                  SQL302 Module 1   22
SQL DQL
• Data Manipulation Language (DML)
      – Select




Bookstore         SQL302 Module 1    23
SQL DML
• Data Manipulation Language (DML)
      – Insert
      – Update
      – Delete




Bookstore         SQL302 Module 1    24
SQL Statement Processing

                        Parse

                      Validate

                     Optimize

                    Access Plan

                      Execute

Bookstore            SQL302 Module 1   25
Sample Database(s)



• Before we continue (note: instructor may have
  already done this)…
• Load the sample database(s) if not already loaded
      – Use supplied SQL Script (after class this script may be
        found on Box.com).



Bookstore                  SQL302 Module 1                    26
Text Conventions
• In Access character strings are normally
  surrounded by double quotes
      – “Jones”
• In an enterprise database such as Oracle or
  SQL Sever enclose text strings in single
  quotes
      – ‘Jones’

Bookstore          SQL302 Module 1              27
Date Conventions
• In an enterprise database such as Oracle or
  SQL Sever, enclose dates in single quotes
      – ‘2004-12-23’ MySQL
      – ’12-23-2004’ SQL Server
      – ’23-DEC-04’ Oracle




Bookstore             SQL302 Module 1           28
Select statement clauses
       SELECT…
       INTO…
       FROM…
       WHERE…
       GROUP BY…
       HAVING…
       ORDER BY…
Bookstore            SQL302 Module 1   29
SELECT


            See SQL202 for syntax and
            semantics of basic SELECT
            statement




Bookstore              SQL302 Module 1   30
On Your Own
• Find books written by Mark Twain
• Show title, publisher, year




Bookstore        SQL302 Module 1     31
Complex Predicates
  Follow normal boolean logic
  Select   customer_last_name,
  customer_street
  From customers
  Where (customer_last_name =
  ‘Jones’ or customer_last_name =
  ‘Smith’)and customer_state=‘NY’

Bookstore         SQL302 Module 1   32
Select with Complex Where




Bookstore       SQL302 Module 1    33
Complex Where Result




Bookstore          SQL302 Module 1   34
Special Operators
 • Can be used in where clause
 • Covered in this class (SQL302)
       – Exists (Covered in section on Joins)
       – Like extensions
       – Any, some, all

 • Previously Covered in SQL202
       –    LIKE
       –    IN
       –    BETWEEN
       –    IS NULL
Bookstore                      SQL302 Module 1   35
Like Extensions
• ANSI wildcards
• Where
  customer_last_name
  like ‘[JK]o%’
  like ‘[J-M]%’
  like [^abc]%




Bookstore         SQL302 Module 1   36
Any, some, All
• Any, some                   • All
• Modifies comparison         • Modifies comparison
  operator                      operator
• Ex: expr > any (1,2,3)      • Ex: expr > all(1,2,3)
  means expr would              would have to be
  have to be greater            greater than 3
  than the minimum
  which is 1

Bookstore            SQL302 Module 1                    37
On Your Own
• Find all customers with a last name that starts
  with a through m
• Find all customers that live in a state that does
  not start with m




Bookstore             SQL302 Module 1                 38
Case
• Used to return a choice from two or more
  alternatives
• Two forms
      – Searched case
      – Unsearched case




Bookstore             SQL302 Module 1        39
Unsearched (Simple) CASE
• This form of case has a selector which
  takes on a value used to select an
  alternative
• Syntax:
      Select case <selector>
           When <value1> then <expr1>,
           When <value2> then <expr2>,
           …
      Else
           <statement>
      End
Bookstore                    SQL302 Module 1   40
Unsearched (Simple Case)
• Example: expand the order filled status
  columns in the orders table




Bookstore            SQL302 Module 1        41
Searched CASE
• This form of the Case statement does not
  have a selector
• Syntax:
      Select case
           When <condition1> then <expr1>,
           When <condition2> then <expr2>,
           …
      Else
           <statement>
      End
Bookstore                   SQL302 Module 1   42
Searched CASE
• Example: list names of referring
  customers, self in no referrer




Bookstore         SQL302 Module 1    43
CAST
• Function to cast a column to a different
  data type; same idea as cast in c
  programming
• Syntax:
      CAST ( expression AS data_type [ ( length ) ] )




Bookstore               SQL302 Module 1                 44
CAST
• Example: combine author name and
  publication year into one column




Bookstore       SQL302 Module 1      45
CAST results




Bookstore      SQL302 Module 1   46
Convert
• Function to convert from one data type to
  another; mostly replaced by cast
• Syntax
      CONVERT ( data_type [ ( length ) ] , expression
       [ , style ] )




Bookstore              SQL302 Module 1              47
Convert
• Example:
      – Remove time from display of a datetime
        column




Bookstore              SQL302 Module 1           48
Convert results




Bookstore       SQL302 Module 1   49
Subqueries
• One select statement embedded in another
• Can be nested multiple levels deep
• Can be used in select, from and where
  clauses
• Two types:
      – Uncorrelated – executes inner query then outer
      – Correlated – executes inner query once for
        each outer query row

Bookstore              SQL302 Module 2               50
Uncorrelated Subquery
• In list (covered in sql202 basic class)
• Single valued




Bookstore          SQL302 Module 2          51
Uncorrelated Subquery

            select isbn, quantity
            from orderlines
            where order_numb in
            (select order_numb from
            orders where order_date
            between ‘1/1/99’ and
            ‘12/31/99’);
Bookstore              SQL302 Module 2   52
Single-valued Subquery
• Subqueries can be used where an
  expression returns a scalar or single value
      – calculations
      – comparisons
• Can be used in select list, from clause and
  where clause


Bookstore              SQL302 Module 2          53
Single-valued Subquery
• Example
      – Show all orderlines with an order total greater
        than the average for all orderlines
• Code
    use bookstore;
    SELECT isbn, quantity
        , (select avg(quantity) from orderlines) as
    [Average Quantity]
    FROM orderlines AS ol
    WHERE quantity >
    (select avg(quantity) from orderlines)
Bookstore               SQL302 Module 2                   54
Correlated Subquery with Exists
• Inner subquery executed once for each outer row
• Exists will return true or false depending on
  whether the result will have any rows or not
• Can be a quick way to test for existence of
  records (parent records, say) as used in
  application enforcement of referential integrity




Bookstore           SQL302 Module 2                  55
Correlated subquery with Exists
            SELECT isbn, quantity
            FROM orderlines AS ol
            WHERE exists
            (select * from orders o where
            ol.order_numb = o.order_numb
             and o.order_date between ‘1/1/99’
            and ‘12/31/99’);



Bookstore                  SQL302 Module 2       56
Derived Tables
• Sort of a named subquery
• Allows you to access columns inside the
  subquery from the containing outer query
• Syntax
  <select statement> as derivedtablename



Bookstore         SQL302 Module 2            57
Derived Tables
• Example: List the number of orders per
  year
• Code
    use bookstore;
    select order_year, count(order_numb)
    from(
        select YEAR(order_date) as order_year,
    order_numb
        from orders) as d
    group by order_year;
Bookstore            SQL302 Module 2             58
Common Table Expressions
• Can be used to define a subquery that can
  be reused within an SQL statement
• Syntax
            With CTE_name (column list)
            As (
            Select statement
            )
            <outer query that uses the CTE>

Bookstore                    SQL302 Module 2   59
Common Table Expressions
• Example: show order_lines with cost more
  than the average. Demonstrate two
  techniques:
      – Technique 1 - Using subqueries w/out a CTE
      – Technique 2 - With CTE’s




Bookstore              SQL302 Module 2               60
Technique 1 – w/out CTE
select isbn, cost_each, (select
  AVG(cost_each)from orderlines)
from orderlines
where cost_each > (select AVG(cost_each) from
  orderlines)
order by isbn;




Bookstore           SQL302 Module 2             61
Technique 2 – using a CTE
with average_cost_cte(average_cost)
as
(select AVG(cost_each)
from orderlines)
select isbn, cost_each, average_cost
from orderlines, average_cost_cte
where cost_each > average_cost
order by isbn;




Bookstore           SQL302 Module 2    62
SQL Exercises
  • List all customers whose last name does not
    end with s or t.
  • Find all customers who have not placed an
    order.
  • Find all order lines with an amount less than
    the average. Include the order date without the
    time.
  • List all books with a price greater than the
    average price for all books. Show the variance
    from the average, too. Use a CTE.
Bookstore             SQL302 Module 1   [end module]   63
Notes




Bookstore   SQL302 Module 1   64

More Related Content

Viewers also liked

Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public RecordsRyan Thornburg
 
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Link Journalism: Curation to increase trust, relevance, brevity and pageviewsLink Journalism: Curation to increase trust, relevance, brevity and pageviews
Link Journalism: Curation to increase trust, relevance, brevity and pageviewsRyan Thornburg
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3Dan D'Urso
 
Reporting for Online:
Tools for Building Trust and Relevance
Reporting for Online:
Tools for Building Trust and RelevanceReporting for Online:
Tools for Building Trust and Relevance
Reporting for Online:
Tools for Building Trust and RelevanceRyan Thornburg
 
Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2guest4a9aba
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The NetherlandsBZK
 
My Logo Portfolio
My Logo PortfolioMy Logo Portfolio
My Logo Portfoliobeth7865
 
Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009pulamajor
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institutemoorebl
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1guest38bf
 
El nazisme viscut des del bàndol alemany (clotet, conangla)
El nazisme viscut des del bàndol alemany (clotet, conangla)El nazisme viscut des del bàndol alemany (clotet, conangla)
El nazisme viscut des del bàndol alemany (clotet, conangla)JAVIER ALSINA GONZALEZ
 
Tutorial: Your First Reporting Assignment
Tutorial: Your First Reporting AssignmentTutorial: Your First Reporting Assignment
Tutorial: Your First Reporting AssignmentRyan Thornburg
 
Thom Point of View on Segmentation
Thom Point of View on SegmentationThom Point of View on Segmentation
Thom Point of View on SegmentationPieterDuron
 
Creating a Photo Story With Soundslides
Creating a Photo Story With SoundslidesCreating a Photo Story With Soundslides
Creating a Photo Story With SoundslidesRyan Thornburg
 

Viewers also liked (20)

Vhag profile 2013
Vhag profile 2013Vhag profile 2013
Vhag profile 2013
 
London
LondonLondon
London
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public Records
 
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Link Journalism: Curation to increase trust, relevance, brevity and pageviewsLink Journalism: Curation to increase trust, relevance, brevity and pageviews
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
 
Widget SOA
Widget SOAWidget SOA
Widget SOA
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
 
Reporting for Online:
Tools for Building Trust and Relevance
Reporting for Online:
Tools for Building Trust and RelevanceReporting for Online:
Tools for Building Trust and Relevance
Reporting for Online:
Tools for Building Trust and Relevance
 
ELS SILENCIS D'ORIENT
ELS SILENCIS D'ORIENT ELS SILENCIS D'ORIENT
ELS SILENCIS D'ORIENT
 
Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2
 
Profit Hunters
Profit HuntersProfit Hunters
Profit Hunters
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The Netherlands
 
My Logo Portfolio
My Logo PortfolioMy Logo Portfolio
My Logo Portfolio
 
Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institute
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
El nazisme viscut des del bàndol alemany (clotet, conangla)
El nazisme viscut des del bàndol alemany (clotet, conangla)El nazisme viscut des del bàndol alemany (clotet, conangla)
El nazisme viscut des del bàndol alemany (clotet, conangla)
 
Tutorial: Your First Reporting Assignment
Tutorial: Your First Reporting AssignmentTutorial: Your First Reporting Assignment
Tutorial: Your First Reporting Assignment
 
Operació t4 i josef mengele
Operació t4 i josef mengeleOperació t4 i josef mengele
Operació t4 i josef mengele
 
Thom Point of View on Segmentation
Thom Point of View on SegmentationThom Point of View on Segmentation
Thom Point of View on Segmentation
 
Creating a Photo Story With Soundslides
Creating a Photo Story With SoundslidesCreating a Photo Story With Soundslides
Creating a Photo Story With Soundslides
 

Similar to SQL302 Intermediate SQL Workshop 1

SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualDan D'Urso
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualDan D'Urso
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualDan D'Urso
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignDan D'Urso
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1Dan D'Urso
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)Michael Rys
 
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...IDERA Software
 
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012Andrew Brust
 
Relational Database and mysql insight
Relational Database and mysql insightRelational Database and mysql insight
Relational Database and mysql insightmentallog
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentEmbarcadero Technologies
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searchingdamienjoyce
 
My sql introduction for Bestcom
My sql introduction for BestcomMy sql introduction for Bestcom
My sql introduction for BestcomIvan Tu
 
My S Q L Introduction for 1 day training
My S Q L  Introduction for 1 day trainingMy S Q L  Introduction for 1 day training
My S Q L Introduction for 1 day trainingIvan Tu
 
NewSQL - Deliverance from BASE and back to SQL and ACID
NewSQL - Deliverance from BASE and back to SQL and ACIDNewSQL - Deliverance from BASE and back to SQL and ACID
NewSQL - Deliverance from BASE and back to SQL and ACIDTony Rogerson
 

Similar to SQL302 Intermediate SQL Workshop 1 (20)

SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL Manual
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)
 
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
 
RDBMS vs NoSQL
RDBMS vs NoSQLRDBMS vs NoSQL
RDBMS vs NoSQL
 
Oracle sql demo
Oracle sql demoOracle sql demo
Oracle sql demo
 
Sq lite module5
Sq lite module5Sq lite module5
Sq lite module5
 
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
 
Relational Database and mysql insight
Relational Database and mysql insightRelational Database and mysql insight
Relational Database and mysql insight
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searching
 
SQL Intro
SQL IntroSQL Intro
SQL Intro
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
My sql introduction for Bestcom
My sql introduction for BestcomMy sql introduction for Bestcom
My sql introduction for Bestcom
 
My S Q L Introduction for 1 day training
My S Q L  Introduction for 1 day trainingMy S Q L  Introduction for 1 day training
My S Q L Introduction for 1 day training
 
SQL 3.pptx
SQL 3.pptxSQL 3.pptx
SQL 3.pptx
 
NewSQL - Deliverance from BASE and back to SQL and ACID
NewSQL - Deliverance from BASE and back to SQL and ACIDNewSQL - Deliverance from BASE and back to SQL and ACID
NewSQL - Deliverance from BASE and back to SQL and ACID
 

More from Dan D'Urso

LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartDan D'Urso
 
Database Normalization
Database NormalizationDatabase Normalization
Database NormalizationDan D'Urso
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingDan D'Urso
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedDan D'Urso
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingDan D'Urso
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using PythonDan D'Urso
 
Stem conference
Stem conferenceStem conference
Stem conferenceDan D'Urso
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joinsDan D'Urso
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisDan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL MedianDan D'Urso
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2Dan D'Urso
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesDan D'Urso
 
AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queriesDan D'Urso
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesDan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1Dan D'Urso
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2Dan D'Urso
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosDan D'Urso
 

More from Dan D'Urso (20)

LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with Lucidchart
 
Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database Diagramming
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 Accelerated
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic Training
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
 
Stem conference
Stem conferenceStem conference
Stem conference
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joins
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and Analysis
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
AIN100
AIN100AIN100
AIN100
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access Queries
 
AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queries
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 

Recently uploaded

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
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
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
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!
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 
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
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

SQL302 Intermediate SQL Workshop 1

  • 1. SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server2008 T-SQL Fundamentals by Itzik Ben-gan Module 1 – Relational Database Background, CASE, Cast & Convert, Subqueries, Table Expressions Bookstore SQL302 Module 1 1
  • 2. Note on SQL302 Slides • Many of these slides were originally designed to support a single SQL course which was used for any of MS Access, MySQL, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the vendor specific slides out into their own slide sets. Bookstore2 SQL302 Module 2 2
  • 3. Warning! • Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines Orderlines Bookstore2 SQL302 Module 2 3
  • 4. SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2012. All rights reserved. Bookstore2 SQL302 Module 2 4
  • 5. SQL302 Resources • Bookstore database scripts found on box.com at http://tinyurl.com/SQLScripts • Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases • Follow up questions? sql.support@dhdursoassociates.com Bookstore SQL302 Module 1 5
  • 6. SQL Programming • Course focus is SQL language • Widely used for: – Database administration – Enterprise application development – Data driven web sites • A foundation skill for eBusiness and almost all major business applications that use relational databases Bookstore SQL302 Module 1 6
  • 7. SQL302 • Students should have taken SQL202 or have equivalent experience. It is assumed students know basic SQL. • We will use the Management Studio in this class, but the focus will be on SQL scripting Bookstore SQL302 Module 1 7
  • 8. Relational Database Evolution • Based on Codd’s paper • Early commercial efforts focused on Unix • First mainframe implementation by IBM - precursor to today’s DB2 • First PC implementation in early 80’s by Oracle Bookstore SQL302 Module 1 8
  • 9. Relational Database Basics • Storage • Indexes • Databases • Views • Tables • Cursors • Rows • Application interfaces • Columns Bookstore SQL302 Module 1 9
  • 11. Constraints • Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to N Bookstore SQL302 Module 1 11
  • 12. Relational Database with constraints Bookstore SQL302 Module 1 12
  • 13. Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # Users Bookstore SQL302 Module 1 13
  • 14. System Architecture File Server Architecture Access MDB Access Bookstore SQL302 Module 1 14
  • 15. System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic App Bookstore SQL302 Module 1 15
  • 16. System Architecture Web Architecture Web Oracle Server DB SQL Browser Bookstore SQL302 Module 1 16
  • 17. Approaching SQL • Relatively simple • Two main environments – Interactive (This course) – Embedded • Static (Compiled) • Dynamic Bookstore SQL302 Module 1 17
  • 18. SQL Standardization ANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99 • Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQL Bookstore SQL302 Module 1 18
  • 19. SQL Conformance • Entry • Intermediate • Advanced • Most are at least entry level Bookstore SQL302 Module 1 19
  • 20. SQL Statements • Data Manipulation Language (DML) • Data Control Language (DCL) • Data Definition Language (DDL) • Note: SQL 99 changes these to seven types including DQL Data Query Language Bookstore SQL302 Module 1 20
  • 21. SQL DDL • Data definition language (DDL) – Create, alter, drop, etc. – Frequently implemented via various CASE tools: Visio, Embarcadero, ERWin, etc. – But very useful for database administration Bookstore SQL302 Module 1 21
  • 22. SQL DCL • Data Control Language (DDL) – Grant – Revoke – Deny – Constraints Bookstore SQL302 Module 1 22
  • 23. SQL DQL • Data Manipulation Language (DML) – Select Bookstore SQL302 Module 1 23
  • 24. SQL DML • Data Manipulation Language (DML) – Insert – Update – Delete Bookstore SQL302 Module 1 24
  • 25. SQL Statement Processing Parse Validate Optimize Access Plan Execute Bookstore SQL302 Module 1 25
  • 26. Sample Database(s) • Before we continue (note: instructor may have already done this)… • Load the sample database(s) if not already loaded – Use supplied SQL Script (after class this script may be found on Box.com). Bookstore SQL302 Module 1 26
  • 27. Text Conventions • In Access character strings are normally surrounded by double quotes – “Jones” • In an enterprise database such as Oracle or SQL Sever enclose text strings in single quotes – ‘Jones’ Bookstore SQL302 Module 1 27
  • 28. Date Conventions • In an enterprise database such as Oracle or SQL Sever, enclose dates in single quotes – ‘2004-12-23’ MySQL – ’12-23-2004’ SQL Server – ’23-DEC-04’ Oracle Bookstore SQL302 Module 1 28
  • 29. Select statement clauses SELECT… INTO… FROM… WHERE… GROUP BY… HAVING… ORDER BY… Bookstore SQL302 Module 1 29
  • 30. SELECT See SQL202 for syntax and semantics of basic SELECT statement Bookstore SQL302 Module 1 30
  • 31. On Your Own • Find books written by Mark Twain • Show title, publisher, year Bookstore SQL302 Module 1 31
  • 32. Complex Predicates Follow normal boolean logic Select customer_last_name, customer_street From customers Where (customer_last_name = ‘Jones’ or customer_last_name = ‘Smith’)and customer_state=‘NY’ Bookstore SQL302 Module 1 32
  • 33. Select with Complex Where Bookstore SQL302 Module 1 33
  • 34. Complex Where Result Bookstore SQL302 Module 1 34
  • 35. Special Operators • Can be used in where clause • Covered in this class (SQL302) – Exists (Covered in section on Joins) – Like extensions – Any, some, all • Previously Covered in SQL202 – LIKE – IN – BETWEEN – IS NULL Bookstore SQL302 Module 1 35
  • 36. Like Extensions • ANSI wildcards • Where customer_last_name like ‘[JK]o%’ like ‘[J-M]%’ like [^abc]% Bookstore SQL302 Module 1 36
  • 37. Any, some, All • Any, some • All • Modifies comparison • Modifies comparison operator operator • Ex: expr > any (1,2,3) • Ex: expr > all(1,2,3) means expr would would have to be have to be greater greater than 3 than the minimum which is 1 Bookstore SQL302 Module 1 37
  • 38. On Your Own • Find all customers with a last name that starts with a through m • Find all customers that live in a state that does not start with m Bookstore SQL302 Module 1 38
  • 39. Case • Used to return a choice from two or more alternatives • Two forms – Searched case – Unsearched case Bookstore SQL302 Module 1 39
  • 40. Unsearched (Simple) CASE • This form of case has a selector which takes on a value used to select an alternative • Syntax: Select case <selector> When <value1> then <expr1>, When <value2> then <expr2>, … Else <statement> End Bookstore SQL302 Module 1 40
  • 41. Unsearched (Simple Case) • Example: expand the order filled status columns in the orders table Bookstore SQL302 Module 1 41
  • 42. Searched CASE • This form of the Case statement does not have a selector • Syntax: Select case When <condition1> then <expr1>, When <condition2> then <expr2>, … Else <statement> End Bookstore SQL302 Module 1 42
  • 43. Searched CASE • Example: list names of referring customers, self in no referrer Bookstore SQL302 Module 1 43
  • 44. CAST • Function to cast a column to a different data type; same idea as cast in c programming • Syntax: CAST ( expression AS data_type [ ( length ) ] ) Bookstore SQL302 Module 1 44
  • 45. CAST • Example: combine author name and publication year into one column Bookstore SQL302 Module 1 45
  • 46. CAST results Bookstore SQL302 Module 1 46
  • 47. Convert • Function to convert from one data type to another; mostly replaced by cast • Syntax CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) Bookstore SQL302 Module 1 47
  • 48. Convert • Example: – Remove time from display of a datetime column Bookstore SQL302 Module 1 48
  • 49. Convert results Bookstore SQL302 Module 1 49
  • 50. Subqueries • One select statement embedded in another • Can be nested multiple levels deep • Can be used in select, from and where clauses • Two types: – Uncorrelated – executes inner query then outer – Correlated – executes inner query once for each outer query row Bookstore SQL302 Module 2 50
  • 51. Uncorrelated Subquery • In list (covered in sql202 basic class) • Single valued Bookstore SQL302 Module 2 51
  • 52. Uncorrelated Subquery select isbn, quantity from orderlines where order_numb in (select order_numb from orders where order_date between ‘1/1/99’ and ‘12/31/99’); Bookstore SQL302 Module 2 52
  • 53. Single-valued Subquery • Subqueries can be used where an expression returns a scalar or single value – calculations – comparisons • Can be used in select list, from clause and where clause Bookstore SQL302 Module 2 53
  • 54. Single-valued Subquery • Example – Show all orderlines with an order total greater than the average for all orderlines • Code use bookstore; SELECT isbn, quantity , (select avg(quantity) from orderlines) as [Average Quantity] FROM orderlines AS ol WHERE quantity > (select avg(quantity) from orderlines) Bookstore SQL302 Module 2 54
  • 55. Correlated Subquery with Exists • Inner subquery executed once for each outer row • Exists will return true or false depending on whether the result will have any rows or not • Can be a quick way to test for existence of records (parent records, say) as used in application enforcement of referential integrity Bookstore SQL302 Module 2 55
  • 56. Correlated subquery with Exists SELECT isbn, quantity FROM orderlines AS ol WHERE exists (select * from orders o where ol.order_numb = o.order_numb and o.order_date between ‘1/1/99’ and ‘12/31/99’); Bookstore SQL302 Module 2 56
  • 57. Derived Tables • Sort of a named subquery • Allows you to access columns inside the subquery from the containing outer query • Syntax <select statement> as derivedtablename Bookstore SQL302 Module 2 57
  • 58. Derived Tables • Example: List the number of orders per year • Code use bookstore; select order_year, count(order_numb) from( select YEAR(order_date) as order_year, order_numb from orders) as d group by order_year; Bookstore SQL302 Module 2 58
  • 59. Common Table Expressions • Can be used to define a subquery that can be reused within an SQL statement • Syntax With CTE_name (column list) As ( Select statement ) <outer query that uses the CTE> Bookstore SQL302 Module 2 59
  • 60. Common Table Expressions • Example: show order_lines with cost more than the average. Demonstrate two techniques: – Technique 1 - Using subqueries w/out a CTE – Technique 2 - With CTE’s Bookstore SQL302 Module 2 60
  • 61. Technique 1 – w/out CTE select isbn, cost_each, (select AVG(cost_each)from orderlines) from orderlines where cost_each > (select AVG(cost_each) from orderlines) order by isbn; Bookstore SQL302 Module 2 61
  • 62. Technique 2 – using a CTE with average_cost_cte(average_cost) as (select AVG(cost_each) from orderlines) select isbn, cost_each, average_cost from orderlines, average_cost_cte where cost_each > average_cost order by isbn; Bookstore SQL302 Module 2 62
  • 63. SQL Exercises • List all customers whose last name does not end with s or t. • Find all customers who have not placed an order. • Find all order lines with an amount less than the average. Include the order date without the time. • List all books with a price greater than the average price for all books. Show the variance from the average, too. Use a CTE. Bookstore SQL302 Module 1 [end module] 63
  • 64. Notes Bookstore SQL302 Module 1 64