All questions

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

Add a Q&A

Drop an image here or click to choose. It is saved as images/N.ext.

Live preview

Publish to GitHub

Drafts 0

Drafts live in this browser only. Download or push them to make them public.

    Files to commit

    data/qa.json
    sitemap.xml
    robots.txt

    Push with the GitHub API

    Uses a fine-grained token with Contents: Read and write on your repo. The token stays in this page's memory only: it is never saved or sent anywhere except api.github.com.