SQL Joins

By

Published · Updated

Tagged: Database

Learn how SQL joins work: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN and CROSS JOIN, with runnable examples, finding rows with no match, and the common pitfalls.

A join combines rows from two tables, matching them on a column they have in common. It’s how you answer questions like “which car does this person own?” when people and cars live in separate tables.

Suppose you have 2 tables, people and cars:

CREATE TABLE people (
  name VARCHAR(20) PRIMARY KEY,
  age INT NOT NULL
);

CREATE TABLE cars (
  id INT PRIMARY KEY,
  brand VARCHAR(20) NOT NULL,
  model VARCHAR(20) NOT NULL,
  owner VARCHAR(20)
);

We add some data. Flavio owns 2 cars, Roger owns 1, Syd owns none, and one car has no owner:

INSERT INTO people VALUES ('Flavio', 37);
INSERT INTO people VALUES ('Roger', 8);
INSERT INTO people VALUES ('Syd', 7);

INSERT INTO cars VALUES (1, 'Ford', 'Fiesta', 'Flavio');
INSERT INTO cars VALUES (2, 'Ford', 'Mustang', 'Roger');
INSERT INTO cars VALUES (3, 'Fiat', 'Panda', 'Flavio');
INSERT INTO cars VALUES (4, 'Tesla', 'Model 3', NULL);

I ran the queries on these tables in PostgreSQL 17 and SQLite 3.54, and both return the same rows.

A basic join

Say the police stopped Roger driving the Mustang. He looks young, and they want to know his age from their database.

Roger is my dog, but let’s suppose dogs can drive cars.

We can create a join with this syntax:

SELECT people.age
FROM people
JOIN cars ON people.name = cars.owner
WHERE cars.model = 'Mustang';

We’ll get this result back:

 age
-----
   8

What is happening? We are joining the two tables on two specific columns: name from the people table, and owner from the cars table. For each pair of rows where people.name = cars.owner is true, the database builds one combined row. Then WHERE keeps only the Mustang.

JOIN on its own is an inner join. INNER JOIN means exactly the same thing, the INNER keyword is optional.

Pick columns from both tables

Once two tables are joined, you can select columns from either of them. Short table aliases keep the query readable:

SELECT p.name, p.age, c.brand, c.model
FROM people p
JOIN cars c ON p.name = c.owner;
  name  | age | brand |  model
--------+-----+-------+---------
 Flavio |  37 | Ford  | Fiesta
 Flavio |  37 | Fiat  | Panda
 Roger  |   8 | Ford  | Mustang

Two things to notice:

Prefix columns with the table name or alias (p.name, not name). If both tables have a column with the same name, like id, an unprefixed name is ambiguous and the query fails. The PostgreSQL docs call qualifying all column names in a join good style, and I agree.

LEFT JOIN: keep every row from the first table

To list all people, including those without a car, use LEFT JOIN:

SELECT p.name, c.model
FROM people p
LEFT JOIN cars c ON p.name = c.owner;
  name  |  model
--------+---------
 Flavio | Fiesta
 Flavio | Panda
 Roger  | Mustang
 Syd    |

Every row from the left table (the one in FROM) is in the result. When there’s no matching car, the car columns are NULL.

LEFT OUTER JOIN is the same thing, OUTER is optional.

Find rows with no match

A very common question is “which people have no car?”. Use a LEFT JOIN and keep the rows where the right side is NULL:

SELECT p.name
FROM people p
LEFT JOIN cars c ON p.name = c.owner
WHERE c.id IS NULL;
 name
------
 Syd

Check a column that can never be NULL in a real match, like the primary key c.id. And use IS NULL, because = NULL is never true.

RIGHT JOIN and FULL OUTER JOIN

RIGHT JOIN is the mirror image: it keeps every row from the right table. This lists all cars, including the one without an owner:

SELECT p.name, c.model
FROM people p
RIGHT JOIN cars c ON p.name = c.owner;
  name  |  model
--------+---------
 Flavio | Fiesta
 Roger  | Mustang
 Flavio | Panda
        | Model 3

You can always rewrite a RIGHT JOIN as a LEFT JOIN by swapping the tables, and that’s what I usually do. The MySQL docs also recommend LEFT JOIN over RIGHT JOIN to keep queries portable.

FULL OUTER JOIN keeps unmatched rows from both sides:

SELECT p.name, c.model
FROM people p
FULL OUTER JOIN cars c ON p.name = c.owner;
  name  |  model
--------+---------
 Flavio | Fiesta
 Flavio | Panda
 Roger  | Mustang
 Syd    |
        | Model 3

Support varies by database:

WHERE vs ON in a LEFT JOIN

This is the pitfall that bites everyone at least once.

Say you want all people, plus their Ford if they have one. This looks right, but it’s not:

SELECT p.name, c.model
FROM people p
LEFT JOIN cars c ON p.name = c.owner
WHERE c.brand = 'Ford';
  name  |  model
--------+---------
 Flavio | Fiesta
 Roger  | Mustang

Syd is gone. WHERE runs after the join, and for Syd c.brand is NULL, so the condition is not true and the row is removed. Your LEFT JOIN silently turned into an inner join.

Put the condition in ON instead:

SELECT p.name, c.model
FROM people p
LEFT JOIN cars c ON p.name = c.owner AND c.brand = 'Ford';
  name  |  model
--------+---------
 Flavio | Fiesta
 Roger  | Mustang
 Syd    |

A condition in ON decides which rows match. A condition in WHERE filters the result after the join. With an inner join the two give the same result, with an outer join they don’t.

Counting with a LEFT JOIN

To count how many cars each person has, including zero, count a column from the right table:

SELECT p.name, COUNT(c.id) AS cars
FROM people p
LEFT JOIN cars c ON p.name = c.owner
GROUP BY p.name;
  name  | cars
--------+------
 Flavio |    2
 Roger  |    1
 Syd    |    0

Don’t use COUNT(*) here. It counts rows, and Syd still has one row in the result (with NULL car columns), so you’d get 1 instead of 0. COUNT(c.id) skips NULL values.

USING

When the join columns have the same name in both tables, USING is a shorter way to write the condition:

SELECT *
FROM orders
JOIN customers USING (customer_id);

This is the same as ON orders.customer_id = customers.customer_id, and SELECT * shows the customer_id column only once.

There’s also NATURAL JOIN, which joins on every column name the two tables share. I avoid it: the PostgreSQL docs point out that if someone later adds a column with the same name to both tables, the join starts using it too.

CROSS JOIN

CROSS JOIN pairs every row of the first table with every row of the second, with no condition:

SELECT COUNT(*) FROM people CROSS JOIN cars;

That’s 3 people times 4 cars, so 12 rows. It’s useful for things like generating every combination of sizes and colors.

You can also get it by accident. If you list tables with a comma, FROM people, cars, and forget the WHERE condition that links them, you get every combination. With big tables that’s a huge, wrong result, so prefer an explicit JOIN ... ON.

To learn the basics of reading data from one table first, see how to use SELECT.

Want me to talk about your product? You can sponsor this site.

Related posts about database: