SlideShare a Scribd company logo
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 (20)

PPTX
Vhag profile 2013
Elroy Fernandes
 
PPTX
Digital Public Records
Ryan Thornburg
 
PPT
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Ryan Thornburg
 
PPT
Widget SOA
Stephen Anthony
 
PPT
SQL200.3 Module 3
Dan D'Urso
 
PPT
Reporting for Online:
Tools for Building Trust and Relevance
Ryan Thornburg
 
ODP
ELS SILENCIS D'ORIENT
JAVIER ALSINA GONZALEZ
 
PPT
Pharma Powerpoint 2
guest4a9aba
 
PPT
Profit Hunters
Cory Rhodes
 
PPT
eParticipation in The Netherlands
BZK
 
PDF
My Logo Portfolio
beth7865
 
PDF
Resume Portfolio Linkedin 01 2009
pulamajor
 
PPT
George Washington Teacher’s Institute
moorebl
 
PPT
AVB201.1 MS Access VBA Module 1
guest38bf
 
PPTX
El nazisme viscut des del bàndol alemany (clotet, conangla)
JAVIER ALSINA GONZALEZ
 
PPTX
Tutorial: Your First Reporting Assignment
Ryan Thornburg
 
PPTX
Operació t4 i josef mengele
JAVIER ALSINA GONZALEZ
 
PPT
Thom Point of View on Segmentation
PieterDuron
 
PPT
Creating a Photo Story With Soundslides
Ryan Thornburg
 
Vhag profile 2013
Elroy Fernandes
 
Digital Public Records
Ryan Thornburg
 
Link Journalism: Curation to increase trust, relevance, brevity and pageviews
Ryan Thornburg
 
Widget SOA
Stephen Anthony
 
SQL200.3 Module 3
Dan D'Urso
 
Reporting for Online:
Tools for Building Trust and Relevance
Ryan Thornburg
 
ELS SILENCIS D'ORIENT
JAVIER ALSINA GONZALEZ
 
Pharma Powerpoint 2
guest4a9aba
 
Profit Hunters
Cory Rhodes
 
eParticipation in The Netherlands
BZK
 
My Logo Portfolio
beth7865
 
Resume Portfolio Linkedin 01 2009
pulamajor
 
George Washington Teacher’s Institute
moorebl
 
AVB201.1 MS Access VBA Module 1
guest38bf
 
El nazisme viscut des del bàndol alemany (clotet, conangla)
JAVIER ALSINA GONZALEZ
 
Tutorial: Your First Reporting Assignment
Ryan Thornburg
 
Operació t4 i josef mengele
JAVIER ALSINA GONZALEZ
 
Thom Point of View on Segmentation
PieterDuron
 
Creating a Photo Story With Soundslides
Ryan Thornburg
 

Similar to SQL302 Intermediate SQL Workshop 1 (20)

PPT
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
PDF
SQL212 Oracle SQL Manual
Dan D'Urso
 
PDF
SQL202 SQL Server SQL Manual
Dan D'Urso
 
PDF
SQL201W MySQL SQL Manual
Dan D'Urso
 
PDF
10g sql e book
Mansoor Abd Algadir
 
PDF
Sql 2009
Cathie101
 
PPT
SQL200.1 Module 1
Dan D'Urso
 
PDF
SQL Tutorial
ziamd
 
PDF
SQL
kaushal123
 
PDF
SQL
kaushal123
 
DOC
Module 3
cs19club
 
PPT
SQL212.3 Introduction to SQL using Oracle Module 3
Dan D'Urso
 
PDF
SQL Commands
Divyank Jindal
 
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
PPTX
Dbms
saurav-IT
 
PPTX
Info 2102 l1 database review
IIUM
 
PPTX
data base programming chapter1 26 slides
nights1988
 
PPTX
BITM3730Week14.pptx
MattMarino13
 
PDF
PHP Roadshow - MySQL Database Essentials
Cherrie Ann Domingo
 
PDF
Modern Database Management 12th Edition Hoffer Test Bank
anitahhomi
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
SQL212 Oracle SQL Manual
Dan D'Urso
 
SQL202 SQL Server SQL Manual
Dan D'Urso
 
SQL201W MySQL SQL Manual
Dan D'Urso
 
10g sql e book
Mansoor Abd Algadir
 
Sql 2009
Cathie101
 
SQL200.1 Module 1
Dan D'Urso
 
SQL Tutorial
ziamd
 
Module 3
cs19club
 
SQL212.3 Introduction to SQL using Oracle Module 3
Dan D'Urso
 
SQL Commands
Divyank Jindal
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
Dbms
saurav-IT
 
Info 2102 l1 database review
IIUM
 
data base programming chapter1 26 slides
nights1988
 
BITM3730Week14.pptx
MattMarino13
 
PHP Roadshow - MySQL Database Essentials
Cherrie Ann Domingo
 
Modern Database Management 12th Edition Hoffer Test Bank
anitahhomi
 
Ad

More from Dan D'Urso (20)

PPT
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
PPTX
Database Normalization
Dan D'Urso
 
PPT
VIS201d Visio Database Diagramming
Dan D'Urso
 
PPT
PRJ101a Project 2013 Accelerated
Dan D'Urso
 
PPT
PRJ101xl Project Libre Basic Training
Dan D'Urso
 
PPT
Introduction to coding using Python
Dan D'Urso
 
PPTX
Stem conference
Dan D'Urso
 
PDF
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
PPTX
Microsoft access self joins
Dan D'Urso
 
PDF
AIN106 Access Reporting and Analysis
Dan D'Urso
 
PDF
Course Catalog
Dan D'Urso
 
PDF
AIN100
Dan D'Urso
 
PPT
SQL206 SQL Median
Dan D'Urso
 
PPT
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
PDF
AIN102 Microsoft Access Queries
Dan D'Urso
 
PPT
AIN102S Access string function sample queries
Dan D'Urso
 
PPT
AIN102.2 Microsoft Access Queries
Dan D'Urso
 
PPT
AIN102.1 Microsoft Access Queries Module 1
Dan D'Urso
 
PDF
AIN100B Microsoft Access Level 2
Dan D'Urso
 
PDF
AMP110 Microsoft Access Macros
Dan D'Urso
 
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
Database Normalization
Dan D'Urso
 
VIS201d Visio Database Diagramming
Dan D'Urso
 
PRJ101a Project 2013 Accelerated
Dan D'Urso
 
PRJ101xl Project Libre Basic Training
Dan D'Urso
 
Introduction to coding using Python
Dan D'Urso
 
Stem conference
Dan D'Urso
 
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
Microsoft access self joins
Dan D'Urso
 
AIN106 Access Reporting and Analysis
Dan D'Urso
 
Course Catalog
Dan D'Urso
 
AIN100
Dan D'Urso
 
SQL206 SQL Median
Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
AIN102 Microsoft Access Queries
Dan D'Urso
 
AIN102S Access string function sample queries
Dan D'Urso
 
AIN102.2 Microsoft Access Queries
Dan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
Dan D'Urso
 
AIN100B Microsoft Access Level 2
Dan D'Urso
 
AMP110 Microsoft Access Macros
Dan D'Urso
 
Ad

Recently uploaded (20)

PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Designing Production-Ready AI Agents
Kunal Rai
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
July Patch Tuesday
Ivanti
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Designing Production-Ready AI Agents
Kunal Rai
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
July Patch Tuesday
Ivanti
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 

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 [email protected] 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? [email protected] 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