SlideShare a Scribd company logo
1 of 56
Introduction to Databases
Autumn 2022
Egyptian Russian University IS201 IS201: Database Systems 1
Egyptian Russian University
IS201: Database Systems
Dr. Nermeen Kamel
SQL – Basics
(More Practice)
© Praphamontripong
IS201
Database Systems
Consider sample data of an Orders table. How many days elapsed
between the order date and the ship date for each order?
Orders
Example 1: Translate
and Clean Up
Select the order number,
order date, ship date,
ship date minus order
as DaysElapsed from the
Orders table
Select the order number,
order date, ship date,
ship date minus order as
DaysElapsed from the
Orders table
© Praphamontripong
Example 1: Translate and Clean Up
SELECT OrderNumber,
OrderDate, ShipDate,
(ShipDate - OrderDate)
AS DaysElapsed
FROM Orders;
Select the order number,
order date, ship date, ship
date minus order as
DaysElapsed from the Orders
table
Note: rename the column header
© Praphamontripong
Consider sample data of an Orders table. Show me a list of orders
made by each customer in descending date order
Orders
Example 2: Translate and Clean Up
Select the customer ID, order
number, order date, ship date, from
the Orders table for each customer
and then sort by customer and
descending order date
Select the customer ID, order
number, order date, ship date, from
the Orders table for each customer
group by customer ID and then sort
by customer order by customer ID
and descending order date desc
© Praphamontripong
Example 2: Translate and Clean Up
Select the customer ID, order
number, order date, ship date, from
the Orders table for each customer
group by customer ID and then sort
by customer order by customer ID
and descending order date desc
SELECT CustomerID,
OrderNumber, OrderDate,
ShipDate
FROM Orders
GROUP BY CustomerID,
OrderNumber
ORDER BY CustomerID,
OrderDate DESC;
Note: Several DBMS requires that everything in “ORDER BY” must be in “GROUP BY” and everything in
“GROUP BY” must be in “SELECT.” (MySQL doesn’t seem to enforce these requirements)
© Praphamontripong
Find Courses that Minnie is a TA. Also, list all S_id who takes those
courses
SELECT S_id, Course FROM Student_lecture AS S
WHERE S.Teaching_assistant = “Minnie” ;
Student_lecture
S_id Address Course Teaching_assistant
1234 57 Hockanum Blvd Database Systems Minnie
2345 1400 E. Bellows Database Systems Humpty
3456 900 S. Detroit Cloud Computing Dumpty
1234 57 Hockanum Blvd Web Programming Lang. Mickey
5678 2131 Forest Lake Ln. Software Analysis Minnie
Recap 1: SELECT .. FROM .. WHERE
For each row in S:
if (row.Teaching_assistant = ”Minnie”:
output (row.S_id, row.Course)
FROM
Open an iterator
1
WHERE
Filter each row
2
SELECT
output selected attributes
3
© Praphamontripong
Recap 2: SELECT .. FROM .. WHERE
Find all S_id who is taking Database Systems and have Humpty as a TA
Student_lecture
S_id Address Course Teaching_assistant
1234 57 Hockanum Blvd Database Systems Minnie
2345 1400 E. Bellows Database Systems Humpty
3456 900 S. Detroit Cloud Computing Dumpty
1234 57 Hockanum Blvd Web Programming Lang. Mickey
5678 2131 Forest Lake Ln. Software Analysis Minnie
SELECT S_id FROM Student_lecture AS S
WHERE S.Course = “Database Systems” AND
S.Teaching_assistant = “Humpty” ;
S_id
2345
© Praphamontripong
Recap 3: SELECT .. FROM .. WHERE
hiring
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
List all names of TAs and the number of hours the TAs work per
week, rename the hours as “Hours_per_week”
SELECT Name, two_week_hours/2 AS Hours_per_week
FROM hiring
© Praphamontripong
Name Hours_per_week
Minnie 10
Humpty 12
Dumpty 15
Minnie 6
Mickey 8
Recap 4: SELECT .. FROM .. WHERE
List all years
hiring
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
SELECT Year
FROM hiring
Year
4
3
4
3
2
Duplicates
may occur in output
of an operator
© Praphamontripong
Recap 5: SELECT .. FROM .. WHERE
hiring
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
List all years the TAs are in. If multiple TAs are in the same year,
list the year only once
SELECT DISTINCT Year
FROM hiring
© Praphamontripong
Year
4
3
2
Recap 6: SELECT .. FROM .. WHERE
hiring
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
List all names of TAs and the number of hours the TAs work per
week, rename the hours as “Hours_per_week”, then order the
result set by names and then Hours_per_week
SELECT Name, two_week_hours/2 AS Hours_per_week
FROM hiring
ORDER BY Name, Hours_per_week
© Praphamontripong
Name Hours_per_week
Dumpty 15
Humpty 12
Mickey 8
Minnie 6
Minnie 10
SQL – Aggregates
© Praphamontripong
[A. Silberschatz, H. F
. Korth, S. Sudarshan, Database System Concepts, Ch.3.7 and Ch. 5.5]
[C.M. Ricardo, S.D. Urban, Databases Illuminated, Ch. 5.4]
Aggregation Functions
© Praphamontripong
Calculate a value across an entire set or across groups of
rows within the set
SQL uses five aggregation operators:
• SUM – produces the sum of a column with numerical values
• AVG – produces the average of a column with numerical values
• MIN – applied to a column with numerical values, produces the
smallest value
• MAX – applied to a column with numerical values, produces the
largest value
• COUNT – produces the number of (not necessarily distinct)
values in a column
Example: SUM
Given the loan schema
loan(loan_number, branch_name, amount)
The sum of the amounts of all loans is expressed by
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
SUM(amount)
8700
Total
© Praphamontripong
8700
SELECT SUM(amount)
FROM loan
SELECT SUM(amount) AS Total
FROM loan
Example: AVG
Given the loan schema
loan(loan_number, branch_name, amount)
The average of the amounts of all loans is expressed by
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
AVG(amount)
© Praphamontripong
1242.857142857143
SELECT AVG(amount)
FROM loan
Example: MIN
Given the loan schema
loan(loan_number, branch_name, amount)
The smallest amount of loans is expressed by
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
min(amount)
© Praphamontripong
500
SELECT MIN(amount)
FROM loan
Example: MAX
Given the loan schema
loan(loan_number, branch_name, amount)
The largest amount of loans is expressed by
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
max(amount)
© Praphamontripong
2000
SELECT MAX(amount)
FROM loan
Example: COUNT
Given the loan schema
loan(loan_number, branch_name, amount)
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
count(*)
7
Count(loan_number)
7
Count the number of tuples in the loan table
SELECT count(*) SELECT count(loan_number)
FROM loan FROM loan
Count
© Praphamontripong
rows
Count values
of a specified
column
Example: COUNT .. DISTINCT
Given the loan schema
loan(loan_number, branch_name, amount)
Count the number of values in the branch_name column
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
count(branch_name)
7
count(distinct branch_name)
© Praphamontripong
5
SELECT count(branch_name)
FROM loan
SELECT count(DISTINCT branch_name)
FROM loan
Aggregation: Order of Actions
1. The FROM clause generates the data set
2. The WHERE clause filters the data set generated by the FROM clause
3. The GROUP BY clause aggregates the data set that was filtered by
the WHERE clause (note: GROUP BY does not sort the result set)
4. The HAVING clause filters the data set that was aggregated by the
GROUP BY clause
5. The SELECT clause transforms the filtered aggregated data set
6. The ORDER BY clause sorts the transformed data set
SELECT select_list
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
Order matter
© Praphamontripong
Grouping Requirement
Several DBMS requires that the columns appear in the SELECT
clause that are not used in an aggregation function must appear
in the GROUP BY clause
SELECT column_A, column_B, some_aggregation_function
FROM table_source
GROUP BY column_A, column_B
SELECT column_A, column_B, some_aggregation_function
FROM table_source
GROUP BY column_B
© Praphamontripong
Example: SUM with GROUP BY
© Praphamontripong
Given the loan schema
loan(loan_number, branch_name, amount)
The sum of the amounts of all loans for each branch is
expressed by
loan_number branch_name amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
branch_name SUM(amount)
Downtown 2500
Mianus 500
Perryridge 2800
Redwood 2000
Round Hill 900
SELECT branch_name, SUM(amount)
FROM loan
GROUP BY branch_name;
Grouping, Aggregation, and Null
© Praphamontripong
• The value NULL is ignored in any aggregation
• Not contribute to a sum, average, or count of an attribute
• Cannot be the minimum or maximum in its column
• Null is treated as an ordinary value when forming groups
• Can have a group with NULL attribute(s)
• When performing any aggregation except count over an
empty bag of values, the result is NULL
• The count of an empty bag is 0
HAVING
Clauses
© Praphamontripong
• An aggregation in a HAVING clause applies only to the
tuples of the group being tested – filter groups
• Any attributes of relations in the FROM clause may be
aggregated in the HAVING clause
• But only those attributes that are in the GROUP BY list
may appear unaggregated in the having clause
branch_name SUM(amount)
Downtown 2500
Perryridge 2800
The sum of the amounts of all loans for each branch that has
more than one loan is expressed by
SELECT branch_name, sum(amount)
FROM loan
GROUP BY branch_name
HAVING COUNT(branch_name) > 1;
Example 1
List the number of customers in each country. Only include
countries with more than 10 customers
count(id) Country
11 France
11 Germany
13 USA
SELECT count(id), country
FROM Customer
GROUP BY country
HAVING COUNT(id) > 10;
© Praphamontripong
Example 2
List the number of customers in each country, except USA,
sorted high to low. Only include countries with 9 or more
customers
count(id) Country
11 France
11 Germany
9 Brazil
SELECT COUNT(id), country
Customer
country <> “USA”
FROM
WHERE
GROUP BY country
HAVING
ORDER BY COUNT(id)
COUNT(id) >= 9
DESC;
© Praphamontripong
Final Notes about
Aggregation
© Praphamontripong
#1: Keep the GROUP BY clause small and precise
• Several DBMSs require that all non-aggregated columns must
be in the GROUP BY clause
• Excessive columns in GROUP BY can negatively impact the
query’s performance; make the query hard to read,
understand, rewrite
• For queries that need both aggregations and details, do all
aggregations in subqueries first, then join those to the tables to
retrieve the details
Final Notes about
Aggregation
© Praphamontripong
#2: COUNT(*) and COUNT(<column_name>) are different
• COUNT(*) – count all rows, including ones with null values
• COUNT(<column_name>) – count only the rows where the
column value is not NULL
• Sometimes, dividing a query into subqueies can be more
efficient than using a GROUP BY.
Final Notes about Aggregation
© Praphamontripong
#3: Use DISTINCT to get distinct counts
• COUNT(*) – returns the number of rows in a group, including
NULL value and duplicates
• COUNT(<column_name>) – returns the number of rows where
the column value is not NULL
• COUNT(DISTINCT <column_name>) – returns the number of
rows with unique, non-null values of the column
Wrap-Up
© Praphamontripong
• Aggregation functions
• Order of actions matter when applying aggregation
• Aggregation helps make decisions and succinctly convey
information
What’s next?
• SQL – Joins
• Combine techniques (aggregates and joins) to solve
complex questions
SQL - Join
© Praphamontripong [A. Silberschatz, H. F
. Korth, S. Sudarshan, Database System Concepts, Ch.4.1]
[ https://www.dofactory.com/sql/join ]
Recap 1: Aggregation
© Praphamontripong
ID name dept_name salary
10101 Srinivasan Comp. Sci. 65000.00
12121 Wu Finance 90000.00
15151 Mozart Music 40000.00
22222 Einstein Physics 95000.00
32343 El Said History 60000.00
33456 Gold Physics 87000.00
45565 Kate Comp. Sci. 75000.00
58583 Katz History 62000.00
76543 Singh Finance 80000.00
76766 Brandt Biology 72000.00
83821 Kate Comp. Sci. 92000.00
98345 Kim Elec. Eng. 80000.00
Instructor (refer to alldbs.sql)
Find average salary
for each department
SELECT dept_name, AVG(salary)
FROM instructor
GROUP BY dept_name;
Recap 2: Aggregation
© Praphamontripong
ID name dept_name salary
10101 Srinivasan Comp. Sci. 65000.00
12121 Wu Finance 90000.00
15151 Mozart Music 40000.00
22222 Einstein Physics 95000.00
32343 El Said History 60000.00
33456 Gold Physics 87000.00
45565 Kate Comp. Sci. 75000.00
58583 Katz History 62000.00
76543 Singh Finance 80000.00
76766 Brandt Biology 72000.00
83821 Kate Comp. Sci. 92000.00
98345 Kim Elec. Eng. 80000.00
Find average salary
for each department
that is greater than
70000
SELECT dept_name, AVG(salary)
FROM instructor
GROUP BY dept_name
HAVING AVG(salary) > 70000;
Instructor (refer to alldbs.sql)
Recap: Primary Keys, Foreign Keys
Hiring (TA_id, Name, Year, Two_week_hours)
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
Key = one or more
attributes that uniquely
identify a row
TA_Assignment (TA_id, Course)
TA_id Course
1234 Database Systems
2345 Database Systems
3456 Cloud Computing
1234 Software Analysis
5678 Web Programming Lang.
Foreign key = one or more
attributes that uniquely
identify a row in another
table
5678 Mickey 2 16
references
Foreign key describes a relationship between tables
© Praphamontripong
JOIN
• Combine related tables or sets of data on key values
• All tables (or relations) must have a unique identifier
(primary key)
• Any related tables must contain a copy of the unique
identifier (foreign key) from the related table
left
table
right
table
FULL JOIN
left
table
right
table
LEFT JOIN
left
table
right
table
RIGHT JOIN
left
table
right
table
(INNER) JOIN
left
table
right
table
NATURAL JOIN
(preserve all rows,
uncommon, thus skip)
© Praphamontripong
(most common)
(preserve all rows
in right table)
(preserve all rows
in left table)
NATURAL JOIN
left
table
right
table
NATURAL JOIN
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Not include the repeated column
one(p1, colA, colB) two(p2, p1, colX, colY)
SELECT *
FROM one NATURAL JOIN two;
for each row1 in one:
for each row2 in two:
if (row1.p1 = row2.p1):
output (row1.p1, row1.colA,
row2.p2, row2.colX,
row1.colB,
row2.colY)
Join on common
named
attribute(s).
If no match
found, move on.
© Praphamontripong
p1 colA colB p2 colX colY
1 A aa 9001 55 ABC
2 B bb 9006 42 STU
3 C cc 9002 77 PQR
3 C cc 9003 95 DEF
5 E ee 9005 50 KLM
7 G gg 9004 62 GHI
7 G gg 9007 83 XYZ
NATURAL JOIN
left
table
right
table
NATURAL JOIN
Not include the repeated column
one(p1, colA, colB) two(p2, p1, colX,
SELECT *
FROM one
NATURAL JOIN two
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
colY)
Note the order of the columns; order of rows does not matter
© Praphamontripong
(INNER) JOIN
left
table
right
table
(INNER) JOIN
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Include the repeated column
one(p1, colA, colB) two(p2, p1, colX, colY)
SELECT *
FROM one JOIN two ON one.p1 =
two.p1;
Join on specified
attribute(s).
If no match
found, move on.
© Praphamontripong
for each row1 in one:
for each row2 in two:
if (row1.p1 = row2.p1):
output (row1.p1, row1.colA, row1.colB,
row2.p2, row2.p1, row2.colX, row2.colY)
p1 colA colB p2 p1 colX colY
1 A aa 9001 1 55 ABC
2 B bb 9006 2 42 STU
3 C cc 9002 3 77 PQR
3 C cc 9003 3 95 DEF
5 E ee 9005 5 50 KLM
7 G gg 9004 7 62 GHI
7 G gg 9007 7 83 XYZ
(INNER) JOIN
left
table
right
table
(INNER) JOIN
SELECT *
FROM one JOIN two
ON one.p1 = two.p1
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Include the repeated column
one(p1, colA, colB) two(p2, p1, colX, colY)
SELECT *
FROM one INNER JOIN two
ON one.p1 = two.p1
Note the order of the columns; order of rows does not matter
© Praphamontripong
Cartesian (Cross)
Product
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
one(p1, colA, colB) two(p2, p1, colX, colY)
SELECT *
FROM one JOIN two;
for each row1 in one:
for each row2 in two:
output (row1.p1, row1.colA, row1.colB,
row2.p2, row2.p1, row2.colX, row2.colY)
SELECT *
FROM one, two;
© Praphamontripong
p1 colA colB p2 p1 colX colY
1 A aa 9001 1 55 ABC
1 A aa 9005 5 50 KLM
1 A aa 9004 7 62 GHI
1 A aa 9003 3 95 DEF
1 A aa 9007 7 83 XYZ
1 A aa 9002 3 77 PQR
1 A aa 9006 2 42 STU
2 B bb 9002 3 77 PQR
2 B bb 9006 2 42 STU
2 B bb 9001 1 55 ABC
2 B bb 9005 5 50 KLM
2 B bb 9004 7 62 GHI
2 B bb 9003 3 95 DEF
2 B bb 9007 7 83 XYZ
3 C cc 9003 3 95 DEF
3 C cc 9007 7 83 XYZ
... … … ... … … …
Cartesian (Cross)
Product
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
one(p1, colA, colB)
two(p2, p1, colX, colY)
one × two
Note the order of the columns; order of rows does not matter
© Praphamontripong
NATURAL LEFT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
SELECT *
FROM one NATURAL LEFT OUTER JOIN
two;
Join on common
named
attribute(s).
If no match
found, pad with
NULL values
left
table
right
table
LEFT JOIN
Preserve all rows
in left table
© Praphamontripong
p1 colA colB p2 colX colY
1 A aa 9001 55 ABC
2 B bb 9006 42 STU
3 C cc 9002 77 PQR
3 C cc 9003 95 DEF
4 D dd NULL NULL NULL
5 E ee 9005 50 KLM
7 G gg 9004 62 GHI
7 G gg 9007 83 XYZ
8 H hh NULL NULL NULL
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Note the order of the columns; order of rows does not matter
NATURAL LEFT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY) left
table
right
table
LEFT JOIN
© Praphamontripong
LEFT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
SELECT *
FROM one LEFT OUTER JOIN two
ON one.p1 = two.p1;
Join on specified
attribute(s).
If no match
found, pad with
NULL values
left
table
right
table
LEFT JOIN
Preserve all rows
in left table
© Praphamontripong
p1 colA colB p2 p1 colX colY
1 A aa 9001 1 55 ABC
2 B bb 9006 2 42 STU
3 C cc 9002 3 77 PQR
3 C cc 9003 3 95 DEF
4 D dd NULL NULL NULL NULL
5 E ee 9005 5 50 KLM
7 G gg 9004 7 62 GHI
7 G gg 9007 7 83 XYZ
8 H hh NULL NULL NULL NULL
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Note the order of the columns; order of rows does not matter
LEFT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY) left
table
right
table
LEFT JOIN
© Praphamontripong
NATURAL RIGHT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
SELECT *
FROM one NATURAL RIGHT OUTER JOIN
two;
Join on common
named
attribute(s).
If no match
found, pad with
NULL values
left
table
right
table
RIGHT JOIN
Preserve all rows
in right table
© Praphamontripong
p1 colA colB p2 colX colY
1 A aa 9001 55 ABC
2 B bb 9006 42 STU
3 C cc 9002 77 PQR
3 C cc 9003 95 DEF
5 E ee 9005 50 KLM
7 G gg 9004 62 GHI
7 G gg 9007 83 XYZ
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Note the order of the columns; order of rows does not matter
NATURAL RIGHT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
Since two.p1 is a foreign key
referencing one.p1,
matches are always founded
left
table
right
table
RIGHT JOIN
© Praphamontripong
RIGHT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Join on specified
attribute(s).
If no match
found, pad with
NULL values
left
table
right
table
RIGHT JOIN
SELECT *
FROM one RIGHT OUTER JOIN two
ON one.p1 = two.p1;
Preserve all rows
in right table
© Praphamontripong
p1 colA colB
1 A aa
2 B bb
3 C cc
4 D dd
5 E ee
7 G gg
8 H hh
p2 p1 colX colY
9001 1 55 ABC
9002 3 77 PQR
9003 3 95 DEF
9004 7 62 GHI
9005 5 50 KLM
9006 2 42 STU
9007 7 83 XYZ
Note the order of the columns; order of rows does not matter
RIGHT OUTER JOIN
Augment a join by the dangling tuples
one(p1, colA, colB) two(p2, p1, colX, colY)
Since two.p1 is a foreign key
referencing one.p1,
matches are always founded
left
table
right
table
RIGHT JOIN
p1 colA colB p2 p1 colX colY
1 A aa 9001 1 55 ABC
2 B bb 9006 2 42 STU
3 C cc 9002 3 77 PQR
3 C cc 9003 3 95 DEF
5 E ee 9005 5 50 KLM
7 G gg 9004 7 62 GHI
7 G gg 9007 7 83 XYZ
© Praphamontripong
Self Joins
© Praphamontripong
• Join with itself
• Useful when the table has a FOREIGN KEY which
references its own PRIMARY KEY
• Can be viewed as joining two copies of the same table
• To do self join, use aliases
(Challenging) Example: Self Joins
© Praphamontripong
Find names of all TAs who are assigned to Database Systems and
Software Analysis
Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course)
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
TA_id Course
1234 Database Systems
2345 Database Systems
3456 Cloud Computing
1234 Software Analysis
5678 Web Programming Lang.
2345 Software Analysis
How should we write SQL?
(Challenging) Example: Self Joins
© Praphamontripong
Find names of all TAs who are assigned to Database Systems and
Software Analysis
Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course)
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
TA_id Course
1234 Database Systems
2345 Database Systems
3456 Cloud Computing
1234 Software Analysis
5678 Web Programming Lang.
2345 Software Analysis
SELECT H.Name
From Hiring AS H, TA_Assignment AS T
WHERE H.TA_id = T.TA_id AND
T.Course = "Database Systems" AND
T.Course = "Software Analysis";
Will this work?
No.
Returns empty set
(Challenging) Example: Self Joins
© Praphamontripong
Find names of all TAs who are assigned to Database Systems and
Software Analysis
Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course)
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
TA_id Course
1234 Database Systems
2345 Database Systems
3456 Cloud Computing
1234 Software Analysis
5678 Web Programming Lang.
2345 Software Analysis
SELECT H.Name
From Hiring AS H, TA_Assignment AS T1,
TA_Assignment AS T2
WHERE H.TA_id = T1.TA_id AND
H.TA_id = T2.TA_id AND
T1.Course = "Database Systems" AND
T2.Course = "Software Analysis";
Will this work?
Name
Minnie
Humpty
(Challenging) Example: Self Joins
Find names of all TAs who are assigned to Database Systems and
Software Analysis
Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course)
TA_id Name Year Two_week_hours
1234 Minnie 4 20
2345 Humpty 3 24
3456 Dumpty 4 30
3333 Minnie 3 12
5678 Mickey 2 16
TA_id Course
1234 Database Systems
2345 Database Systems
3456 Cloud Computing
1234 Software Analysis
5678 Web Programming Lang.
2345 Software Analysis
SELECT H.Name
From Hiring AS H, TA_Assignment AS T1,
TA_Assignment AS T2
WHERE H.TA_id =
H.TA_id =
T1.Course
T2.Course
T1.TA_id AND
T2.TA_id AND
= "Database Systems" AND
= "Software Analysis";
Let’s consider each
part of the query
All pairs of courses
a TA is assigned
For each pair, check
for courses
© Praphamontripong
Wrap-Up
Join combines data across tables
• Nested-loop
• Natural join (most common)
• Inner join (filter Cartesian product)
• Outer joins (preserve non-matching tuples)
• Self join pattern
Different joining techniques can be used to achieve particular goals
left
table
right
table
LEFT JOIN
left
table
right
table
RIGHT JOIN
left
table
right
table
NATURAL JOIN
left
table
right
table
(INNER) JOIN
© Praphamontripong

More Related Content

Similar to DB_lecturs8 27 11.pptx

Simran kaur,BCA Final Year 2015
Simran kaur,BCA Final Year 2015Simran kaur,BCA Final Year 2015
Simran kaur,BCA Final Year 2015dezyneecole
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Charles Givre
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2Belal Arfa
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricksYanli Liu
 
LWPG1_001 Chapter 4.pptx
LWPG1_001 Chapter 4.pptxLWPG1_001 Chapter 4.pptx
LWPG1_001 Chapter 4.pptxNitinmadas
 
Vishwajeet Sikhwal ,BCA,Final Year 2015
Vishwajeet Sikhwal ,BCA,Final Year 2015Vishwajeet Sikhwal ,BCA,Final Year 2015
Vishwajeet Sikhwal ,BCA,Final Year 2015dezyneecole
 
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole CollegeDivyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole Collegedezyneecole
 
James Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science PortfolioJames Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science Portfoliocolbydaman
 
Tactical data engineering
Tactical data engineeringTactical data engineering
Tactical data engineeringJulian Hyde
 
Pooja Bijawat,Bachelor Degree in Computer Application
Pooja Bijawat,Bachelor Degree in Computer ApplicationPooja Bijawat,Bachelor Degree in Computer Application
Pooja Bijawat,Bachelor Degree in Computer Applicationdezyneecole
 
Chapter 16-spreadsheet1 questions and answer
Chapter 16-spreadsheet1  questions and answerChapter 16-spreadsheet1  questions and answer
Chapter 16-spreadsheet1 questions and answerRaajTech
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOAltinity Ltd
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimizationVivek Singh
 
SECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxSECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxkenjordan97598
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
Automating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftAutomating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftThousandEyes
 
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud Alithya
 

Similar to DB_lecturs8 27 11.pptx (20)

Assignment#04
Assignment#04Assignment#04
Assignment#04
 
Simran kaur,BCA Final Year 2015
Simran kaur,BCA Final Year 2015Simran kaur,BCA Final Year 2015
Simran kaur,BCA Final Year 2015
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
LWPG1_001 Chapter 4.pptx
LWPG1_001 Chapter 4.pptxLWPG1_001 Chapter 4.pptx
LWPG1_001 Chapter 4.pptx
 
Vishwajeet Sikhwal ,BCA,Final Year 2015
Vishwajeet Sikhwal ,BCA,Final Year 2015Vishwajeet Sikhwal ,BCA,Final Year 2015
Vishwajeet Sikhwal ,BCA,Final Year 2015
 
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole CollegeDivyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
Divyansh Mehta,BCA Final Year 2015 ,Dezyne E'cole College
 
James Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science PortfolioJames Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science Portfolio
 
Tactical data engineering
Tactical data engineeringTactical data engineering
Tactical data engineering
 
Pooja Bijawat,Bachelor Degree in Computer Application
Pooja Bijawat,Bachelor Degree in Computer ApplicationPooja Bijawat,Bachelor Degree in Computer Application
Pooja Bijawat,Bachelor Degree in Computer Application
 
Chapter 16-spreadsheet1 questions and answer
Chapter 16-spreadsheet1  questions and answerChapter 16-spreadsheet1  questions and answer
Chapter 16-spreadsheet1 questions and answer
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
70433 Dumps DB
70433 Dumps DB70433 Dumps DB
70433 Dumps DB
 
SECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxSECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docx
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Automating Performance Monitoring at Microsoft
Automating Performance Monitoring at MicrosoftAutomating Performance Monitoring at Microsoft
Automating Performance Monitoring at Microsoft
 
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud
nter-pod Revolutions: Connected Enterprise Solution in Oracle EPM Cloud
 

Recently uploaded

VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...Suhani Kapoor
 
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...Suhani Kapoor
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceSanjay Bokadia
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳anilsa9823
 
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackVIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackSuhani Kapoor
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...shivangimorya083
 
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls DubaiDark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls Dubaikojalkojal131
 
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)Soham Mondal
 
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen DatingDubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Datingkojalkojal131
 
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service Cuttack
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service CuttackLow Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service Cuttack
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service CuttackSuhani Kapoor
 
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineBruce Bennett
 
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girlsshivangimorya083
 
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call Girls
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call GirlsSonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call Girls
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call GirlsNiya Khan
 
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...Suhani Kapoor
 
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...Niya Khan
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士obuhobo
 
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackSuhani Kapoor
 

Recently uploaded (20)

VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
VIP Russian Call Girls Amravati Chhaya 8250192130 Independent Escort Service ...
 
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
VIP Russian Call Girls in Bhilai Deepika 8250192130 Independent Escort Servic...
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector Experience
 
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service  🧳
CALL ON ➥8923113531 🔝Call Girls Husainganj Lucknow best Female service 🧳
 
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service CuttackVIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
VIP Call Girl Cuttack Aashi 8250192130 Independent Escort Service Cuttack
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
 
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls DubaiDark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
 
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)
 
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen DatingDubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
 
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service Cuttack
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service CuttackLow Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service Cuttack
Low Rate Call Girls Cuttack Anika 8250192130 Independent Escort Service Cuttack
 
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
 
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
 
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call GirlsDelhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
Delhi Call Girls In Atta Market 9711199012 Book Your One night Stand Call Girls
 
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call Girls
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call GirlsSonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call Girls
Sonam +91-9537192988-Mind-blowing skills and techniques of Ahmedabad Call Girls
 
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
VIP Russian Call Girls in Amravati Deepika 8250192130 Independent Escort Serv...
 
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...
Neha +91-9537192988-Friendly Ahmedabad Call Girls has Complete Authority for ...
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
 
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
 

DB_lecturs8 27 11.pptx

  • 1. Introduction to Databases Autumn 2022 Egyptian Russian University IS201 IS201: Database Systems 1 Egyptian Russian University IS201: Database Systems Dr. Nermeen Kamel
  • 2. SQL – Basics (More Practice) © Praphamontripong IS201 Database Systems
  • 3. Consider sample data of an Orders table. How many days elapsed between the order date and the ship date for each order? Orders Example 1: Translate and Clean Up Select the order number, order date, ship date, ship date minus order as DaysElapsed from the Orders table Select the order number, order date, ship date, ship date minus order as DaysElapsed from the Orders table © Praphamontripong
  • 4. Example 1: Translate and Clean Up SELECT OrderNumber, OrderDate, ShipDate, (ShipDate - OrderDate) AS DaysElapsed FROM Orders; Select the order number, order date, ship date, ship date minus order as DaysElapsed from the Orders table Note: rename the column header © Praphamontripong
  • 5. Consider sample data of an Orders table. Show me a list of orders made by each customer in descending date order Orders Example 2: Translate and Clean Up Select the customer ID, order number, order date, ship date, from the Orders table for each customer and then sort by customer and descending order date Select the customer ID, order number, order date, ship date, from the Orders table for each customer group by customer ID and then sort by customer order by customer ID and descending order date desc © Praphamontripong
  • 6. Example 2: Translate and Clean Up Select the customer ID, order number, order date, ship date, from the Orders table for each customer group by customer ID and then sort by customer order by customer ID and descending order date desc SELECT CustomerID, OrderNumber, OrderDate, ShipDate FROM Orders GROUP BY CustomerID, OrderNumber ORDER BY CustomerID, OrderDate DESC; Note: Several DBMS requires that everything in “ORDER BY” must be in “GROUP BY” and everything in “GROUP BY” must be in “SELECT.” (MySQL doesn’t seem to enforce these requirements) © Praphamontripong
  • 7. Find Courses that Minnie is a TA. Also, list all S_id who takes those courses SELECT S_id, Course FROM Student_lecture AS S WHERE S.Teaching_assistant = “Minnie” ; Student_lecture S_id Address Course Teaching_assistant 1234 57 Hockanum Blvd Database Systems Minnie 2345 1400 E. Bellows Database Systems Humpty 3456 900 S. Detroit Cloud Computing Dumpty 1234 57 Hockanum Blvd Web Programming Lang. Mickey 5678 2131 Forest Lake Ln. Software Analysis Minnie Recap 1: SELECT .. FROM .. WHERE For each row in S: if (row.Teaching_assistant = ”Minnie”: output (row.S_id, row.Course) FROM Open an iterator 1 WHERE Filter each row 2 SELECT output selected attributes 3 © Praphamontripong
  • 8. Recap 2: SELECT .. FROM .. WHERE Find all S_id who is taking Database Systems and have Humpty as a TA Student_lecture S_id Address Course Teaching_assistant 1234 57 Hockanum Blvd Database Systems Minnie 2345 1400 E. Bellows Database Systems Humpty 3456 900 S. Detroit Cloud Computing Dumpty 1234 57 Hockanum Blvd Web Programming Lang. Mickey 5678 2131 Forest Lake Ln. Software Analysis Minnie SELECT S_id FROM Student_lecture AS S WHERE S.Course = “Database Systems” AND S.Teaching_assistant = “Humpty” ; S_id 2345 © Praphamontripong
  • 9. Recap 3: SELECT .. FROM .. WHERE hiring TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 List all names of TAs and the number of hours the TAs work per week, rename the hours as “Hours_per_week” SELECT Name, two_week_hours/2 AS Hours_per_week FROM hiring © Praphamontripong Name Hours_per_week Minnie 10 Humpty 12 Dumpty 15 Minnie 6 Mickey 8
  • 10. Recap 4: SELECT .. FROM .. WHERE List all years hiring TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 SELECT Year FROM hiring Year 4 3 4 3 2 Duplicates may occur in output of an operator © Praphamontripong
  • 11. Recap 5: SELECT .. FROM .. WHERE hiring TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 List all years the TAs are in. If multiple TAs are in the same year, list the year only once SELECT DISTINCT Year FROM hiring © Praphamontripong Year 4 3 2
  • 12. Recap 6: SELECT .. FROM .. WHERE hiring TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 List all names of TAs and the number of hours the TAs work per week, rename the hours as “Hours_per_week”, then order the result set by names and then Hours_per_week SELECT Name, two_week_hours/2 AS Hours_per_week FROM hiring ORDER BY Name, Hours_per_week © Praphamontripong Name Hours_per_week Dumpty 15 Humpty 12 Mickey 8 Minnie 6 Minnie 10
  • 13. SQL – Aggregates © Praphamontripong [A. Silberschatz, H. F . Korth, S. Sudarshan, Database System Concepts, Ch.3.7 and Ch. 5.5] [C.M. Ricardo, S.D. Urban, Databases Illuminated, Ch. 5.4]
  • 14. Aggregation Functions © Praphamontripong Calculate a value across an entire set or across groups of rows within the set SQL uses five aggregation operators: • SUM – produces the sum of a column with numerical values • AVG – produces the average of a column with numerical values • MIN – applied to a column with numerical values, produces the smallest value • MAX – applied to a column with numerical values, produces the largest value • COUNT – produces the number of (not necessarily distinct) values in a column
  • 15. Example: SUM Given the loan schema loan(loan_number, branch_name, amount) The sum of the amounts of all loans is expressed by loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 SUM(amount) 8700 Total © Praphamontripong 8700 SELECT SUM(amount) FROM loan SELECT SUM(amount) AS Total FROM loan
  • 16. Example: AVG Given the loan schema loan(loan_number, branch_name, amount) The average of the amounts of all loans is expressed by loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 AVG(amount) © Praphamontripong 1242.857142857143 SELECT AVG(amount) FROM loan
  • 17. Example: MIN Given the loan schema loan(loan_number, branch_name, amount) The smallest amount of loans is expressed by loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 min(amount) © Praphamontripong 500 SELECT MIN(amount) FROM loan
  • 18. Example: MAX Given the loan schema loan(loan_number, branch_name, amount) The largest amount of loans is expressed by loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 max(amount) © Praphamontripong 2000 SELECT MAX(amount) FROM loan
  • 19. Example: COUNT Given the loan schema loan(loan_number, branch_name, amount) loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 count(*) 7 Count(loan_number) 7 Count the number of tuples in the loan table SELECT count(*) SELECT count(loan_number) FROM loan FROM loan Count © Praphamontripong rows Count values of a specified column
  • 20. Example: COUNT .. DISTINCT Given the loan schema loan(loan_number, branch_name, amount) Count the number of values in the branch_name column loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 count(branch_name) 7 count(distinct branch_name) © Praphamontripong 5 SELECT count(branch_name) FROM loan SELECT count(DISTINCT branch_name) FROM loan
  • 21. Aggregation: Order of Actions 1. The FROM clause generates the data set 2. The WHERE clause filters the data set generated by the FROM clause 3. The GROUP BY clause aggregates the data set that was filtered by the WHERE clause (note: GROUP BY does not sort the result set) 4. The HAVING clause filters the data set that was aggregated by the GROUP BY clause 5. The SELECT clause transforms the filtered aggregated data set 6. The ORDER BY clause sorts the transformed data set SELECT select_list FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY order_expression [ASC | DESC] ] Order matter © Praphamontripong
  • 22. Grouping Requirement Several DBMS requires that the columns appear in the SELECT clause that are not used in an aggregation function must appear in the GROUP BY clause SELECT column_A, column_B, some_aggregation_function FROM table_source GROUP BY column_A, column_B SELECT column_A, column_B, some_aggregation_function FROM table_source GROUP BY column_B © Praphamontripong
  • 23. Example: SUM with GROUP BY © Praphamontripong Given the loan schema loan(loan_number, branch_name, amount) The sum of the amounts of all loans for each branch is expressed by loan_number branch_name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge 1500 L-16 Perryridge 1300 L-17 Downtown 1000 L-23 Redwood 2000 L-93 Mianus 500 branch_name SUM(amount) Downtown 2500 Mianus 500 Perryridge 2800 Redwood 2000 Round Hill 900 SELECT branch_name, SUM(amount) FROM loan GROUP BY branch_name;
  • 24. Grouping, Aggregation, and Null © Praphamontripong • The value NULL is ignored in any aggregation • Not contribute to a sum, average, or count of an attribute • Cannot be the minimum or maximum in its column • Null is treated as an ordinary value when forming groups • Can have a group with NULL attribute(s) • When performing any aggregation except count over an empty bag of values, the result is NULL • The count of an empty bag is 0
  • 25. HAVING Clauses © Praphamontripong • An aggregation in a HAVING clause applies only to the tuples of the group being tested – filter groups • Any attributes of relations in the FROM clause may be aggregated in the HAVING clause • But only those attributes that are in the GROUP BY list may appear unaggregated in the having clause branch_name SUM(amount) Downtown 2500 Perryridge 2800 The sum of the amounts of all loans for each branch that has more than one loan is expressed by SELECT branch_name, sum(amount) FROM loan GROUP BY branch_name HAVING COUNT(branch_name) > 1;
  • 26. Example 1 List the number of customers in each country. Only include countries with more than 10 customers count(id) Country 11 France 11 Germany 13 USA SELECT count(id), country FROM Customer GROUP BY country HAVING COUNT(id) > 10; © Praphamontripong
  • 27. Example 2 List the number of customers in each country, except USA, sorted high to low. Only include countries with 9 or more customers count(id) Country 11 France 11 Germany 9 Brazil SELECT COUNT(id), country Customer country <> “USA” FROM WHERE GROUP BY country HAVING ORDER BY COUNT(id) COUNT(id) >= 9 DESC; © Praphamontripong
  • 28. Final Notes about Aggregation © Praphamontripong #1: Keep the GROUP BY clause small and precise • Several DBMSs require that all non-aggregated columns must be in the GROUP BY clause • Excessive columns in GROUP BY can negatively impact the query’s performance; make the query hard to read, understand, rewrite • For queries that need both aggregations and details, do all aggregations in subqueries first, then join those to the tables to retrieve the details
  • 29. Final Notes about Aggregation © Praphamontripong #2: COUNT(*) and COUNT(<column_name>) are different • COUNT(*) – count all rows, including ones with null values • COUNT(<column_name>) – count only the rows where the column value is not NULL • Sometimes, dividing a query into subqueies can be more efficient than using a GROUP BY.
  • 30. Final Notes about Aggregation © Praphamontripong #3: Use DISTINCT to get distinct counts • COUNT(*) – returns the number of rows in a group, including NULL value and duplicates • COUNT(<column_name>) – returns the number of rows where the column value is not NULL • COUNT(DISTINCT <column_name>) – returns the number of rows with unique, non-null values of the column
  • 31. Wrap-Up © Praphamontripong • Aggregation functions • Order of actions matter when applying aggregation • Aggregation helps make decisions and succinctly convey information What’s next? • SQL – Joins • Combine techniques (aggregates and joins) to solve complex questions
  • 32. SQL - Join © Praphamontripong [A. Silberschatz, H. F . Korth, S. Sudarshan, Database System Concepts, Ch.4.1] [ https://www.dofactory.com/sql/join ]
  • 33. Recap 1: Aggregation © Praphamontripong ID name dept_name salary 10101 Srinivasan Comp. Sci. 65000.00 12121 Wu Finance 90000.00 15151 Mozart Music 40000.00 22222 Einstein Physics 95000.00 32343 El Said History 60000.00 33456 Gold Physics 87000.00 45565 Kate Comp. Sci. 75000.00 58583 Katz History 62000.00 76543 Singh Finance 80000.00 76766 Brandt Biology 72000.00 83821 Kate Comp. Sci. 92000.00 98345 Kim Elec. Eng. 80000.00 Instructor (refer to alldbs.sql) Find average salary for each department SELECT dept_name, AVG(salary) FROM instructor GROUP BY dept_name;
  • 34. Recap 2: Aggregation © Praphamontripong ID name dept_name salary 10101 Srinivasan Comp. Sci. 65000.00 12121 Wu Finance 90000.00 15151 Mozart Music 40000.00 22222 Einstein Physics 95000.00 32343 El Said History 60000.00 33456 Gold Physics 87000.00 45565 Kate Comp. Sci. 75000.00 58583 Katz History 62000.00 76543 Singh Finance 80000.00 76766 Brandt Biology 72000.00 83821 Kate Comp. Sci. 92000.00 98345 Kim Elec. Eng. 80000.00 Find average salary for each department that is greater than 70000 SELECT dept_name, AVG(salary) FROM instructor GROUP BY dept_name HAVING AVG(salary) > 70000; Instructor (refer to alldbs.sql)
  • 35. Recap: Primary Keys, Foreign Keys Hiring (TA_id, Name, Year, Two_week_hours) TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 Key = one or more attributes that uniquely identify a row TA_Assignment (TA_id, Course) TA_id Course 1234 Database Systems 2345 Database Systems 3456 Cloud Computing 1234 Software Analysis 5678 Web Programming Lang. Foreign key = one or more attributes that uniquely identify a row in another table 5678 Mickey 2 16 references Foreign key describes a relationship between tables © Praphamontripong
  • 36. JOIN • Combine related tables or sets of data on key values • All tables (or relations) must have a unique identifier (primary key) • Any related tables must contain a copy of the unique identifier (foreign key) from the related table left table right table FULL JOIN left table right table LEFT JOIN left table right table RIGHT JOIN left table right table (INNER) JOIN left table right table NATURAL JOIN (preserve all rows, uncommon, thus skip) © Praphamontripong (most common) (preserve all rows in right table) (preserve all rows in left table)
  • 37. NATURAL JOIN left table right table NATURAL JOIN p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Not include the repeated column one(p1, colA, colB) two(p2, p1, colX, colY) SELECT * FROM one NATURAL JOIN two; for each row1 in one: for each row2 in two: if (row1.p1 = row2.p1): output (row1.p1, row1.colA, row2.p2, row2.colX, row1.colB, row2.colY) Join on common named attribute(s). If no match found, move on. © Praphamontripong
  • 38. p1 colA colB p2 colX colY 1 A aa 9001 55 ABC 2 B bb 9006 42 STU 3 C cc 9002 77 PQR 3 C cc 9003 95 DEF 5 E ee 9005 50 KLM 7 G gg 9004 62 GHI 7 G gg 9007 83 XYZ NATURAL JOIN left table right table NATURAL JOIN Not include the repeated column one(p1, colA, colB) two(p2, p1, colX, SELECT * FROM one NATURAL JOIN two p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ colY) Note the order of the columns; order of rows does not matter © Praphamontripong
  • 39. (INNER) JOIN left table right table (INNER) JOIN p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Include the repeated column one(p1, colA, colB) two(p2, p1, colX, colY) SELECT * FROM one JOIN two ON one.p1 = two.p1; Join on specified attribute(s). If no match found, move on. © Praphamontripong for each row1 in one: for each row2 in two: if (row1.p1 = row2.p1): output (row1.p1, row1.colA, row1.colB, row2.p2, row2.p1, row2.colX, row2.colY)
  • 40. p1 colA colB p2 p1 colX colY 1 A aa 9001 1 55 ABC 2 B bb 9006 2 42 STU 3 C cc 9002 3 77 PQR 3 C cc 9003 3 95 DEF 5 E ee 9005 5 50 KLM 7 G gg 9004 7 62 GHI 7 G gg 9007 7 83 XYZ (INNER) JOIN left table right table (INNER) JOIN SELECT * FROM one JOIN two ON one.p1 = two.p1 p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Include the repeated column one(p1, colA, colB) two(p2, p1, colX, colY) SELECT * FROM one INNER JOIN two ON one.p1 = two.p1 Note the order of the columns; order of rows does not matter © Praphamontripong
  • 41. Cartesian (Cross) Product p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ one(p1, colA, colB) two(p2, p1, colX, colY) SELECT * FROM one JOIN two; for each row1 in one: for each row2 in two: output (row1.p1, row1.colA, row1.colB, row2.p2, row2.p1, row2.colX, row2.colY) SELECT * FROM one, two; © Praphamontripong
  • 42. p1 colA colB p2 p1 colX colY 1 A aa 9001 1 55 ABC 1 A aa 9005 5 50 KLM 1 A aa 9004 7 62 GHI 1 A aa 9003 3 95 DEF 1 A aa 9007 7 83 XYZ 1 A aa 9002 3 77 PQR 1 A aa 9006 2 42 STU 2 B bb 9002 3 77 PQR 2 B bb 9006 2 42 STU 2 B bb 9001 1 55 ABC 2 B bb 9005 5 50 KLM 2 B bb 9004 7 62 GHI 2 B bb 9003 3 95 DEF 2 B bb 9007 7 83 XYZ 3 C cc 9003 3 95 DEF 3 C cc 9007 7 83 XYZ ... … … ... … … … Cartesian (Cross) Product p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ one(p1, colA, colB) two(p2, p1, colX, colY) one × two Note the order of the columns; order of rows does not matter © Praphamontripong
  • 43. NATURAL LEFT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ SELECT * FROM one NATURAL LEFT OUTER JOIN two; Join on common named attribute(s). If no match found, pad with NULL values left table right table LEFT JOIN Preserve all rows in left table © Praphamontripong
  • 44. p1 colA colB p2 colX colY 1 A aa 9001 55 ABC 2 B bb 9006 42 STU 3 C cc 9002 77 PQR 3 C cc 9003 95 DEF 4 D dd NULL NULL NULL 5 E ee 9005 50 KLM 7 G gg 9004 62 GHI 7 G gg 9007 83 XYZ 8 H hh NULL NULL NULL p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Note the order of the columns; order of rows does not matter NATURAL LEFT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) left table right table LEFT JOIN © Praphamontripong
  • 45. LEFT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ SELECT * FROM one LEFT OUTER JOIN two ON one.p1 = two.p1; Join on specified attribute(s). If no match found, pad with NULL values left table right table LEFT JOIN Preserve all rows in left table © Praphamontripong
  • 46. p1 colA colB p2 p1 colX colY 1 A aa 9001 1 55 ABC 2 B bb 9006 2 42 STU 3 C cc 9002 3 77 PQR 3 C cc 9003 3 95 DEF 4 D dd NULL NULL NULL NULL 5 E ee 9005 5 50 KLM 7 G gg 9004 7 62 GHI 7 G gg 9007 7 83 XYZ 8 H hh NULL NULL NULL NULL p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Note the order of the columns; order of rows does not matter LEFT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) left table right table LEFT JOIN © Praphamontripong
  • 47. NATURAL RIGHT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ SELECT * FROM one NATURAL RIGHT OUTER JOIN two; Join on common named attribute(s). If no match found, pad with NULL values left table right table RIGHT JOIN Preserve all rows in right table © Praphamontripong
  • 48. p1 colA colB p2 colX colY 1 A aa 9001 55 ABC 2 B bb 9006 42 STU 3 C cc 9002 77 PQR 3 C cc 9003 95 DEF 5 E ee 9005 50 KLM 7 G gg 9004 62 GHI 7 G gg 9007 83 XYZ p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Note the order of the columns; order of rows does not matter NATURAL RIGHT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) Since two.p1 is a foreign key referencing one.p1, matches are always founded left table right table RIGHT JOIN © Praphamontripong
  • 49. RIGHT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Join on specified attribute(s). If no match found, pad with NULL values left table right table RIGHT JOIN SELECT * FROM one RIGHT OUTER JOIN two ON one.p1 = two.p1; Preserve all rows in right table © Praphamontripong
  • 50. p1 colA colB 1 A aa 2 B bb 3 C cc 4 D dd 5 E ee 7 G gg 8 H hh p2 p1 colX colY 9001 1 55 ABC 9002 3 77 PQR 9003 3 95 DEF 9004 7 62 GHI 9005 5 50 KLM 9006 2 42 STU 9007 7 83 XYZ Note the order of the columns; order of rows does not matter RIGHT OUTER JOIN Augment a join by the dangling tuples one(p1, colA, colB) two(p2, p1, colX, colY) Since two.p1 is a foreign key referencing one.p1, matches are always founded left table right table RIGHT JOIN p1 colA colB p2 p1 colX colY 1 A aa 9001 1 55 ABC 2 B bb 9006 2 42 STU 3 C cc 9002 3 77 PQR 3 C cc 9003 3 95 DEF 5 E ee 9005 5 50 KLM 7 G gg 9004 7 62 GHI 7 G gg 9007 7 83 XYZ © Praphamontripong
  • 51. Self Joins © Praphamontripong • Join with itself • Useful when the table has a FOREIGN KEY which references its own PRIMARY KEY • Can be viewed as joining two copies of the same table • To do self join, use aliases
  • 52. (Challenging) Example: Self Joins © Praphamontripong Find names of all TAs who are assigned to Database Systems and Software Analysis Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course) TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 TA_id Course 1234 Database Systems 2345 Database Systems 3456 Cloud Computing 1234 Software Analysis 5678 Web Programming Lang. 2345 Software Analysis How should we write SQL?
  • 53. (Challenging) Example: Self Joins © Praphamontripong Find names of all TAs who are assigned to Database Systems and Software Analysis Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course) TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 TA_id Course 1234 Database Systems 2345 Database Systems 3456 Cloud Computing 1234 Software Analysis 5678 Web Programming Lang. 2345 Software Analysis SELECT H.Name From Hiring AS H, TA_Assignment AS T WHERE H.TA_id = T.TA_id AND T.Course = "Database Systems" AND T.Course = "Software Analysis"; Will this work? No. Returns empty set
  • 54. (Challenging) Example: Self Joins © Praphamontripong Find names of all TAs who are assigned to Database Systems and Software Analysis Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course) TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 TA_id Course 1234 Database Systems 2345 Database Systems 3456 Cloud Computing 1234 Software Analysis 5678 Web Programming Lang. 2345 Software Analysis SELECT H.Name From Hiring AS H, TA_Assignment AS T1, TA_Assignment AS T2 WHERE H.TA_id = T1.TA_id AND H.TA_id = T2.TA_id AND T1.Course = "Database Systems" AND T2.Course = "Software Analysis"; Will this work? Name Minnie Humpty
  • 55. (Challenging) Example: Self Joins Find names of all TAs who are assigned to Database Systems and Software Analysis Hiring(TA_id, Name, Year, Two_week_hours) TA_Assignment(TA_id, Course) TA_id Name Year Two_week_hours 1234 Minnie 4 20 2345 Humpty 3 24 3456 Dumpty 4 30 3333 Minnie 3 12 5678 Mickey 2 16 TA_id Course 1234 Database Systems 2345 Database Systems 3456 Cloud Computing 1234 Software Analysis 5678 Web Programming Lang. 2345 Software Analysis SELECT H.Name From Hiring AS H, TA_Assignment AS T1, TA_Assignment AS T2 WHERE H.TA_id = H.TA_id = T1.Course T2.Course T1.TA_id AND T2.TA_id AND = "Database Systems" AND = "Software Analysis"; Let’s consider each part of the query All pairs of courses a TA is assigned For each pair, check for courses © Praphamontripong
  • 56. Wrap-Up Join combines data across tables • Nested-loop • Natural join (most common) • Inner join (filter Cartesian product) • Outer joins (preserve non-matching tuples) • Self join pattern Different joining techniques can be used to achieve particular goals left table right table LEFT JOIN left table right table RIGHT JOIN left table right table NATURAL JOIN left table right table (INNER) JOIN © Praphamontripong