SlideShare a Scribd company logo
SQL302




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

            Workshop 2 – Joins, Set Operations, Window
                            Functions
Bookstore                         SQL302 Module 2                                 1
Note on SQL302 Slides
    • 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 Oracle,
      Access, and MySQL slides out into their own slide
      sets. The SQL302 slides will cover Microsoft SQL
      Server.


Bookstore                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


Bookstore                  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-2012All rights reserved.


Bookstore                            SQL302 Module 2   4
SQL302 Resources
• Bookstore database scripts found on
  box.net 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 2        5
Relational Database with constraints (from text)




Bookstore                SQL302 Module 2                  6
Sample Employees Database




Bookstore2 &          SQL204 Module 1      7
Employees
More conventions
• Names can be surrounded with “ “ or [ ] as
  in [order details].
• Some of the PowerPoint slides may have
  this convention.
• Better practice is to use an underscore as in
  order_details.


Bookstore          SQL302 Module 2                8
SQL302

                   SQL Programming

            Part 1 – Joins: Natural, Self and Outer


Bookstore                  SQL302 Module 2            9
Joins
•   Inner (Covered in SQL202 course)
•   Natural Join
•   Self
•   Data Warehouse operators
•   Outer
      – Left
      – Right
      – Full
• Cross
• Theta
• We will cover some of the more advanced or subtle
  aspects of joins in this class
Bookstore               SQL302 Module 2               10
Natural Joins
• Table1 natural join table3 – automatically
  uses columns with same name
• Table 1 natural join table2 using(<column-
  list>
• Not yet available in SQL Server



Bookstore         SQL302 Module 2              11
Correlation Names (Table Aliases)

• Can abbreviate references to tables
• For example:
      Select e.name, j.payrange
      From employees as e
      Inner join job_information as j
      On e.jobcode = j.jobcode;



Bookstore               SQL302 Module 2   12
Self Joins
• Implements a recursive relationship
• Important in various applications
      –     Parts lists/assemblies
      –     HR
      –     Etc.
      –     Table joined to itself using correlation names



Bookstore                   SQL302 Module 2                  13
Self Joins

            SELECT e.*, m.name
            FROM employees AS e, employees
            AS m
            WHERE e.managerid =
            m.employeeid;




Bookstore               SQL302 Module 2      14
Bookstore   SQL302 Module 2   15
Datawarehouse clauses
• Two keywords that can be added to a
  grouped query
      – Rollup
      – Cube
• Places additional summary rows in the
  result set
• Result set is a true relational result set

Bookstore           SQL302 Module 2            16
Rollup
• Example: calculate average salaries by
  job_title_code and manager




Bookstore         SQL302 Module 2          17
Rollup results




Bookstore       SQL302 Module 2   18
cube
• Similar to rollup but computes summary
  rows in all dimensions




Bookstore        SQL302 Module 2           19
Cube results
• Add a new set of rows which total by year




Bookstore         SQL302 Module 2             20
Bookstore   SQL302 Module 2   21
Outer Joins
• Left – selects all rows from the left or first table,
  even if no match exists in the other table
      – Widely used in commercial practice
      – Especially useful for reporting
      – Can be slower and interfere with optimizer
• Right – same idea but all rows from right table
• Full – all rows form both tables


Bookstore                 SQL302 Module 2                 22
Left Outer Join

            Basic SQL 92 Syntax:
            Select <column-list>
            From <table1>
            Left join <table2>
            On <join condition>

Bookstore                SQL302 Module 2   23
Left Outer Join
• List all customers with their orders
• Include customers with no orders as well




Bookstore         SQL302 Module 2            24
Left-Join

            Basic Example:
            SELECT customer_first_name,
            customer_street, order_numb,
            order_date
            from customers as c
            left join orders as o
            on c.customer_numb =
            o.customer_numb

Bookstore               SQL302 Module 2    25
Left Join with Results




Bookstore           SQL302 Module 2   26
Negative Left Join
• List all the customers who have not placed
  any orders
• This is an example of a query which finds
  unmatched records




Bookstore         SQL302 Module 2              27
Negative Left-Join (Unmatched)
            Basic Example:
            SELECT customer_first_name,
            customer_last_name, order_numb,
            order_date
            from customers as c
            left join orders as o
            on c.customer_numb =
            o.customer_numb
            Where order_numb is null;
Bookstore               SQL302 Module 2       28
Bookstore   SQL302 Module 2   29
Left Join w/ Partial Match
• List all customers along with any orders
  placed in 1999
• If they did not place 1999 orders we still
  want to include them in the printout




Bookstore             SQL302 Module 2          30
Left Join w/ Partial Match
            Example:
            SELECT customer_first_name,
            customer_last_name, order_numb, order_date
            from customers as c
            Left join
            (select customer_numb, order_numb,
            order_date
                  From orders
                  Where year(order_date) = 1999) as d
            on c.customer_numb = d.customer_numb;


Bookstore                    SQL302 Module 2             31
Own Your Own
• List all books and their order totals for
  1999
• Show the book even if there were no
  orders placed in 1999




Bookstore          SQL302 Module 2            32
Theta Joins
• Theta joins involve inequalities in the
  matching conditions
• Can be used for some interesting queries
  which do not involve the usual primary
  key to foreign key matchings




Bookstore         SQL302 Module 2            33
Theta join
• Find all customers that live at the same address
      – Requires a self join of the customers table on address
        field




Bookstore                  SQL302 Module 2                       34
Theta join results




 • Can be further processed with a union query to
   consolidate names into a single list
Bookstore               SQL302 Module 2             35
SQL302

            SQL Programming

            Part 3– Set Operations


Bookstore         SQL302 Module 2    36
Set Operations
• More on unions
• Intersect
• Except




Bookstore          SQL302 Module 2   37
Unions
• Combines two or more tables
• Tables must be union compatible




Bookstore        SQL302 Module 2    38
Unions

      Select <column-list> from
      <table1>
      Union [ALL]
      Select <same-columns> from
      <table2>



Bookstore           SQL302 Module 2   39
Unions
• Example: consolidate two columns into one
  column




Bookstore          SQL302 Module 2            40
Union consolidation result
• Customers in same city




Bookstore             SQL302 Module 2    41
Unions
• Example: add a total row to a query result
• Code:
            use bookstore;
            select order_numb
                  , sum(quantity) as "Quantity"
                  , sum(cost_line)as "Total Cost"
            from orderlines
            group by order_numb
            union
            select NULL, sum(quantity),
            sum(cost_line)
            from orderlines;
Bookstore                 SQL302 Module 2           42
unions
• Example: add an element to a pick list




Bookstore         SQL302 Module 2          43
intersect
• The intersect operator finds rows in
  common between two tables
• Syntax
    Select <column-list> from <table1>
    intersect
    Select <same-columns> from <table2>



Bookstore         SQL302 Module 2         44
intersect
• Example: find cities in common between
  sources and customers
• Code
    select customer_city, customer_state,
    customer_zip
    from customers
    intersect
    select source_city, source_state,
    source_zip
    from sources; SQL302 Module 2
Bookstore                                   45
Except
• Finds all rows from first table that are not
  found in the second table
• Syntax:
    Select <column-list> from <table1>
    except
    Select <same-columns> from <table2>



Bookstore          SQL302 Module 2               46
except
• Example: find sources that are not located
  in any of our customer’s cities
• Code
    select source_city, source_state,
    source_zip
    from sources
    except
    select customer_city, customer_state,
    customer_zip
    from customers;SQL302 Module 2
Bookstore                                      47
SQL302

             SQL Programming

            Part 4 – Window Functions


Bookstore           SQL302 Module 2     48
Aggregate Functions
•   Count
•   Sum
•   Min
•   Max
•   Avg
•   Often used in conjunction with grouping
    and window functions
Bookstore          SQL302 Module 2            49
Window Functions
• Sort of like grouping, but aggregates can
  be taken along with straight columns in the
  select list
• The function is applied over a window
      – Partition by column
      – Partition by ()



Bookstore              SQL302 Module 2      50
Window Functions

      Basic syntax:

      Select …, window function(column)
             partition by <column>
      From <table>
      where <predicate>



Bookstore             SQL302 Module 2     51
Window Functions
     Example: Show salary along with average for the
     job_title and overall

     Code:
     use employeedb;
     select soc_sec_no,          name, salary
           , SUM(salary)         over(partition
     by job_title_code)          as [Job Code
     Average]
           , SUM(salary)         over() as
     [Average]
     from employees;
Bookstore                SQL302 Module 2               52
Exercise
• List all customers and their orders
      – Name nicely formatted
      – With orders in the year of 1999 (do not use
        between, etc.)
      – Show total order quantities and amounts
      – Only include orders with more than three
        order lines


Bookstore               SQL302 Module 2               53
Notes




Bookstore   SQL302 Module 2   54
Notes




Bookstore   SQL302 Module 2   55

More Related Content

Viewers also liked (20)

PPT
AIN102S Access string function sample queries
Dan D'Urso
 
PDF
Muziekdigitaal Taggerfm Pitch 091027
Tim Rootsaert
 
PPT
Pharma Powerpoint 2
guest4a9aba
 
PDF
GovProjects.org
F R
 
PDF
SQL201W MySQL SQL Manual
Dan D'Urso
 
PPT
eParticipation in The Netherlands
BZK
 
PDF
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
RICK Lin
 
PPT
AVB201.1 MS Access VBA Module 1
guest38bf
 
PDF
Managing Your Career In Tough Times 102308
Joellyn Schwerdlin
 
PPT
KaDouce AutoBio
Karine L
 
PDF
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
Andres Agostini, Future Knowledgist
 
PPTX
Digital Public Records
Ryan Thornburg
 
PDF
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Andres Agostini, Future Knowledgist
 
PDF
我國數位產業學習發展與推動概況
RICK Lin
 
PPT
PREMIS FOTOGRAFIA FILOSOFICA
JAVIER ALSINA GONZALEZ
 
PPT
Preparing Students
Katie Turner
 
PPT
George Washington Teacher’s Institute
moorebl
 
PPTX
Show Your Work: Cheap & Easy Tools for Presenting Data
Ryan Thornburg
 
PDF
My Print Portfolio
beth7865
 
PPT
Test 1
ntawfik
 
AIN102S Access string function sample queries
Dan D'Urso
 
Muziekdigitaal Taggerfm Pitch 091027
Tim Rootsaert
 
Pharma Powerpoint 2
guest4a9aba
 
GovProjects.org
F R
 
SQL201W MySQL SQL Manual
Dan D'Urso
 
eParticipation in The Netherlands
BZK
 
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
RICK Lin
 
AVB201.1 MS Access VBA Module 1
guest38bf
 
Managing Your Career In Tough Times 102308
Joellyn Schwerdlin
 
KaDouce AutoBio
Karine L
 
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
Andres Agostini, Future Knowledgist
 
Digital Public Records
Ryan Thornburg
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Andres Agostini, Future Knowledgist
 
我國數位產業學習發展與推動概況
RICK Lin
 
PREMIS FOTOGRAFIA FILOSOFICA
JAVIER ALSINA GONZALEZ
 
Preparing Students
Katie Turner
 
George Washington Teacher’s Institute
moorebl
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Ryan Thornburg
 
My Print Portfolio
beth7865
 
Test 1
ntawfik
 

Similar to SQL302 Intermediate SQL Workshop 2 (20)

PPT
SQL212.2 Introduction to SQL using Oracle Module 2
Dan D'Urso
 
PPT
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
PPT
SQL200.3 Module 3
Dan D'Urso
 
PPT
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
PDF
SQL202 SQL Server SQL Manual
Dan D'Urso
 
PDF
sql_bootcamp.pdf
John McClane
 
PPT
SQL212.3 Introduction to SQL using Oracle Module 3
Dan D'Urso
 
PDF
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
PDF
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
Frederic Descamps
 
PDF
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
mCloud
 
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
PPT
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
PDF
Introduction to Data Modeling with Apache Cassandra
Luke Tillman
 
PPTX
Implementing Tables and Views.pptx
LuisManuelUrbinaAmad
 
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
PPTX
Developer's Approach to Code Management
Michael Rosenblum
 
PDF
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
MariaDB plc
 
PDF
introduction to big data and data scienece
nehayarrapothu
 
PPTX
U-SQL Intro (SQLBits 2016)
Michael Rys
 
PPTX
Distributed database
NasIr Irshad
 
SQL212.2 Introduction to SQL using Oracle Module 2
Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
SQL200.3 Module 3
Dan D'Urso
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
SQL202 SQL Server SQL Manual
Dan D'Urso
 
sql_bootcamp.pdf
John McClane
 
SQL212.3 Introduction to SQL using Oracle Module 3
Dan D'Urso
 
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
Frederic Descamps
 
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
mCloud
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
Introduction to Data Modeling with Apache Cassandra
Luke Tillman
 
Implementing Tables and Views.pptx
LuisManuelUrbinaAmad
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
Developer's Approach to Code Management
Michael Rosenblum
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
MariaDB plc
 
introduction to big data and data scienece
nehayarrapothu
 
U-SQL Intro (SQLBits 2016)
Michael Rys
 
Distributed database
NasIr Irshad
 
Ad

More from Dan D'Urso (18)

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
 
PPTX
Microsoft access self joins
Dan D'Urso
 
PDF
AIN106 Access Reporting and Analysis
Dan D'Urso
 
PDF
Course Catalog
Dan D'Urso
 
PDF
SQL212 Oracle SQL Manual
Dan D'Urso
 
PDF
AIN100
Dan D'Urso
 
PPT
SQL206 SQL Median
Dan D'Urso
 
PDF
AIN102 Microsoft Access 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
 
PDF
Course Catalog
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
 
Microsoft access self joins
Dan D'Urso
 
AIN106 Access Reporting and Analysis
Dan D'Urso
 
Course Catalog
Dan D'Urso
 
SQL212 Oracle SQL Manual
Dan D'Urso
 
AIN100
Dan D'Urso
 
SQL206 SQL Median
Dan D'Urso
 
AIN102 Microsoft Access 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
 
Course Catalog
Dan D'Urso
 
Ad

Recently uploaded (20)

PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Biography of Daniel Podor.pdf
Daniel Podor
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
July Patch Tuesday
Ivanti
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 

SQL302 Intermediate SQL Workshop 2

  • 1. SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T- SQL Fundamentals by Itzki Ben-gan Workshop 2 – Joins, Set Operations, Window Functions Bookstore SQL302 Module 2 1
  • 2. Note on SQL302 Slides • 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 Oracle, Access, and MySQL slides out into their own slide sets. The SQL302 slides will cover Microsoft SQL Server. Bookstore 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 Bookstore 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-2012All rights reserved. Bookstore SQL302 Module 2 4
  • 5. SQL302 Resources • Bookstore database scripts found on box.net at http://tinyurl.com/SQLScripts • Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases • Follow up questions? [email protected] Bookstore SQL302 Module 2 5
  • 6. Relational Database with constraints (from text) Bookstore SQL302 Module 2 6
  • 7. Sample Employees Database Bookstore2 & SQL204 Module 1 7 Employees
  • 8. More conventions • Names can be surrounded with “ “ or [ ] as in [order details]. • Some of the PowerPoint slides may have this convention. • Better practice is to use an underscore as in order_details. Bookstore SQL302 Module 2 8
  • 9. SQL302 SQL Programming Part 1 – Joins: Natural, Self and Outer Bookstore SQL302 Module 2 9
  • 10. Joins • Inner (Covered in SQL202 course) • Natural Join • Self • Data Warehouse operators • Outer – Left – Right – Full • Cross • Theta • We will cover some of the more advanced or subtle aspects of joins in this class Bookstore SQL302 Module 2 10
  • 11. Natural Joins • Table1 natural join table3 – automatically uses columns with same name • Table 1 natural join table2 using(<column- list> • Not yet available in SQL Server Bookstore SQL302 Module 2 11
  • 12. Correlation Names (Table Aliases) • Can abbreviate references to tables • For example: Select e.name, j.payrange From employees as e Inner join job_information as j On e.jobcode = j.jobcode; Bookstore SQL302 Module 2 12
  • 13. Self Joins • Implements a recursive relationship • Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation names Bookstore SQL302 Module 2 13
  • 14. Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid; Bookstore SQL302 Module 2 14
  • 15. Bookstore SQL302 Module 2 15
  • 16. Datawarehouse clauses • Two keywords that can be added to a grouped query – Rollup – Cube • Places additional summary rows in the result set • Result set is a true relational result set Bookstore SQL302 Module 2 16
  • 17. Rollup • Example: calculate average salaries by job_title_code and manager Bookstore SQL302 Module 2 17
  • 18. Rollup results Bookstore SQL302 Module 2 18
  • 19. cube • Similar to rollup but computes summary rows in all dimensions Bookstore SQL302 Module 2 19
  • 20. Cube results • Add a new set of rows which total by year Bookstore SQL302 Module 2 20
  • 21. Bookstore SQL302 Module 2 21
  • 22. Outer Joins • Left – selects all rows from the left or first table, even if no match exists in the other table – Widely used in commercial practice – Especially useful for reporting – Can be slower and interfere with optimizer • Right – same idea but all rows from right table • Full – all rows form both tables Bookstore SQL302 Module 2 22
  • 23. Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition> Bookstore SQL302 Module 2 23
  • 24. Left Outer Join • List all customers with their orders • Include customers with no orders as well Bookstore SQL302 Module 2 24
  • 25. Left-Join Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numb Bookstore SQL302 Module 2 25
  • 26. Left Join with Results Bookstore SQL302 Module 2 26
  • 27. Negative Left Join • List all the customers who have not placed any orders • This is an example of a query which finds unmatched records Bookstore SQL302 Module 2 27
  • 28. Negative Left-Join (Unmatched) Basic Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numb Where order_numb is null; Bookstore SQL302 Module 2 28
  • 29. Bookstore SQL302 Module 2 29
  • 30. Left Join w/ Partial Match • List all customers along with any orders placed in 1999 • If they did not place 1999 orders we still want to include them in the printout Bookstore SQL302 Module 2 30
  • 31. Left Join w/ Partial Match Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c Left join (select customer_numb, order_numb, order_date From orders Where year(order_date) = 1999) as d on c.customer_numb = d.customer_numb; Bookstore SQL302 Module 2 31
  • 32. Own Your Own • List all books and their order totals for 1999 • Show the book even if there were no orders placed in 1999 Bookstore SQL302 Module 2 32
  • 33. Theta Joins • Theta joins involve inequalities in the matching conditions • Can be used for some interesting queries which do not involve the usual primary key to foreign key matchings Bookstore SQL302 Module 2 33
  • 34. Theta join • Find all customers that live at the same address – Requires a self join of the customers table on address field Bookstore SQL302 Module 2 34
  • 35. Theta join results • Can be further processed with a union query to consolidate names into a single list Bookstore SQL302 Module 2 35
  • 36. SQL302 SQL Programming Part 3– Set Operations Bookstore SQL302 Module 2 36
  • 37. Set Operations • More on unions • Intersect • Except Bookstore SQL302 Module 2 37
  • 38. Unions • Combines two or more tables • Tables must be union compatible Bookstore SQL302 Module 2 38
  • 39. Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2> Bookstore SQL302 Module 2 39
  • 40. Unions • Example: consolidate two columns into one column Bookstore SQL302 Module 2 40
  • 41. Union consolidation result • Customers in same city Bookstore SQL302 Module 2 41
  • 42. Unions • Example: add a total row to a query result • Code: use bookstore; select order_numb , sum(quantity) as "Quantity" , sum(cost_line)as "Total Cost" from orderlines group by order_numb union select NULL, sum(quantity), sum(cost_line) from orderlines; Bookstore SQL302 Module 2 42
  • 43. unions • Example: add an element to a pick list Bookstore SQL302 Module 2 43
  • 44. intersect • The intersect operator finds rows in common between two tables • Syntax Select <column-list> from <table1> intersect Select <same-columns> from <table2> Bookstore SQL302 Module 2 44
  • 45. intersect • Example: find cities in common between sources and customers • Code select customer_city, customer_state, customer_zip from customers intersect select source_city, source_state, source_zip from sources; SQL302 Module 2 Bookstore 45
  • 46. Except • Finds all rows from first table that are not found in the second table • Syntax: Select <column-list> from <table1> except Select <same-columns> from <table2> Bookstore SQL302 Module 2 46
  • 47. except • Example: find sources that are not located in any of our customer’s cities • Code select source_city, source_state, source_zip from sources except select customer_city, customer_state, customer_zip from customers;SQL302 Module 2 Bookstore 47
  • 48. SQL302 SQL Programming Part 4 – Window Functions Bookstore SQL302 Module 2 48
  • 49. Aggregate Functions • Count • Sum • Min • Max • Avg • Often used in conjunction with grouping and window functions Bookstore SQL302 Module 2 49
  • 50. Window Functions • Sort of like grouping, but aggregates can be taken along with straight columns in the select list • The function is applied over a window – Partition by column – Partition by () Bookstore SQL302 Module 2 50
  • 51. Window Functions Basic syntax: Select …, window function(column) partition by <column> From <table> where <predicate> Bookstore SQL302 Module 2 51
  • 52. Window Functions Example: Show salary along with average for the job_title and overall Code: use employeedb; select soc_sec_no, name, salary , SUM(salary) over(partition by job_title_code) as [Job Code Average] , SUM(salary) over() as [Average] from employees; Bookstore SQL302 Module 2 52
  • 53. Exercise • List all customers and their orders – Name nicely formatted – With orders in the year of 1999 (do not use between, etc.) – Show total order quantities and amounts – Only include orders with more than three order lines Bookstore SQL302 Module 2 53
  • 54. Notes Bookstore SQL302 Module 2 54
  • 55. Notes Bookstore SQL302 Module 2 55