Skip to content
Byte Yatra Blogs

A friendly introduction to SQL joins

Inner, left and full joins explained with one small example you can run in five minutes

Byte Yatra Team

2 min read ·

Joins are where most people's SQL confidence goes to die. They do not need to. A join does one thing: it puts rows from two tables side by side when they share a value. Everything else is a question of what to do with the rows that do not match.

The example

Two tiny tables: customers, and the orders they placed.

customers.idname
1Asha
2Ben
3Chen
orders.idcustomer_idtotal
10140
11115
12260
13925

Notice two awkward rows: Chen has no orders, and order 13 belongs to customer 9, who does not exist.

Inner join: only the matches

SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id;

You get Asha twice and Ben once. Chen disappears (no orders) and order 13 disappears (no customer). An inner join keeps only rows that match on both sides.

Left join: keep everything on the left

SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;

Now Chen comes back, with empty (NULL) order columns. Use a left join when the question is about the left table: “every customer and their orders, if any”.

A handy trick: LEFT JOIN ... WHERE o.id IS NULL finds customers who never ordered.

Full join: keep everything

SELECT c.name, o.id AS order_id, o.total
FROM customers c
FULL JOIN orders o ON o.customer_id = c.id;

Chen and order 13 both appear, each with empty columns on the side that is missing. Full joins are mostly for checking data: they show you what does not line up.

Picking the right one

QuestionJoin
Orders with their customer's nameInner
Every customer, even without ordersLeft
What does not match between two tables?Full

Three mistakes to avoid

  1. Joining on the wrong column. o.id = c.id runs without error and returns nonsense.
  2. Forgetting duplicates. One customer with three orders becomes three rows. Sums of customer fields will triple.
  3. Filtering a left join in WHERE. WHERE o.total > 20 quietly turns a left join back into an inner one. Put the condition in the ON clause instead.

Run the three queries above on the tiny tables, look at the rows, and joins stop being magic.

Responses

Loading responses