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

PPT
SQL302 Intermediate SQL Workshop 2
PDF
SQL302 Intermediate SQL
PPT
SQL302 Intermediate SQL Workshop 3
PPT
SQL201S Accelerated Introduction to MySQL Queries
PPT
SQL212.1 Introduction to SQL using Oracle Module 1
PDF
Mcts self paced training kit exam 432 sql server 2008 - implementation and ...
PDF
Module 3 design and implementing tables
SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL
SQL302 Intermediate SQL Workshop 3
SQL201S Accelerated Introduction to MySQL Queries
SQL212.1 Introduction to SQL using Oracle Module 1
Mcts self paced training kit exam 432 sql server 2008 - implementation and ...
Module 3 design and implementing tables

Viewers also liked (20)

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

Similar to SQL302 Intermediate SQL Workshop 1 (20)

PPT
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
PDF
SQL212 Oracle SQL Manual
PDF
SQL202 SQL Server SQL Manual
PDF
SQL201W MySQL SQL Manual
PDF
10g sql e book
PDF
Sql 2009
PPT
SQL200.1 Module 1
PDF
SQL Tutorial
PDF
PDF
DOC
Module 3
PPT
SQL212.3 Introduction to SQL using Oracle Module 3
PDF
SQL Commands
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
PPTX
Dbms
PPTX
Info 2102 l1 database review
PPTX
data base programming chapter1 26 slides
PPTX
BITM3730Week14.pptx
PDF
PHP Roadshow - MySQL Database Essentials
PDF
Modern Database Management 12th Edition Hoffer Test Bank
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL212 Oracle SQL Manual
SQL202 SQL Server SQL Manual
SQL201W MySQL SQL Manual
10g sql e book
Sql 2009
SQL200.1 Module 1
SQL Tutorial
Module 3
SQL212.3 Introduction to SQL using Oracle Module 3
SQL Commands
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dbms
Info 2102 l1 database review
data base programming chapter1 26 slides
BITM3730Week14.pptx
PHP Roadshow - MySQL Database Essentials
Modern Database Management 12th Edition Hoffer Test Bank
Ad

More from Dan D'Urso (20)

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

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Machine Learning_overview_presentation.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
NewMind AI Weekly Chronicles - August'25-Week II
Dropbox Q2 2025 Financial Results & Investor Presentation
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The AUB Centre for AI in Media Proposal.docx
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Machine Learning_overview_presentation.pptx
cuic standard and advanced reporting.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Big Data Technologies - Introduction.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity

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