A join reads two tables at once and pairs their rows up on a column they share. It is how a query answers a question that no single table can, such as which production each invoice was raised against.
Two related tables
Section titled “Two related tables”Alongside the Productions table from SQL Select, suppose the accounts team keeps a table of supplier invoices:
| InvoiceID | ProductionID | Supplier | Amount |
|---|---|---|---|
| 1001 | 1 | Hartwell Lighting | 24,600.00 |
| 1002 | 2 | Kestrel Catering | 3,180.00 |
| 1003 | 1 | Ashby Camera Hire | 41,250.00 |
| 1004 | 4 | Kestrel Catering | 2,940.00 |
An invoice does not repeat the production’s title. It holds the production’s ProductionID instead, which points at one row of Productions: invoices 1001 and 1003 both belong to production 1, The Lantern Keepers.
Joining them
Section titled “Joining them”To list each invoice with the title of its production, join the tables where their ProductionID values match:
SELECT Invoices.InvoiceID, Productions.Title, Invoices.Supplier, Invoices.AmountFROM InvoicesINNER JOIN Productions ON Invoices.ProductionID = Productions.ProductionID;| InvoiceID | Title | Supplier | Amount |
|---|---|---|---|
| 1001 | The Lantern Keepers | Hartwell Lighting | 24,600.00 |
| 1002 | Quarry Lane | Kestrel Catering | 3,180.00 |
| 1003 | The Lantern Keepers | Ashby Camera Hire | 41,250.00 |
| 1004 | Six Bells | Kestrel Catering | 2,940.00 |
Each column is written as Table.Column, because both tables have a ProductionID and the database needs to know which one you mean.
Saltmarsh and Fennick’s Return are missing from the result: they have no invoices, and an inner join keeps only rows that find a partner in the other table.
The four kinds of join
Section titled “The four kinds of join”The kinds of join differ in what they do with a row that has no partner:
INNER JOINkeeps only the rows that match in both tables.LEFT JOINkeeps every row of the first table, filling the second table’s columns withNULLwhere nothing matches.RIGHT JOINdoes the same the other way round, keeping every row of the second table.FULL OUTER JOINkeeps every row of both tables, matched up where they can be.
So Productions LEFT JOIN Invoices would return six rows: the four invoices above, each with its production, and then Saltmarsh and Fennick’s Return once each, beside empty invoice columns.