Full, Cross, and Self Joins
Sample Tables
Here is the schema for the sample World table:
To download the actual files, you can get them from my Github repository.
FULL JOIN
A FULL JOIN
combines the results of a LEFT JOIN
and a RIGHT JOIN
, ensuring that all records from both tables are included in the result set. If there is no match, the result set will have null values for every column from the table that lacks a corresponding row.
Syntax:
SELECT left_table.id AS L_id
right_table.id AS R_id
left_table.val AS L_val
right_table.val AS R_val
FROM left_table
FULL JOIN right_table
USING (id);
The keyword FULL OUTER JOIN
can also be used.
Examples on FULL JOIN
Consider the prime_ministers
and presidents
tables. To list all countries along with their prime ministers and presidents:
SELECT
p1.country,
p1.prime_minister,
p2.president
FROM prime_ministers AS p1
FULL JOIN presidents AS p2
ON p1.country = p2.country
LIMIT 10;
Output:
country | prime_minister | president |
---|---|---|
USA | NULL | Joe Biden |
France | NULL | Emmanuel Macron |
South Korea | NULL | Moon Jae-in |
India | Narendra Modi | Ram Nath Kovind |
Germany | Angela Merkel | Frank-Walter Steinmeier |
Italy | Mario Draghi | Sergio Mattarella |
Brazil | NULL | Jair Bolsonaro |
Mexico | NULL | Andrés Manuel López Obrador |
China | NULL | Xi Jinping |
Russia | NULL | Vladimir Putin |
Note that the NULL
values can appear in both columns.
CROSS JOIN
A CROSS JOIN
creates all possible combinations of rows between two tables. This results in a Cartesian product, where each row from the first table is combined with every row from the second table.
Syntax:
SELECT id1, id2
FROM table1
CROSS JOIN table2
Examples on CROSS JOIN
Consider a scenario where we want to list all possible meetings of prime ministers from Asia with presidents from South America. This means each prime minister will have to set a meeting with every presidents in South America, and vice versa.
SELECT prime_minister, president
FROM prime_ministers AS p1
CROSS JOIN presidents AS p2
WHERE p1.continent IN ('Asia')
AND p2.continent IN ('South America');