Skip to content

SQL Joins

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.

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.

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.Amount
FROM Invoices
INNER 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 kinds of join differ in what they do with a row that has no partner:

  • INNER JOIN keeps only the rows that match in both tables.
  • LEFT JOIN keeps every row of the first table, filling the second table’s columns with NULL where nothing matches.
  • RIGHT JOIN does the same the other way round, keeping every row of the second table.
  • FULL OUTER JOIN keeps 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.

INNER JOIN: only the rows that match in both tables LEFT JOIN: every row of table1, with the matching rows of table2 RIGHT JOIN: every row of table2, with the matching rows of table1 FULL OUTER JOIN: every row of both tables, matched where they can be