UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
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
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
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
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
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
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
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
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
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