Joining Customers to Orders in SQL
A join lets one result use columns from more than one table.
Real datasets are usually split into related tables. The
orders
table knows which customer placed an order, but the customer name lives in
customers.
A
JOIN
matches rows using a shared key. Here, both tables use
customer_id.
In
orders,
customer_id
isn't a new customer. It points back at the one row in
customers
that placed the order, and the join follows that pointer. The short names
after
as,
o
and
c, are table aliases:
o.customer_id
means the
customer_id
column of orders, which matters once two tables share a column name.
Follow the key, then filter
Build the join by matching the key columns first, then add filters after
the relationship is working. In this lesson, the join creates rows that
contain both order details and customer details, so the
state
filter can come from the customer table.
select a.id_column, b.detail_column
from table_a as a
join table_b as b
on a.shared_id = b.shared_id Leave the key match out and every order pairs with every customer: see why a JOIN without ON multiplies rows.
Schema · Garden Shop Tables · orders, customers 2 tables
One row per order. Unshipped orders have a null shipped_date.
One row per customer. Some customers have no phone on file.
Join orders to customers. Return the order id, order date, customer first name, customer last name, and order status for orders from PA customers, newest first.
Run your query to inspect the result.
Expected answer
- Columns: order_id, order_date, first_name, last_name, status.
- Rows: 9 Pennsylvania customer orders.
- The first row should be order 19 for Theo Brandt.
Related
INNER, LEFT, RIGHT, FULL, and CROSS joins.
Join types and common join patterns.
Practice join keys, left joins, duplicate rows, and debugging.
One-to-many joins can inflate totals.
Qualify shared columns with a table alias.
Nested SELECTs, IN, EXISTS, and correlation.