Inner, outer, self & cross joins
Pick the right join and explain why rows appear or go missing.
By Invicly Tech, , in SQL & PostgreSQL. About 10 minutes to read.
In short
A join combines rows from two tables using a matching condition, usually a foreign key. The join type decides what happens to rows that have no match: dropped, kept with NULLs, or paired with everything.
Explained simply
Good databases split information into separate tables so each fact is stored once. Customers live in one table, orders in another. Each order holds a customer_id that points back to its customer. A join is how you put the pieces back together in one result.
Imagine two lists on your desk: guests and seat bookings. To print a seating chart you match each booking's guest number to a guest's name. That matching rule is the ON part of a join: ON bookings.guest_id = guests.id.
The type of join answers one question: what should happen to rows that find no partner? INNER JOIN drops them. LEFT JOIN keeps everything from the first table and fills the gaps with NULL. FULL JOIN keeps unmatched rows from both sides.
Joins are not limited to two tables. You can chain them: customers to orders, orders to order items, items to products. Each JOIN adds one more table, matched by its own ON condition.
Press Play on a diagram to walk through it one step at a time.
- Only rows with a match on both sides
- Unmatched customers disappear
- Most common join
- Every left row is kept
- No match: right columns are NULL
- Find missing: WHERE right.id IS NULL
- All rows from both sides
- NULLs fill either side
- Good for reconciling lists
- Drop them
- INNER JOIN
- Keep all rows of the first table
- LEFT JOIN
- Unmatched columns become NULL
- Keep unmatched rows from both
- FULL OUTER JOIN
- I want only the unmatched ones
- LEFT JOIN ... WHERE right.id IS NULL
- or NOT EXISTS
- There is no match condition
- CROSS JOIN: every pair
- Step 1customers
Ann: 1 row
- Step 2JOIN orders
Ann has 3 orders: 3 rows
- Step 3JOIN order_items
4 items per order: 12 rows
- Step 4SUM(orders.total)
Each order total counted 4 times
In depth
How Postgres actually performs a join
The join you write says what you want, not how to get it. The planner picks one of three methods.
A nested loop takes each row on one side and looks up matches on the other, ideally through an index. It is great when one side is small. A hash join reads the smaller table into an in-memory hash table, then scans the bigger table once and probes the hash for each row. It is great for large, unsorted inputs with an equality condition. A merge join sorts both sides by the join key and walks them together like a zip. It suits inputs that are already sorted, for example by an index.
You can see which one was chosen with EXPLAIN. You rarely need to force it; good indexes and fresh statistics let Postgres choose well.
- Nested loop: small outer side + index on inner
- Hash join: big tables, equality join
- Merge join: both sides sorted on the key
- For each outer row, find matches
- Best when one side is small
- Index on the inner side helps
- Build a hash table of the smaller side
- Scan the bigger side once and probe
- Needs an equality condition
- Both sides sorted on the key
- Walk both lists in step
- Good when an index gives sorted order
Row counts: why joins multiply
A join returns one output row for every pair of rows that match. If a customer has 3 orders, that customer appears 3 times. If each order has 4 items and you also join items, the customer appears 12 times.
This is correct behaviour, but it surprises people when they then add SUM(orders.total): every order total is now counted 4 times, once per item. This is called fan-out. Before summing, ask what one row of the joined result stands for. If it is "one order item", only sum item-level columns. If you need order-level totals, sum them in a separate subquery first and then join the results.
ON vs WHERE with outer joins
With an INNER JOIN, a condition behaves the same in ON or in WHERE. With a LEFT JOIN it does not.
Conditions in ON decide which right-side rows count as a match. Left rows are kept no matter what. Conditions in WHERE run after the join and remove whole result rows. So LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid' keeps every customer and only attaches paid orders. Moving o.status = 'paid' into WHERE throws away customers with no paid order, because their o.status is NULL. The query has silently become an inner join.
- Every customer is kept
- Only paid orders are attached
- No paid order: order columns are NULL
- Runs after the join
- Rows with NULL status are removed
- Customers with no paid order vanish
Join shortcuts: USING and LATERAL
When both tables name the key the same way, JOIN orders USING (customer_id) is shorter than writing the ON condition, and the result has a single customer_id column.
LATERAL is a more advanced tool. It lets a subquery on the right refer to columns of the current left row, like a loop. For example, for each customer you can fetch their three latest orders with a LATERAL subquery that uses ORDER BY and LIMIT 3. A plain join cannot do per-row limits like that.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Write inner joins~1h
- 2Use left and full outer joins~1h
- 3Join a table to itself~1h
- 4Explain missing and duplicated rows~1h
Key points
- Join on keys: JOIN orders o ON o.customer_id = c.id.
- One-to-many joins repeat the "one" side once per matching row.
- A WHERE filter on the right table of a LEFT JOIN turns it into an inner join.
- A self join joins a table to itself with two aliases, e.g. employee and manager.
- CROSS JOIN pairs every row with every row: rows multiply.
Key terms
Tap a card to flip it. 0/5 known
Examples
-- customers with no orders
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
-- employees and their managers (self join)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;A three-table order report
The team wants every order line from today with the customer name and product name. Step 1: start from order_items, the finest grain. Step 2: join orders to get the date and customer_id. Step 3: join customers for the name. Step 4: join products for the product name. Each JOIN uses the foreign key that links the two tables. One output row equals one order line.
SELECT o.id AS order_id, c.name AS customer,
p.name AS product, oi.qty, oi.unit_price
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN customers c ON c.id = o.customer_id
JOIN products p ON p.id = oi.product_id
WHERE o.ordered_at >= current_date
ORDER BY o.id;Every product with its sales this month, including zero
A plain join would hide products that sold nothing. Step 1: start from products, because every product must appear. Step 2: LEFT JOIN order_items. Step 3: collect this month's order lines in a subquery and LEFT JOIN that, so the date filter can never remove a product. Step 4: COALESCE the sum to show 0 instead of NULL.
SELECT p.name, COALESCE(SUM(s.qty), 0) AS units_sold
FROM products p
LEFT JOIN (
SELECT oi.product_id, oi.qty
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.ordered_at >= date_trunc('month', now())
) s ON s.product_id = p.id
GROUP BY p.id, p.name
ORDER BY units_sold DESC;Quick reference
- FROM a JOIN b ON b.a_id = a.id (JOIN alone means INNER JOIN)
- LEFT JOIN keeps every row of the left table; missing right columns are NULL
- Right-table filters for LEFT JOIN go in ON, not WHERE
- Anti-join: LEFT JOIN b ... WHERE b.id IS NULL, or WHERE NOT EXISTS (...)
- JOIN ... USING (col) when both tables use the same column name
- Rows out = matching pairs; one-to-many joins repeat the one side
- Count rows before and after each join to catch fan-out early
Common mistakes
- Putting a right-table filter in WHERE instead of ON in a LEFT JOIN.
- Joining two one-to-many tables at once and double-counting totals.
- Forgetting the ON condition, accidentally creating a huge cross join.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List every order id with the customer's name, using orders(id, customer_id) and customers(id, name).
- Exercise 2medium
Find products that have never been ordered, using products(id, name) and order_items(product_id).
- Exercise 3hard
For each customer, show their 2 most recent orders (customers with no orders should still appear once).
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is RIGHT JOIN ever needed?
- Never strictly. A RIGHT JOIN B is the same as B LEFT JOIN A, and most teams write everything as LEFT JOIN so queries read the same way.
- Is JOIN the same as INNER JOIN?
- Yes. The word INNER is optional, so JOIN on its own means an inner join.
- Should I use a join or a subquery?
- Use a join when you need columns from both tables. Use EXISTS or NOT EXISTS when you only need to check whether a match exists; it also avoids duplicate rows.