JOIN Basics
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.”
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in