You are on page 1of 43

Advanced SQL

Modern Database Management


12th Edition
Jeffrey A. Hoffer, V. Ramesh,
Heikki Topi
4. Multiple Table Joins

Total of 68
Rows

Total of 69
Rows
4. Multiple Table Joins - Multiple types of joins

• Select only those customers that have placed an order


• Include Orders that have no order detail
5. Self-Join Example

The same table is used on


both sides of the join;
distinguished using table
aliases
Multiple Tables with Subqueries
• Subquery: placing an inner query (SELECT statement) inside an
outer query

• Options:
• In a condition of the WHERE clause
• As a “table” of the FROM clause
• Within the HAVING clause

• Subqueries can be:


• Noncorrelated–executed once for the entire outer query
• Correlated–executed once for each row returned by the outer query
Quiz - Answer
Some queries could be accomplished by either a join or a
subquery

Join version

Same Result Subquery version

Notice that if you wanted to select the


OrderID, you would have to use the
join version!
Example 2 Query
• Find courses offered in Fall 2009 but not in Spring 2010
Example 2 Query
• Find courses offered in Fall 2009 but not in Spring 2010
select distinct course_id
from section
where semester = ’Fall’
and year = 2009
and course_id not in (select course_id
from section
where semester = ’Spring’ and year= 2010);
Quiz
• Find the orders for the Items created by the artist ‘Umami’
Quiz

Same as:
Correlated vs. Noncorrelated Subqueries

• Noncorrelated subqueries:
• Do not depend on data from the outer query
• Execute once for the entire outer query

• Correlated subqueries:
• Make use of data from the outer query
• Execute once for each row of the outer query
• Can use the EXISTS operator
Processing a noncorrelated subquery

A noncorrelated subquery processes completely before the outer query begins.


© 2013 Pearson Education, Inc. Publishing as Prentice Hall
Correlated Subquery Example
• Show all orders that include furniture finished in natural
ash.
The EXISTS operator will return a
TRUE value if the subquery resulted
in a non-empty set, otherwise it
returns a FALSE

 A correlated subquery always refers to The subquery is testing


an attribute from a table referenced in for a value that comes
the outer query from the outer query
Processing a
correlated
subquery
Subquery refers to outer-
query data, so executes once
for each row of outer query

Note: Only the


orders that
involve products
with Natural
Ash will be
included in the
final results.

© 2013 Pearson Education, Inc. Publishing as Prentice Hall


Quiz
• Find the orders from customers whose First Name starts with ‘J’ using
a) WHERE EXISTS b) INNER JOIN
Quiz – Answer

Same as:
Another Subquery Example
• Show all products whose standard price is higher than the average price
• We now use the subquery in the FROM clause

Data: Query Results:


Another Subquery Example

• First the inner query is executed:

Data: Inner - Query Result:

The WHERE clause normally cannot include


aggregate functions, but because the
aggregation is performed in the subquery its
result can be used in the outer query’s
WHERE clause.
UNION – UNION ALL

 UNION selects only distinct values

 To allow duplicate values, use the ALL keyword


UNION EXAMPLE
• Find the cities in which you have either customers or suppliers:

How many rows will each statement return?


UNION EXAMPLE
• Find the cities in which you have either customers or suppliers:

How many rows will each statement return?

5 6
UNION EXAMPLE
• Find the cities in which you have either customers or suppliers:

How many rows and columns will this statement return?

SELECT c.City, s.City


FROM Customers c, suppliers s;
UNION – UNION ALL
• A more complicated example:

First query

Combine

Second query
UNION – UNION ALL
• A more complicated example:

Note: With
UNION queries,
the quantity and
data types of the
attributes in the
SELECT clauses
of both queries
must be identical.
Conditional Expressions Using Case Syntax
• This is the way to build statements of the form: if … then …
Conditional Expressions Using Case Syntax

SELECT ProductNumber, Category = CASE ProductLine


WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END, Name
FROM Production.Product
ORDER BY ProductNumber;

SELECT ProductNumber, Name, "Price Range" = CASE


WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >=50 and ListPrice <250 THEN 'Under $250'
WHEN ListPrice >=250 and ListPrice <1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
Tips for Developing Queries
• Be familiar with the data model (entities and relationships)
• Review ERD
• Understand the desired results
• Know the attributes desired in results
• Identify the entities that contain desired attributes
Example: CustomersIds are usually stored in Customer_T but the customers who have placed orders
can be found by the CustomerID in Order_T

• Fine tune your query


• Construct a WHERE equality for each link
• Use GROUP BY and HAVING clauses if needed
• Consider the effect on unusual data
Example: Use functions like NVL() when dealing with NULL values
Tips for Debugging
If an SQL query runs, it doesn’t mean it is correct!

• Consider the effect on unusual data

• Always check by hand

• Start with the subquery that is nested most deeply

• When its results are correct, use that tested subset to test the outer
query…

• And if your query doesn’t run, learn how to read the errors…
• Examples on Joins
Example
Color Brand Car
Model

Find: The IDs of all the sports cars


Example
Color Brand Car
Model

Find: The IDs of all the sports cars

Ok now you have all the cars


Example
Color Brand Car
Model

Find: The IDs of all the sports cars

And in a different syntax, using alias


Example
Color Brand Car
Model

Find: The IDs of all the sports cars

And now you have only the sports cars


Example
Color Brand Car
Model

Find: The IDs and the colors of all the sports cars
Example
Color Brand Car
Model

Find: The IDs of all the sports cars

You have the colors of the sports cars


Example
Color Brand Car
Model

How many rows will the following statement return?


Example
Color Brand Car
Model

How many rows will the following statement return?

Answer is 40!
Example
Color Brand Car
Model

A count of each brand we carry and the number of cars in it


Example
Color Brand Car
Model

A count of each brand we carry and the number of cars in it

The brands joined with CARS


Example
Color Brand Car
Model

A count of each brand we carry and the number of cars in it

The brands joined with CARS, including


those that do not exist in cars
Example
Color Brand Car
Model

A count of each brand we carry and the number of cars in it

And now the counts


Example
Color Brand Car
Model

A count of each brand and color


Example
Color Brand Car
Model

A count of each brand and color

And now the counts

You might also like