Join Basics: INNER JOIN

A join pairs rows from two tables that match a condition and makes each pair one row. INNER JOIN keeps only rows that have a match. A join that also keeps unmatched rows is an outer join.

JOIN … ON

Orders and customer names

SELECT o.ord_id, o.ord_dt, o.amt, c.cust_nm, c.grade
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.cust_id = 101
ORDER BY o.ord_id
  • JOIN is short for INNER JOIN.
  • The o in orders o is a table alias. When both tables have a column with the same name (cust_id), you must state which table it belongs to, as in o.cust_id.
  • Put the pairing condition in ON and the result filter in WHERE. With INNER JOIN either place gives the same result, but with an outer join it does not (outer join).

Joining three tables

Joins can be chained. Each next table attaches to the result of the previous join.

Orders, customers, grade names

SELECT o.ord_id, c.cust_nm, g.grade_nm, o.amt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
JOIN grade_cd g  ON g.grade = c.grade
WHERE o.cust_id IN (100, 101)
ORDER BY o.ord_id

Aggregating after a join

Order count and amount by grade (customers 101-300)

SELECT g.grade_nm, COUNT(*) AS orders, SUM(o.amt) AS total_amt
FROM customers c
JOIN grade_cd g ON g.grade = c.grade
JOIN orders o   ON o.cust_id = c.cust_id
WHERE c.cust_id BETWEEN 101 AND 300
GROUP BY g.grade_nm
ORDER BY orders DESC

How the row count changes

The row count of a join result is the number of pairs. If one customer has several orders, the customer row repeats once per order. So a SUM of a customer-side value after the join grows by the number of repeats.

Counting orders while trying to count customers

SELECT COUNT(*)                  AS joined_rows,
       COUNT(DISTINCT c.cust_id) AS customers
FROM customers c
JOIN orders o ON o.cust_id = c.cust_id
WHERE c.cust_id BETWEEN 101 AND 110

TIP If the row count after a join differs from what you expect, check whether the join key is unique on one side. customers.cust_id is the primary key and unique, so attaching customers to orders keeps the order count unchanged.

Old syntax: FROM a, b WHERE

Comma join (same result)

SELECT o.ord_id, c.cust_nm
FROM orders o, customers c
WHERE c.cust_id = o.cust_id
  AND o.cust_id = 101
ORDER BY o.ord_id

Listing tables with commas in FROM and writing the join condition in WHERE is also standard. If you omit the join condition, you get every combination of rows (a Cartesian product), so JOIN … ON, which separates join conditions from filter conditions, is recommended. When you need a Cartesian product, state the intent with CROSS JOIN.