Professional Documents
Culture Documents
Data Management and SQL
Data Management and SQL
Talking to Databases
Part 1:
JOINS
Joining tables is used to gather related data from distinct tables in one
place (a flat table).
JOINS
JOINS are used to retrieve data from multiple tables.
Types of JOINS:
• INNER JOIN
• OUTER JOIN:
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• CROSS JOIN
JOINS
General syntax:
LEFT JOIN
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
RIGHT JOIN
RIGHT JOIN
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
FULL JOIN
FULL JOIN
Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.column = table2.column;
OUTER JOIN
Here is a more complicated country database:
Try all 4 joins and check the number of rows in the results.
OUTER JOIN
Q2. How many different languages are spoken in each country? Query
for country name from countries, and number of languages as num_lan.
Sort the resulting data by number of languages in descending order.
OUTER JOIN
A2. How many different languages are spoken in each country? Query
for country name from countries, and number of languages as num_lan.
Sort the resulting data by number of languages in descending order.
OUTER JOIN
Q3. How many different countries and distinct different languages exist
on each continent? Sort results by continent in alphabetical order.
OUTER JOIN
A3. How many different countries and distinct different languages exist
on each continent? Sort results by continent in alphabetical order.
CROSS JOIN
table1 table2
CROSS JOIN
Syntax:
SELECT columns
FROM table1
CROSS JOIN table2;
CROSS JOIN
Q. Compare the results of using CROSS JOIN and INNER JOIN to query
for country name and language name pairs in the America continent.
CROSS JOIN
A. CROSS JOIN
CROSS JOIN
A. INNER JOIN
Part 2:
Set Clauses
Set Operators:
• UNION (ALL): q1∪q2
• INTERSECT (ALL): q1 ∩ q2
• EXCEPT (ALL): q1 – q2
Id col_a
Id col_a Id col_a
1 A
1 A 3 C
UNION 2 B
2 B 4 D
3 C
3 C 5 E
4 D
5 E
Set Clauses
Q1. How many different country codes are returned when using UNION
to combine the countries table and the languages table?