Explain it simply
Explain it simply
Imagine a school with one book listing students and another listing exam results. The results book holds only student numbers, not names. To know who scored what, you match equal numbers across the two books. A JOIN does that matching inside the database.
An online shop works the same way: the customers table stores customer details, and the orders table points each order at a customer through customer_id. A JOIN pairs rows with the same customer_id, so an order and its customer's name appear on one row.
Problem → Why → Solution
The problem: everything crammed into one table
Before learning JOIN, many developers build one table where every order repeats the customer's name and country. If Antonio Moreno places 20 orders, his name is stored 20 times. When he moves country, all 20 rows need updating, and if one is missed the database claims he lives in two countries. A customer who has not ordered yet has nowhere to be stored at all.
-- one table, customer details copied onto every order
-- order_id | customer_name | country | order_date
-- 10309 | Antonio Moreno | Mexico | 1996-09-19
-- 10310 | Antonio Moreno | Mexico | 1996-09-20
UPDATE orders_flat SET country = 'Spain'
WHERE order_id = 10309; -- forgot 10310: Antonio now lives in two countriesWhy splitting the tables works better
Store each fact in exactly one place and there is only one place to update, so the copies can never disagree. This idea is called normalization. The customers table keeps one row per customer, and orders keeps only a customer_id foreign key. The price is that reading the data means reconnecting the tables, and JOIN is the tool that reconnects them.
Core concept: a JOIN tests pairs of rows
The easiest way to understand a JOIN is this picture: every row of the left table is paired with every row of the right table, and only pairs for which the ON condition is true are kept. With 4 customers and 4 orders there are 16 possible pairs, and ON o.customer_id = c.customer_id keeps the 3 that match. The database does not really build all 16 pairs, since indexes give it faster strategies, but the result always agrees with this mental model.
One important consequence follows from that model: the number of output rows need not equal either table's row count. Antonio Moreno has two orders, so he appears twice; this is a one-to-many relationship. If you expect one row per customer, that surprises you, so before running a join ask "what does one output row represent?" Here the answer is "one order".
The join types differ in exactly one decision: what to do with rows that find no partner. INNER JOIN keeps only matched pairs. LEFT JOIN keeps every left row and fills the right-hand columns with NULL when there is no match. RIGHT JOIN is the mirror image. FULL JOIN keeps unmatched rows from both sides. CROSS JOIN has no ON condition and returns every possible pair.
Both tables contain a column called customer_id, so every column is written as alias.column, like c.customer_id, to say which table it comes from. In FROM customers AS c, c is the alias. The two columns in ON are usually a primary key and the foreign key that points at it.
| Join type | Rows it keeps | Rows here |
|---|---|---|
| INNER JOIN | Matched pairs only | 3 |
| LEFT JOIN | Matched + left-only | 5 |
| RIGHT JOIN | Matched + right-only | 4 |
| FULL JOIN | Matched + both kinds of leftovers | 6 |
| CROSS JOIN | Every possible pair (4 x 4) | 16 |
customers (left) and orders (right) matched on customer_id
----------------------------------------------------------
customers (left) orders (right)
id customer_name order_id customer_id
1 Alfreds Futterkiste .... (none)
2 Ana Trujillo <---- 10308 2
3 Antonio Moreno <---- 10309 3
<---- 10310 3
4 Around the Horn .... (none)
(none) .... 10311 NULL (guest checkout)
matched pairs: 3 left-only: 1 and 4 right-only: 10311- Consider every pair of rows
- Test each pair with the ON condition
- Keep the pairs where it is true
- Join type decides leftover rows
INNER throws leftover rows away; the OUTER joins keep them and pad the missing side with NULLs.
General pattern
SELECT a.column_name, b.column_name
FROM left_table AS a
[INNER | LEFT | RIGHT | FULL] JOIN right_table AS b
ON b.foreign_key = a.primary_key;
-- every combination, no ON clause
SELECT a.column_name, b.column_name
FROM left_table AS a
CROSS JOIN right_table AS b;The table after FROM is the "left" one and the table after JOIN is the "right" one. The keyword before JOIN decides what happens to unmatched rows, and ON decides which rows form a pair. A bare JOIN means INNER JOIN.
Example: seeing all three kinds of rows with a FULL JOIN
There are four customers; Alfreds and Around the Horn have not ordered yet. Order 10311 was a guest checkout with no account, so its customer_id is NULL. A FULL JOIN keeps every row, and a CASE expression labels what kind of row each one is. From those labels you can predict what every other join type would return.
SELECT c.customer_name,
o.order_id,
CASE
WHEN o.order_id IS NULL THEN 'customer only'
WHEN c.customer_id IS NULL THEN 'order only'
ELSE 'matched'
END AS match_status
FROM customers AS c
FULL JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;Code breakdown
- Line 1-2
SELECT c.customer_name,c.customer_name comes from customers and o.order_id from orders; the aliases make each column's source table obvious.
- Lines 3-7
WHEN o.order_id IS NULL THEN 'customer only'CASE tests its conditions top to bottom. A NULL on the order side means a customer with no order, a NULL on the customer side means an order with no owner, and everything else is matched.
- Line 8
FROM customers AS ccustomers is the left table and gets the alias c.
- Line 9
FULL JOIN orders AS o ON o.customer_id = c.customer_idPairs rows with equal customer_id and keeps unmatched rows from both sides. A comparison like NULL = 2 is never true, so order 10311 pairs with no customer.
- Line 10
ORDER BY c.customer_id, o.order_id;Sorts by customer. In PostgreSQL NULL sorts last in ascending order, so the ownerless order 10311 appears at the bottom.
customer_name | order_id | match_status
---------------------+----------+---------------
Alfreds Futterkiste | | customer only
Ana Trujillo | 10308 | matched
Antonio Moreno | 10309 | matched
Antonio Moreno | 10310 | matched
Around the Horn | | customer only
| 10311 | order only
(6 rows)Reading every join type off that result
Group the six example rows by their label and the answer for every join type appears. This way of thinking lets you predict a result before running the query. The next two lessons study INNER JOIN and LEFT JOIN in depth.
- INNER JOIN = the 3 matched rows (10308, 10309, 10310)
- customers LEFT JOIN orders = 3 matched + 2 customer-only = 5 rows
- customers RIGHT JOIN orders = 3 matched + 1 order-only = 4 rows
- FULL JOIN = all six rows; CROSS JOIN = 4 x 4 = 16 rows (no ON)
USING (customer_id) is shorthand for ON o.customer_id = c.customer_id and works when both columns share a name. LEFT JOIN can also be written LEFT OUTER JOIN with the same meaning. MySQL has no FULL JOIN, so there you combine a LEFT JOIN and a RIGHT JOIN with UNION.
SELECT c.customer_name, o.order_id
FROM customers AS c
JOIN orders AS o USING (customer_id)
ORDER BY o.order_id;In real projects
Where this shows up in real projects
An application screen usually knows more than any single table. An order-history page joins orders with customers, products and shippers to show names. An admin list of "customers who have never ordered" is a LEFT JOIN. In data warehouses, joining a fact table of individual sales to dimension tables such as product, store and date is the backbone of every report.
Even with an ORM such as Prisma, the Django ORM or SQLAlchemy, joins are being generated underneath. The N+1 problem, where opening one page fires hundreds of queries, comes from fetching related data one row at a time, and fetching it with a single JOIN is usually the fix. Indexes on foreign-key columns are the main thing that keeps those joins fast.
Common mistakes
Common mistakes
1. Forgetting the join condition
Listing tables with a comma, FROM customers, orders, and forgetting the linking condition in WHERE gives a CROSS JOIN. That is 16 rows here, but a hundred million for two tables of 10,000 rows each. Use the JOIN ... ON syntax: PostgreSQL rejects an INNER or LEFT JOIN without ON as a syntax error, so it is hard to forget.
2. Joining on the wrong columns
Joining columns that share a type but not a meaning, such as ON o.order_id = c.customer_id, raises no error and quietly matches the wrong rows. Always pair a foreign key with the primary key it references, and name columns so that relationship is obvious.
3. Assuming one row per customer
Joining customers to orders repeats each customer once per order. Counting that result as "number of customers" counts Antonio twice. Decide what one output row represents before you count, and use COUNT(DISTINCT c.customer_id) when you need distinct customers.
Mini challenge
Mini challenge: staff without a department, departments without staff
departments holds three departments and employees holds four people. Ko Ko has no department yet, and Research has no staff. Find both kinds of "unpaired" rows in one query.
- Join employees and departments on dept_id
- Choose the join type that keeps unmatched rows from both sides
- Remove the matched rows with WHERE
- Show emp_name and dept_name
SELECT e.emp_name, d.dept_name
FROM employees AS e
-- TODO: pick the join type that keeps leftovers from BOTH tables
-- and join on dept_id
-- TODO: keep only rows where one side is missing (IS NULL)
;Expected: Two rows, Ko Ko and Research: emp_name | dept_name ----------+----------- Ko Ko | | Research (2 rows)
Show hint
After a FULL JOIN, an unmatched row has NULL in the other side's primary key. Test e.emp_id IS NULL OR d.dept_id IS NULL. Avoid testing e.dept_id: it is NULL for Ko Ko, but also on the Research row, which makes the logic confusing.
Show solution
SELECT e.emp_name, d.dept_name
FROM employees AS e
FULL JOIN departments AS d ON d.dept_id = e.dept_id
WHERE e.emp_id IS NULL
OR d.dept_id IS NULL
ORDER BY e.emp_name, d.dept_name;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Data is split across tables so each fact lives in one place, and JOIN reconnects it.
- A JOIN tests pairs of rows with the ON condition and keeps matches; one-to-many relationships repeat rows.
- Join types differ only in leftovers: INNER drops them, LEFT/RIGHT/FULL keep them with NULLs, CROSS keeps every pair.
- Before running a join, predict what one output row means and how many rows you will get.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group