JOIN Basics

Basic SQL
≈ 1 min read

JOIN matches rows from two sources

Suppose the orders table stores user_id, while user information lives in the users table. To return an order together with the user's name, the rows need to be matched by identifier.

SELECT orders.id, users.name
FROM orders
JOIN users ON users.id = orders.user_id;

The condition after ON tells the database which rows from the two tables belong together. As a result, each matching order row is combined with data from the corresponding user row.

Aliases make joins easier to read

SELECT o.id, u.name
FROM orders AS o
JOIN users AS u ON u.id = o.user_id;

The aliases o and u are especially useful when a query contains several tables or when tables have columns with the same names.

A JOIN without a clear matching condition can easily produce the wrong result. Before writing the query, describe the relationship in words first: for example, “an order belongs to a user when orders.user_id = users.id.”