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

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

Viewers also liked (20)

AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queries
 
Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027
 
Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2
 
GovProjects.org
GovProjects.orgGovProjects.org
GovProjects.org
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL Manual
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The Netherlands
 
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308
 
KaDouce AutoBio
KaDouce AutoBioKaDouce AutoBio
KaDouce AutoBio
 
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public Records
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
 
我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況
 
PREMIS FOTOGRAFIA FILOSOFICA
PREMIS FOTOGRAFIA FILOSOFICAPREMIS FOTOGRAFIA FILOSOFICA
PREMIS FOTOGRAFIA FILOSOFICA
 
Preparing Students
Preparing StudentsPreparing Students
Preparing Students
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institute
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataShow Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting Data
 
My Print Portfolio
My Print PortfolioMy Print Portfolio
My Print Portfolio
 
Test 1
Test 1Test 1
Test 1
 

Similar to SQL302 Intermediate SQL Workshop 2

SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
Dan D'Urso
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
Dan D'Urso
 
sql_bootcamp.pdf
sql_bootcamp.pdfsql_bootcamp.pdf
sql_bootcamp.pdf
John McClane
 
SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3
Dan D'Urso
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
Dan D'Urso
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
Frederic Descamps
 
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgradeDevelopers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
mCloud
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
Dan D'Urso
 
LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with Lucidchart
Dan D'Urso
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache Cassandra
Luke Tillman
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptx
LuisManuelUrbinaAmad
 
Developer's Approach to Code Management
Developer's Approach to Code ManagementDeveloper's Approach to Code Management
Developer's Approach to Code Management
Michael Rosenblum
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
MariaDB plc
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)
Michael Rys
 
Distributed database
Distributed databaseDistributed database
Distributed database
NasIr Irshad
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)
Zohar Elkayam
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2
Kunihisa Abukawa
 

Similar to SQL302 Intermediate SQL Workshop 2 (20)

SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
 
SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
 
sql_bootcamp.pdf
sql_bootcamp.pdfsql_bootcamp.pdf
sql_bootcamp.pdf
 
SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
 
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgradeDevelopers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
 
LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with Lucidchart
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache Cassandra
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptx
 
Developer's Approach to Code Management
Developer's Approach to Code ManagementDeveloper's Approach to Code Management
Developer's Approach to Code Management
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2
 

More from Dan D'Urso

Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
Dan D'Urso
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database Diagramming
Dan D'Urso
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 Accelerated
Dan D'Urso
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic Training
Dan D'Urso
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
Dan D'Urso
 
Stem conference
Stem conferenceStem conference
Stem conference
Dan D'Urso
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joins
Dan D'Urso
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and Analysis
Dan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
Dan D'Urso
 
AIN100
AIN100AIN100
AIN100
Dan D'Urso
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
Dan D'Urso
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access Queries
Dan D'Urso
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
Dan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
Dan D'Urso
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2
Dan D'Urso
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
Dan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
Dan D'Urso
 

More from Dan D'Urso (18)

Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database Diagramming
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 Accelerated
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic Training
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
 
Stem conference
Stem conferenceStem conference
Stem conference
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joins
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and Analysis
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
AIN100
AIN100AIN100
AIN100
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access Queries
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 

Recently uploaded

Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

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 slides.1@dhdursoassociates.com 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? sql.support@dhdursoassociates.com 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