One idea
A JOIN connects rows using a relationship, usually a foreign key pointing to a primary key. You use it when the data you need is split across tables.
Why JOINs matter
Your feature should not store the same detail in many places. For example, an orders table can store user_id, while the users table stores the user name and phone.
When you need to show an order list with buyer names, you combine orders and users in the query. You do not copy the user name into every order row.
Basic INNER JOIN
Use INNER JOIN when you only want rows that have a match in both tables. This is good for required relationships, like an order that must belong to a user.
-- List orders with buyer details
SELECT
orders.id AS order_id,
orders.total_rupees,
orders.status,
users.name AS buyer_name,
users.email AS buyer_email
FROM orders
INNER JOIN users
ON orders.user_id = users.id
ORDER BY orders.id DESC;Read the query
FROM says the main table you are reading from. INNER JOIN names the second table. ON explains how the two tables match.
Use table names before column names when both tables may have the same column, like id or created_at. Use AS to give readable names to the output.
LEFT JOIN for missing data
Use LEFT JOIN when you want every row from the left table, even if the joined table has no match. This helps with optional data.
For example, not every student profile may have a submitted project yet. A LEFT JOIN can still show all students.
-- Show all students, with project title if submitted
SELECT
students.id AS student_id,
students.name,
projects.title AS project_title
FROM students
LEFT JOIN projects
ON projects.student_id = students.id
ORDER BY students.name;Common mistake
Do not join tables without an ON condition. You can accidentally create too many rows, where every row from one table is paired with every row from the other.
If your result suddenly has hundreds of rows for a small seed file, check your ON line first.
Use AI safely
You can ask ChatGPT or Gemini to draft a JOIN query from your schema. Paste only your table definitions, not private data.
Then check three things yourself: the ON condition uses the right keys, the JOIN type matches your need, and the selected columns have clear aliases.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done