LEFT JOIN keeps every row of the first table, the one on the left, whether or not it finds a match in the second. Where there is a match, the row is paired up as in an inner join; where there is none, the second table’s columns are filled with NULL.
SELECT columnsFROM table1LEFT JOIN table2 ON table1.column = table2.column;LEFT OUTER JOIN is another name for the same thing.
The examples use the Productions and Invoices tables from the example database.
Every production, with its invoices
Section titled “Every production, with its invoices”SELECT Productions.Title, Invoices.InvoiceID, Invoices.AmountFROM ProductionsLEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionIDORDER BY Productions.Title;| Title | InvoiceID | Amount |
|---|---|---|
| Fennick’s Return | ||
| Quarry Lane | 1002 | 3,180.00 |
| Saltmarsh | ||
| Six Bells | 1004 | 2,940.00 |
| The Lantern Keepers | 1001 | 24,600.00 |
| The Lantern Keepers | 1003 | 41,250.00 |
All five productions appear. The Lantern Keepers appears twice, once for each of its invoices, and the two productions with no invoices appear once each, with empty invoice columns.
Finding rows with no match
Section titled “Finding rows with no match”Those empty columns are NULL, which makes them easy to pick out. To find the productions that have no invoices at all:
SELECT Productions.TitleFROM ProductionsLEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionIDWHERE Invoices.InvoiceID IS NULL;| Title |
|---|
| Saltmarsh |
| Fennick’s Return |