Complex Queries in SQL
Complex Queries in SQL
ADVANCED SQL
2
Chapter 7 Copyright © 2014 Pearson Education, Inc.
PROCESSING MULTIPLE TABLES
Join–a relational operation that causes two or more
tables with a common domain to be combined into a
single table or view
Equi-join–a join in which the joining condition is
based on equality between values in the common
columns; common columns appear redundantly in the
result table
Natural join–an equi-join in which one of the
duplicate columns is eliminated in the result table
The common columns in joined tables are usually the primary key
of the dominant table and the foreign key of the dependent table in
1:M relationships
Chapter 7 Copyright © 2014 Pearson Education, Inc.
3
PROCESSING MULTIPLE TABLES
Outer join–a join in which rows that do not have
matching values in common columns are
nonetheless included in the result table (as
opposed to inner join, in which rows must have
matching values in order to appear in the result
table)
Union join–includes all columns from each table
in the join, and an instance for each row of each
table
Self join–Matching rows of a table with other
rows from the same table
Customer ID
appears twice in the
result
An INNER join will only return rows from each table that have
matching rows in the other.
Unlike
INNER join,
this will
include
customer
rows with no
matching
order rows
Four tables
involved in
this join
Join version
Subquery version
Correlated subqueries:
Make use of data from the outer query
Execute once for each row of the outer query
Can use the EXISTS operator
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
Chapter 7 Copyright © 2014 Pearson Education, Inc.
26
UNION QUERIES
Combine the output (union of multiple queries)
together into a single result table
First query
Combine
Second query
42