Latest Post:

What is a SQL join?

Definition

A SQL join combines rows from tables, or multiple instances of a table, according to a matching condition. For example, orders can be paired with customers using a customer identifier. The join type determines how matches and records without a match contribute to the result.

An inner join returns matching pairs. A left join also retains rows from the left table without a match. If one record matches several others, the join can produce several result rows.

Why it matters

Joins often sit behind a surprising change in a report’s totals. A table of customers may have one row per customer, while a table of orders has several rows for each customer. Combining them changes the number of rows available to a later calculation, so the resulting total needs to be interpreted at the right level.

Before trusting a joined result, check the relationship:

  • Identify the fields used to match records and whether their values are unique.
  • Decide what should happen to records without a match.
  • Compare row counts and a known total before and after the join.

Use a small example where the expected matches are easy to inspect. That can reveal a problem more clearly than examining a large final chart.

Example: keeping orders without a matching customer

Suppose orders contains these three rows, with order totals in euros:

order_id customer_id order_total
101 1 100.00
102 1 50.00
103 4 80.00

The customers table contains two customers. There is no customer with identifier 4.

customer_id customer_name
1 Alma
2 Bram

A left join keeps every order and adds the customer name wherever an identifier matches:

SELECT orders.order_id,
       customers.customer_name,
       orders.order_total
FROM orders
LEFT JOIN customers
  ON orders.customer_id = customers.customer_id
ORDER BY orders.order_id;
order_id customer_name order_total
101 Alma 100.00
102 Alma 50.00
103 NULL 80.00

NULL means there is no matching name in this result. An inner join would drop order 103, reducing the order value shown from €230 to €150. Bram does not appear because there is no order for that customer. If a customer identifier appeared twice in customers, a matching order would appear twice too: checking the relationship before aggregation prevents inflated totals.