sql212.2 introduction to sql using oracle module 2
DESCRIPTION
Joins, Subqueries, Unions, Calculations and GroupingTRANSCRIPT
Bookstore2 SQL212 Module 2 1
SQL212
SQL Programming
Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping
Bookstore2 SQL212 Module 2 2
SQL212 Contact Information
P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://[email protected]
Copyright 2001-2009. All rights reserved.
Bookstore2 SQL212 Module 2 3
SQL212
SQL Programming
Part 1 – Joins, Subqueries
Bookstore2 SQL212 Module 2 4
Relational Database with constraints (from text)
Bookstore2 SQL212 Module 2 5
Warning!
• Some slides may show queries using a table called…
Order_filled
• The current database uses a better name…
Orders
Construct your queries with this latter table name
Bookstore2 SQL212 Module 2 6
Joins
• Inner• Outer
– Left– Right– Full
• Cross• Self• Theta• We will cover the most important; others as time
and interest permit
Bookstore2 SQL212 Module 2 7
Inner Join
• Pairs each row from first table with corresponding row from second table over the “join column”
• The result set only contains rows where there is a match over the join column in both tables
• Equi-join is the common inner join
Bookstore2 SQL212 Module 2 8
Inner Join
Older Syntax:
Select <column-list>
From <tablelist>
Where <predicate>
Still very commonly used
Inner Join Examples
• Show customers and their orders
• Join the customers table to the orders table where the customer number in each table matches
Bookstore2 SQL212 Module 2 9
Bookstore2 SQL212 Module 2 10
Inner Join
Example using older syntax:
SELECT customer_first_name, customer_street, order_numb, order_date
from customers, orders
Where customers.customer_numb = orders.customer_numb
Bookstore2 SQL212 Module 2 11
Inner Join with Result
Bookstore2 SQL212 Module 2 12
Inner Join (New Syntax)
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Inner join <table2>
On <join condition>
Bookstore2 SQL212 Module 2 13
Inner Join
Basic Example:
SELECT customer_first_name, customer_street, order_numb, order_date
from customers
inner join orders
on customers.customer_numb = orders.customer_numb
Bookstore2 SQL212 Module 2 14
Inner Join with Result
Bookstore2 SQL212 Module 2 15
Inner Join over Multiple columns
• Note that that the join condition can apply to multiple columns if desired
• Used with composite keys
Bookstore2 SQL212 Module 2 16
Inner Join Result in MS Access
Bookstore2 SQL212 Module 2 17
Inner Join
• In the last example…– What was the cardinality of the relationship
between customers and orders?– Which table was the parent?– What was it’s primary key?– In which table did we employ a foreign key
and what was it?
Bookstore2 SQL212 Module 2 18
Cross Join
• What happens when you omit a join expression?
• Get the cartesian product of the tables – all possible combinations of the two tables
• For large tables this will run a long time!
Dual
• Sometimes we want to generate an expression without actually referring to a real table.
• A trivial example would show the date.
• Oracle has a 1 row, 1 column built in table called Dual to handle this.
• Ex: select sysdate from dual;
Bookstore2 SQL212 Module 2 19
Bookstore2 SQL212 Module 2 20
Cross Join Result Set in MS Access
Bookstore2 SQL212 Module 2 21
Additional SQL92 Syntax
• Table1 natural join table2 – automatically uses columns with same name
• Table1 natural join table2 using(<column-list>)
• Not yet widely available in commercial implementations
Natural Join
Bookstore2 SQL212 Module 2 22
Bookstore2 SQL212 Module 2 23
Joining More than Two Tables
• Can join several tables in one select• Try to limit to three or four• Join order can be important for
performance (although optimizers will usually handle this for you)
• Use parentheses to force order of evaluation (also vendor extensions, often called “hints”)
Bookstore2 SQL212 Module 2 24
Joining More than Two Tables
• Add orderlines detail to previous queries
SELECT customer_first_name, customer_street, orders.order_numb, orders.order_date, orderlines.isbn, orderlines.quantity
FROM customers
INNER JOIN orders ON
customers.customer_numb=orders.customer_numb
INNER JOIN orderlines
on orders.order_numb = orderlines.order_numb
Bookstore2 SQL212 Module 2 25
Multi-table Join with Results
Bookstore2 SQL212 Module 2 26
MS Access Multi-table Join Result Set
Own Your Own
• Add the book title to the previous query
Bookstore2 SQL212 Module 2 27
Bookstore2 SQL212 Module 2 28
Sample Database
• Before we continue (Access classes only)…
• Create a new employees table
Bookstore2 SQL212 Module 2 29
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;
Bookstore2 SQL212 Module 2 30
Self Joins
• Implements a recursive relationship
• Important in various applications– Parts lists/assemblies– HR– Etc.– Table joined to itself using correlation names
Bookstore2 SQL212 Module 2 31
Self Joins
SELECT e.*, m.name
FROM employees AS e, employees AS m
WHERE e.managerid = m.employeeid;
Bookstore2 SQL212 Module 2 32
Bookstore2 SQL212 Module 2 33
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
Bookstore2 SQL212 Module 2 34
Left Outer Join
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Left [outer] join <table2>
On <join condition>
Outer Join Example
• Show all customers and their orders.
• Include customers with no orders as well.
Bookstore2 SQL212 Module 2 35
Bookstore2 SQL212 Module 2 36
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
Bookstore2 SQL212 Module 2 37
Bookstore2 SQL212 Module 2 38
Left Join with Results
Bookstore2 SQL212 Module 2 39
SQL200
SQL Programming
Part 2– Subqueries, Unions
Bookstore2 SQL212 Module 2 40
Subqueries
• One select statement embedded in another.• Can be paced in select list, from clause or
where clause.– We will study the latter in this class
• Can be nested multiple levels deep• Two types:
– Uncorrelated – executes inner query then outer– Correlated – executes inner query once for each outer
query row
Subquery Example
• Show all the orderline information for orders places in 1999
• Note that orderlines table does not have order date. Thus must filter on a different table (orders).
Bookstore2 SQL212 Module 2 41
Bookstore2 SQL212 Module 2 42
Uncorrelated Subquery
select isbn, quantity
from orderlines ol
where ol.order_numb in
(select o.order_numb from orders o where order_date between ‘1-JAN-99’ and ’31-DEC-99’)
Bookstore2 SQL212 Module 2 43
Uncorrelated Subquery with Results
Bookstore2 SQL212 Module 2 44
Negative Subquery
• A type of subquery that matches “not found” conditions
Bookstore2 SQL212 Module 2 45
Negative Subquery
select isbn, quantity
from orderlines ol
where ol.order_numb not in
(select o.order_numb from orders o where order_date between ‘1-JAN-99’ and 31-DEC-99’)
Bookstore2 SQL212 Module 2 46
Negative Subquery with Results
Bookstore2 SQL212 Module 2 47
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
Bookstore2 SQL212 Module 2 48
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-JAN-99’ and ‘31-DEC-99’);
This type of query covered in intermediate SQL class
Bookstore2 SQL212 Module 2 49
Unions
• Combines two tables
• Tables must be union compatible
• Uses:– Combine current tables with history– Combine information from tables with no
common join column
Bookstore2 SQL212 Module 2 50
Unions
Select <column-list> from <table1>
Union [ALL]
Select <same-columns> from <table2>
Union Example
• Create a mailing list of customers and sources
• Use a union of the two tables, making sure the columns match
Bookstore2 SQL212 Module 2 51
Bookstore2 SQL212 Module 2 52
Unions
Union Results
Bookstore2 SQL212 Module 2 53
Bookstore2 SQL212 Module 2 54
SQL200
SQL Programming
Part 3 – Calculations, Aggregates
Bookstore2 SQL212 Module 2 55
Calculated Fields
• Can add a column calculated from others
SELECT order_numb, quantity, cost_each, quantity*cost_each as extension
FROM orderlines
Bookstore2 SQL212 Module 2 56
Calculated field in the Result
Bookstore2 SQL212 Module 2 57
Bookstore2 SQL212 Module 2 58
String Manipulation
• Concatenation
• Trim
• Substring
• Upper, Lower
• Etc. (various vendor extensions)
Bookstore2 SQL212 Module 2 59
Concatenation
• Used for concatenated keys
• Useful to format reports
Basic syntax:
(Oracle, std) Field1 || Field2
Bookstore2 SQL212 Module 2 60
Concatenation
select customer_first_name
|| ‘ ‘ || trim(customer_last_name)
as Name
from customers
Bookstore2 SQL212 Module 2 61
Bookstore2 SQL212 Module 2 62
Date Functions
• Numerous date functions• Often vendor specific• Often used:
– Take the year of a date– Take the month of a date– Add a month (not 30 days)– Etc.
Bookstore2 SQL212 Module 2 63
Aggregate Functions
• Count
• Sum
• Min
• Max
• Avg
• Often used in conjunction with grouping
Bookstore2 SQL212 Module 2 64
Aggregate Functions
Basic syntax:
Select <function>(<column>)From <table>Group by <column-list>Having <predicate>
Group by all columns to left of one(s) you want to aggregate
Bookstore2 SQL212 Module 2 65
Aggregate Functions
SELECT orderlines.order_numb, Count(*) AS “Number of Order Lines” , Sum(orderlines.quantity) AS SumOfquantity, Sum(quantity * cost_each) AS extension
FROM orderlines
GROUP BY orderlines.order_numb
having count(*) > 1
Bookstore2 SQL212 Module 2 66
Bookstore2 SQL212 Module 2 67
Having vs. Where
• Having and Where clauses are similar but not the same
• Having removes groups after they are formed
• Where removes rows before groups are formed
Bookstore2 SQL212 Module 2 68
Exercise
• List all customers and their orders– Name nicely formatted– With orders in the year of 1999– Show total order quantities and amounts– Only include orders with more than three
order lines
Bookstore2 SQL212 Module 2 69
Exercise Result
[end module]
Notes
Bookstore2 SQL212 Module 2 70
Notes
Bookstore2 SQL212 Module 2 71
Notes
Bookstore2 SQL212 Module 2 72