What is the difference between INNER JOIN and LEFT JOIN in SQL?
Answer
An `INNER JOIN` keeps only rows that have a match in both tables. A `LEFT JOIN` keeps every row from the left table and fills the right side with `NULL` when there is no match.
Use `LEFT JOIN` when you need to find rows that are missing a relation, for example customers with no orders: join, then filter on `orders.id IS NULL`.
Put filters on the right table in the `ON` clause, not in `WHERE`, or the left join quietly turns into an inner join.
SQL solution
-- Customers and their orders (only customers that have orders)
SELECT c.id, c.name, o.id AS order_id
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;
-- All customers, with NULL where no order exists
SELECT c.id, c.name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
-- Customers that have never ordered
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;Edited by Jack · joysait@rediffmail.com