CSE301 Lec7
CSE301 Lec7
Define terms
CHAPTER 7: Write single and multiple table SQL queries
ADVANCED SQL Define and use three types of joins
5 6
Customer ID
appears twice in the
result
7 8
EQUI-JOIN EXAMPLE – ALTERNATIVE NATURAL JOIN EXAMPLE
SYNTAX For each customer who placed an order, what is the
customer’s name and order number?
Join involves multiple tables in FROM clause
An INNER join will only return rows from each table that have ON clause performs the equality Note: from Fig. 7-1, you see that only
matching rows in the other. 10 Customers have links with orders
check for common columns of the
two tables Only 10 rows will be returned from
This query produces same results as previous equi-join example. this INNER join
9 10
11 12
MULTIPLE TABLE JOIN EXAMPLE Figure 7-4 Results from a four-table join (edited for readability)
Assemble all information necessary to create an invoice for order
number 1006 From CUSTOMER_T table
Four tables
involved in
this join
14
SELF-JOIN EXAMPLE
Figure 7-5 Example of a self-join
17 18
Join version
Subquery version
19 20
Figure 7-6 Graphical depiction of two ways to
answer a query with different types of joins 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
21 22
The WHERE clause normally cannot include aggregate functions, but because
the aggregate is performed in the subquery its result can be used in the outer
query’s WHERE clause
25 26
Second query
27 28
TIPS FOR DEVELOPING QUERIES QUERY EFFICIENCY CONSIDERATIONS
Be familiar with the data model (entities and
relationships) Instead of SELECT *, identify the specific
Understand the desired results attributes in the SELECT clause; this helps
Know the attributes desired in result reduce network traffic of result set
Identify the entities that contain desired Limit the number of subqueries; try to make
attributes
everything done in a single query if possible
Review ERD
If data is to be used many times, make a
Construct a WHERE equality for each link
Fine tune with GROUP BY and HAVING clauses
separate query and store it as a view
if needed
Consider the effect on unusual data
29 30
33 34
37 38
39 40
REASONS TO EMBED SQL IN 3GL
41