Understanding LEFT JOIN, RIGHT JOIN, and INNER JOIN
INNER JOIN, LEFT JOIN, and RIGHT JOIN are used to combine rows from multiple tables, but they differ in how they handle unmatched rows.
• Returns ONLY the rows that have matching values in both tables.
• Rows without matches are excluded.
Example:
SELECT u.id, u.name, o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id;
• Output: Only users who have at least one order.
• Returns ALL rows from the left table.
• Matching rows from the right table are included.
• Non-matching rows from the right table appear as NULL.
Example:
SELECT u.id, u.name, o.amount
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
• Output: All users, even those with NO orders (order fields = NULL).
• Returns ALL rows from the right table.
• Matching rows from the left table are included.
• Non-matching left-table rows appear as NULL.
Example:
SELECT u.id, u.name, o.amount
FROM users u
RIGHT JOIN orders o ON u.id = o.user_id;
• Output: All orders, even if the referenced user is missing.
• INNER JOIN → Only matching rows.
• LEFT JOIN → All left table rows + matching right table rows.
• RIGHT JOIN → All right table rows + matching left table rows.
• LEFT and RIGHT JOIN include unmatched rows as NULL (INNER JOIN does not).
In summary: INNER JOIN shows only related data, while LEFT/RIGHT JOINs preserve all rows from one side, making them useful for detecting missing or optional relationships.