Sub topic 12
Joining Along Keys
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand rows, columns, and NULL. It also assumes that customers has a primary key named customer_id and that orders has a foreign key with the same name.
A join combines rows from two or more tables. A key relationship tells SQL which rows belong together. For example, orders.customer_id stores the primary key value of the customer who placed each order.
Joining a child table to its parent
An inner join returns only rows with a match in both tables:
SELECT
c.customer_id,
c.name,
o.order_id,
o.ordered_at
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY o.ordered_at;The ON condition compares the foreign key in orders with the primary key in customers. The table aliases c and o make the query shorter and clarify which table owns each column.
The result has one row for each matching customer-order pair. A customer with five orders appears five times. A customer with no orders does not appear because an inner join requires a match.
Choosing the join type
Use the join type that matches the question:
| Question | Join |
|---|---|
| Which customers have orders? | `JOIN` or `INNER JOIN` |
| Which customers have orders, including customers with none? | `LEFT JOIN` |
| Which orders have a valid customer? | `JOIN`, with the foreign key enforced |
To include every customer, place customers on the left:
SELECT
c.name,
o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY c.name, o.order_id;For a customer without orders, o.order_id is NULL. This is different from a missing relationship caused by bad data. A declared foreign key prevents an order from storing a non-existent customer ID.
Joining several relationships
You can follow multiple foreign keys in one query. Suppose order_items links orders to products:
SELECT
o.order_id,
p.name AS product_name,
oi.quantity
FROM orders AS o
JOIN order_items AS oi
ON oi.order_id = o.order_id
JOIN products AS p
ON p.product_id = oi.product_id
ORDER BY o.order_id, p.name;Each join can multiply rows. One order with three products produces three result rows. Do not add DISTINCT automatically to hide unexpected duplicates. First check whether the relationship legitimately has multiple matching rows.
For efficient joins, index foreign key columns that are frequently searched or joined:
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);PostgreSQL does not automatically create this index when you declare the foreign key.
Exercise
What rows does a LEFT JOIN return when a customer has no orders?
Show answer
It returns the customer row and fills the selected orders columns with NULL.