SQL JOIN
A JOIN combines rows from two tables using a related column, usually a foreign key such as orders.customer_id pointing to customers.id. JOIN on its own means INNER JOIN: only rows with a match on both sides are returned.
Joins are where SQL becomes powerful, and where most beginners get stuck. The trick is to always ask: which column links these two tables?
Syntax
SELECT a.col, b.col FROM table_a a JOIN table_b b ON b.id = a.b_id;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Two tables
SELECT o.id, c.first_name, c.last_name FROM orders o JOIN customers c ON c.id = o.customer_id;
Each order with its customer's name.
2. Three tables
SELECT o.id, p.name, oi.quantity FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id WHERE o.id = 1;
What was in order 1.
Common mistakes
- Forgetting the ON condition (or joining on the wrong columns), which multiplies rows.
- Ambiguous column names: write o.id and c.id, not just id.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
For every order, return the order id and the customer's first_name and last_name.
FAQ
Is JOIN the same as INNER JOIN?
Yes. INNER is optional.
What is the difference between INNER and LEFT JOIN?
INNER JOIN keeps only matching rows. LEFT JOIN keeps every row from the left table and fills in NULLs where there is no match.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.