Outer Joins
Sample Tables
Here is the schema for the sample leaderships table:
To download the actual files, you can get them from my Github repository.
LEFT JOIN
LEFT JOIN
lets you retrieve records from both tables even if there’s no match on the joining field. It returns all records from the left table and the matching records from the right table.
From the example above, we can see that the result of a LEFT JOIN
on the id
field shows that it includes all records from the left table. On the other hand, an INNER JOIN
will only return the records with matches.
Syntax:
SELECT *
FROM left_table
LEFT JOIN right_table
ON left_table.id = right_table.id;
Using the tables in the leadership database, if we want to include all countries with prime ministers and optionally presidents, LEFT JOIN
is appropriate. The syntax is similar to INNER JOIN
, just replace INNER with LEFT. LEFT JOIN
can also be written as LEFT OUTER JOIN.
- The syntax is similar to
INNER JOIN
; use LEFT instead of INNER. - It returns null values for missing matches.
LEFT JOIN
can also be written asLEFT OUTER JOIN
.
Query:
SELECT p1.country, prime_minister, president
FROM prime_ministers AS p1
LEFT JOIN presidents AS p2
USING (country);
Output:
prime_minister | president |
---|---|
United Kingdom | NULL |
Canada | NULL |
Australia | NULL |
India | Ram Nath Kovind |
Japan | NULL |
Germany | Frank-Walter Steinmeier |
Italy | Sergio Mattarella |
South Africa | NULL |
New Zealand | NULL |
Spain | NULL |
Belgium | NULL |
Sweden | NULL |