SQL SELECT; Working
With Multiple Tables
JOINs
Sub-queries
VIEWS
2 Logistics
Instructor: Siphy, A. S.
email: dullextz@gmail.com/
abdallah.siphy@ifm.ac.tz
Office: Block D, 020
Consultation Time
BY
Appointment
Intro to SQL, 04/11/2022
3 OVERVIEW
More SELECT statements
JOINs
INNER JOIN
NATURAL JOIN
CROSS JOIN
OUTER JOINS(LEFT/RIGHT/FULL)
SUB-QUERY
CORRELATED
NON-CORRELATED
SQL VIEWS
Intro to SQL,
4 SELECT from Multiple Tables
Often you need to combine If the tables have columns
information from two or more with the same name will
tables
produce ambiguity results
You can get the effect of a
You resolve this by
product by using
referencing columns with
SELECT * FROM Table1, the table name
Table2... TableName.Column
SQL, More Select statements 08-Nov-2016
5 SELECT from Multiple Tables
Student Grade Course
ID First Last ID Code Mark Code Title
S103 John Smith S103 DBS 72 DBS Database Systems
S103 John Smith S103 IAI 58 IAI Intro to AI
S104 Mary Jones S104 PR1 68 PR1 Programming 1
S104 Mary Jones S104 IAI 65 IAI Intro to AI
S106 Mark Jones S106 PR2 43 PR2 Programming 2
S107 John Brown S107 PR1 76 PR1 Programming 1
S107 John Brown S107 PR2 60 PR2 Programming 2
S107 John Brown S107 IAI 35 IAI Intro to AI
Student.ID = Grade.ID Course.Code = Grade.Code
SQL, More Select statements
6 JOINs
JOINs can be used to
A CROSS JOIN B
combine tables returns all pairs of rows from A
There are many types of and B
JOIN
CROSS JOIN A NATURAL JOIN B
INNER JOIN returns pairs of rows with
NATURAL JOIN
common values for identically
named columns and without
OUTER JOIN duplicating columns
OUTER JOINs are linked
with NULL values
A INNER JOIN B
LEFT, RIGHT , & FULL
returns pairs of rows satisfying a
OUT JOIN condition
SQL, More Select statements
7 CROSS JOIN
SELECT * FROM
Student
ID Name
Student CROSS JOIN
123 John Enrolment
124 Mary
125 Mark ID Name ID Code
126 Jane 123 John 123 DBS
124 Mary 123 DBS
Enrolment 125 Mark 123 DBS
ID Code 126 Jane 123 DBS
123 John 124 PRG
123 DBS 124 Mary 124 PRG
124 PRG 125 Mark 124 PRG
124 DBS 126 Jane 124 PRG
126 PRG 123 John 124 DBS
124 Mary 124 DBS
SQL, More Select statements 08-Nov-2016
8 NATURAL JOIN
SELECT * FROM
Student Student NATURAL
ID Name JOIN Enrolment
123 John
124 Mary
125 Mark
126 Jane ID Name Code
Enrolment 123 John DBS
124 Mary PRG
ID Code 124 Mary DBS
123 DBS 126 Jane PRG
124 PRG
124 DBS
126 PRG
SQL, More Select statements 08-Nov-2016
9 CROSS and NATURAL JOIN
SELECT * FROM SELECT * FROM
A NATURAL JOIN B
A CROSS JOIN B
is the same as
is the same as
SELECT A.col1,… A.coln, [and all other
columns apart from B.col1,…B.coln]
SELECT * FROM A, B FROM A, B
, and WHERE A.col1 = B.col1
AND A.col2 = B.col2
Cross-product – ...AND A.coln = B.col.n
relational algebra. (this assumes that col1… coln in A and B
have common names)
SQL, More Select statements 08-Nov-2016
10 INNER JOIN
INNER JOINs specify a Can also use
condition which the
SELECT * FROM
pairs of rows satisfy
A INNER JOIN B
USING
SELECT * FROM (col1, col2,…)
A INNER JOIN B Chooses rows where the
ON <condition> given columns are equal
SQL, More Select statements 08-Nov-2016
INNER JOIN
11
SELECT * FROM
Student Student INNER JOIN
ID Name Enrolment USING (ID)
123 John
124 Mary
125 Mark ID Name ID Code
126 Jane 123 John 123 DBS
Enrolment 124 Mary 124 PRG
124 Mary 124 DBS
ID Code 126 Jane 126 PRG
123 DBS
124 PRG
124 DBS
126 PRG
SQL, More Select statements 08-Nov-2016
12 INNER JOIN
SELECT * FROM
Buyer
Buyer INNER JOIN
Name Budget
Smith 100,000
Property ON
Jones 150,000 Price <= Budget
Green 80,000
Property Name Budget Address Price
Address Price Smith 100,000 15 High St 85,000
Jones 150,000 15 High St 85,000
15 High St 85,000 Jones 150,000 12 Queen St 125,000
12 Queen St 125,000
87 Oak Row 175,000
SQL, More Select statements 08-Nov-2016
13 INNER JOIN
SELECT * FROM SELECT * FROM
A INNER JOIN B
A INNER JOIN B
USING(col1, col2,...)
ON <condition>
is the same as
is the same as
SELECT * FROM A, B
SELECT * FROM A, B WHERE A.col1 = B.col1
AND A.col2 = B.col2
WHERE <condition>
AND ...
SQL, More Select statements
14 Outer Joins
Outer joins include dangles
When we take the join of in the result and use NULLs
two relations we match to fill in the blanks
up tuples which share Three kinds of outer join.
values Left outer join
Some tuples have no Right outer join
match, and are ‘lost’ Full outer join
These are called ‘dangles’
08-Nov-2016
SQL, More Select statements
15 Outer Join Syntax in Oracle
SELECT <cols>
FROM <t1> <type> OUTER JOIN <t2>
ON <condition>
Where <type> is one of LEFT, RIGHT, or FULL
Example:
SELECT *
FROM Student FULL OUTER JOIN Enrolment
ON Student.ID = Enrolment.ID
SQL, More Select statements
16 Example: inner join
Student Enrolment
ID Name ID Code Mark
123 John 123 DBS 60
124 Mary 124 PRG 70
125 Mark 125 DBS 50
DBS 80 dangles
126 Jane 128
ID Name ID Code Mark
123 John 123 DBS 60
124 Mary 124 PRG 70
125 Mark 125 DBS 50
Student inner join Enrolment(SELECT * FROM student
INNER JOIN Enrolment ON student.id=enrloment.id) 08-Nov-2016
SQL, More Select statements
17 Example: Full Outer Join
Student Enrolment
ID Name ID Code Mark
123 John 123 DBS 60
124 Mary 124 PRG 70
125 Mark 125 DBS 50
DBS 80 dangles
126 Jane 128
Includes all
Student full outer join Enrolment
non matched
ID Name ID Code Mark
Values on
123 John 123 DBS 60
124 Mary 124 PRG 70 both tables
125 Mark 125 DBS 50
126 Jane null null null
null null 128 DBS 80
08-Nov-2016
SQL, More Select statements
18 Example: Left Outer Join
Student Enrolment
ID Name ID Code Mark
123 John 123 DBS 60
124 Mary 124 PRG 70
125 Mark 125 DBS 50
DBS 80 dangles
126 Jane 128
Student left outer join Enrolment
ID Name ID Code Mark
123 John 123 DBS 60 Includes all
124 Mary 124 PRG 70
125 Mark 125 DBS 50 non matched
126 Jane null null null Student id,
and name
08-Nov-2016
SQL, More Select statements
19 Example: Right Outer Join
Student Enrolment
ID Name ID Code Mark
123 John 123 DBS 60
124 Mary 124 PRG 70
125 Mark 125 DBS 50
DBS 80 dangles
126 Jane 128
Student right outer join Enrolment
Includes all
ID Name ID Code Mark
123 John 123 DBS 60 non matched
124 Mary 124 PRG 70 Enrolment id,
125 Mark 125 DBS 50
null null 128 DBS 80 code and
mark
08-Nov-2016
SQL, More Select statements
Processing Multiple Tables
20
Using 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:
Non-correlated–executed once for the entire outer query
Correlated–executed once for each row returned by the outer
query
Nested Queries
A sub query is a query nested within another query
The enclosing query also called outer query
Nested query is called inner query
There can be multiple levels of nesting
Example: Schema:
Select movie_title People(person_fname, person_lname,
person_id, person_state,
From movies person_city)
Where director_id IN ( Movies(movie_id, movie_title,
director_id, studio_id)
Select person_id Location(movie_id, city, state)
From People
Where person_state = ‘TX’)
22 Using sub-queries
SELECT select_list FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Nested Queries - Types
Non-Correlated Sub Queries:
Requires data required by outer query before it can be
executed
Inner query does not contain any reference to outer query
Behaves like a function
Steps:
1. Subquery is
Example: executed
Select movie_title, studio_id 2. Subquery results
From Movies are plugged into the
Where director_id IN ( outer query
Select person_id 3. The outer query is
From People processed
Where person_state = ‘TX’)
Nested Queries - Types
Correlated Sub Queries:
Contains reference to the outer query
Behaves like a loop Steps:
• Contents of the table
Example: row in outer query are
People(person_fname, person_lname, person_id, person_state, read
person_city) • Sub-query is
Cast_Movies(cast_member_id, role, movie_id)
executed using data
Select person_fname, person_lname
From People p1
in the row being
Where ‘Pam Green’ in ( processed.
Select role • Results of the inner
From Cast_Movies query are passed to
Where p1.person_id = cast_member_id
) the where in the
outer query
The Outer query is
Processed
Equivalent Join Query
Example:
People(person_fname, person_lname, person_id,
person_state, person_city)
Cast_Movies(cast_member_id, role, movie_id)
Select person_fname, person_lname
From People, Cast_Movies
Where Cast_member_id = person_id
And role = ‘Pam Green’
Examples –consider the schema
below
For each customer who placed an order, what is
the customer’s name and order number?
INNER JOIN clause is an alternative to WHERE clause, and is
used to match primary and foreign keys.
An INNER join will only return rows from each table that have
matching rows in the other.
This query produces same results as previous equi-join example.
For each customer who placed an order,
what is the customer’s name and order
number?
ON clause performs the equality
check for common columns of the
two tables
29
Subquery Example
Show all customers who have placed an order
The IN operator will test to
see if the CUSTOMER_ID
value of a row is included in
the list returned from the
subquery
Subquery is embedded in parentheses. In
this case it returns a list that will be used
in the WHERE clause of the outer query
1)List the customer name, ID number, and order
number for all customers. Include customer
information even for customers that do have an
order.
31
Subquery Example
Show all customers who have placed an order
The IN operator will test to
see if the CUSTOMER_ID
value of a row is included in
the list returned from the
subquery
Subquery is embedded in parentheses. In
this case it returns a list that will be used
in the WHERE clause of the outer query
32
Join vs. Subquery
Some queries could be accomplished by either a join or a subquery
Join version
Subquery version
Figure 7-6 Graphical depiction of two ways to
33
answer a query with different types of joins
Figure 7-6 Graphical depiction of two ways to
34
answer a query with different types of joins
35 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
Figure 7-8a Processing a noncorrelated subquery
36
A noncorrelated subquery processes completely before the outer query begins
Chapter 7 Copyright © 2014 Pearson Education, Inc. 36
37
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 The subquery is testing
refers to an attribute from a table for a value that comes
referenced in the outer query from the outer query
Figure 7-8b
38
Processing a
correlated Subquery refers to outer-
subquery 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
Chapter 7 Copyright © 2014 Pearson Education, Inc. 38
39
Another Subquery Example
Show all products whose standard price is
higher than the average price
One column of the subquery is
Subquery forms the an aggregate function that has
derived table used in the an alias name. That alias can
FROM clause of the outer
then be referred to in the outer
query
query
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
40
Union Queries
Combine the output (union of multiple
queries) together into a single result table
First query
Combine
Second query
Figure 7-9 Combining queries using UNION
41
Note: with UNION
queries, the
quantity and data
types of the
attributes in the
SELECT clauses
of both queries
must be identical
Chapter 7 Copyright © 2014 Pearson Education, Inc. 41
42
Tips for Developing Queries
Be familiar with the data model (entities
and relationships)
Understand the desired results
Know the attributes desired in result
Identify the entities that contain desired
attributes
Review ERD
Construct a WHERE equality for each
link
Fine tune with GROUP BY and HAVING
clauses if needed
Consider the effect on unusual data
Defining Views
Views are relations, except that they are not physically stored.
They are used mostly in order to simplify complex queries and
to define conceptually different views of the database to
different classes of users.
Employee(ssn, name, department, project, salary)
CREATE
CREATEVIEW
VIEW Developers
DevelopersASAS
SELECT
SELECTname,
name,project
project
FROM
FROM Employee
Employee
WHERE
WHEREdepartment
department==‘Development’
‘Development’
44 Example
Purchase(customer, product, store)
Product(pname, price)
CREATE
CREATE VIEW
VIEW CustomerPrice
CustomerPrice AS AS
SELECT
SELECT x.customer,
x.customer, y.price
y.price
FROM
FROM Purchase
Purchase x,
x, Product
Product yy
WHERE
WHERE x.product
x.product == y.pname
y.pname
CustomerPrice(customer, price) “virtual table”
45
Purchase(customer, product, store)
Product(pname, price)
CustomerPrice(customer, price)
We can later use the view:
SELECT
SELECT u.customer,
u.customer, v.store
v.store
FROM
FROM CustomerPrice
CustomerPrice u, u, Purchase
Purchase vv
WHERE
WHERE u.customer
u.customer == v.customer
v.customer AND
AND
u.price
u.price >> 100
100
46 Types of Views
We discuss
Virtual views: only virtual
Used in databases views in class
Computed only on-demand – slow at runtime
Always up-to-date
Materialized views
Used in data warehouses
Pre-computed offline – fast at runtime
May have stale data
47 Queries Over Views:
Query Modification
CREATE
CREATE VIEW
VIEW CustomerPrice
CustomerPrice AS AS
View: SELECT
SELECT x.customer,
x.customer, y.price
y.price
FROM
FROM Purchase
Purchase x,
x, Product
Product yy
WHERE
WHERE x.product
x.product == y.pname
y.pname
SELECT
SELECT u.customer,
u.customer, v.store
v.store
Query: FROM
FROM CustomerPrice
CustomerPrice u, u, Purchase
Purchase vv
WHERE
WHERE u.customer
u.customer == v.customer
v.customer AND
AND
u.price
u.price >> 100
100
48 Queries Over Views:
Query Modification
Modified query:
SELECT
SELECT u.customer,
u.customer, v.store
v.store
FROM
FROM (SELECT
(SELECT x.customer,
x.customer, y.price
y.price
FROM
FROM Purchase
Purchase x,x, Product
Product yy
WHERE
WHERE x.product
x.product == y.pname)
y.pname) u,
u, Purchase
Purchase v)
v)
WHERE
WHERE u.customer
u.customer == v.customer
v.customer ANDAND
u.price
u.price >> 100
100
49 Queries Over Views:
Query Modification
Modified and rewritten query:
SELECT
SELECT x.customer,
x.customer, v.store
v.store
FROM
FROM Purchase
Purchase x,x, Product
Product y,
y, Purchase
Purchase v,
v,
WHERE
WHERE x.customer
x.customer == v.customer
v.customer AND
AND
y.price
y.price >> 100
100 AND
AND
x.product
x.product == y.pname
y.pname
50 But What About This ?
SELECT
SELECT DISTINCT
DISTINCT u.customer,
u.customer, v.store
v.store
FROM
FROM CustomerPrice
CustomerPrice u, u, Purchase
Purchase vv
WHERE
WHERE u.customer
u.customer == v.customer
v.customer AND
AND
u.price
u.price >> 100
100
??
51 Answer
SELECT
SELECT DISTINCT
DISTINCT u.customer,
u.customer, v.store
v.store
FROM
FROM CustomerPrice
CustomerPrice u, u, Purchase
Purchase vv
WHERE
WHERE u.customer
u.customer == v.customer
v.customer AND
AND
u.price
u.price >> 100
100
SELECT
SELECT DISTINCT
DISTINCT x.customer,
x.customer, v.store
v.store
FROM
FROM Purchase
Purchase x,x, Product
Product y,
y, Purchase
Purchase v,
v,
WHERE
WHERE x.customer
x.customer == v.customer
v.customer AND
AND
y.price
y.price >> 100
100 AND
AND
x.product
x.product == y.pname
y.pname
52 Applications of Virtual Views
Logical data independence:
Vertical data partitioning
Horizontal data partitioning
Security
Table (view) V reveals only what the users are
allowed to know