Introduction
We use LEFT JOIN to find rows in one table that do not have matching rows in another table. This helps spot missing or unmatched data.
Jump into concepts and practice - no test required
We use LEFT JOIN to find rows in one table that do not have matching rows in another table. This helps spot missing or unmatched data.
SELECT A.* FROM TableA A LEFT JOIN TableB B ON A.key = B.key WHERE B.key IS NULL;
The LEFT JOIN keeps all rows from the left table (TableA).
The WHERE clause filters to only rows where the right table (TableB) has no match (NULL).
SELECT customers.* FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.customer_id IS NULL;
SELECT employees.* FROM employees LEFT JOIN projects ON employees.id = projects.employee_id WHERE projects.employee_id IS NULL;
SELECT products.* FROM products LEFT JOIN sales ON products.id = sales.product_id WHERE sales.product_id IS NULL;
This example finds customers who have not placed any orders. Bob (id=2) has no orders, so he appears in the result.
CREATE TABLE customers (id INT, name VARCHAR(20)); CREATE TABLE orders (id INT, customer_id INT); INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'); INSERT INTO orders VALUES (1, 1), (2, 1), (3, 3); SELECT customers.id, customers.name FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.customer_id IS NULL ORDER BY customers.id;
Always check for NULL in the right table to find unmatched rows.
LEFT JOIN returns all rows from the left table, even if no match exists.
LEFT JOIN plus WHERE right_table.key IS NULL finds unmatched rows.
This technique helps find missing or orphan data in related tables.
LEFT JOIN combined with WHERE right_table.key IS NULL do in SQL?WHERE right_table.key IS NULL selects only those left table rows without a match in the right table.o.customer_id IS NULL selects customers without orders.employees(id, name) and tasks(employee_id, task_name), what does this query return?SELECT e.name FROM employees e LEFT JOIN tasks t ON e.id = t.employee_id WHERE t.employee_id IS NULL;
t.employee_id IS NULL selects employees with no matching tasks.SELECT p.product_id FROM products p LEFT JOIN sales s ON p.product_id = s.product_id WHERE p.product_id IS NULL;
p.product_id IS NULL is wrong because left table columns are never NULL in LEFT JOIN; should check s.product_id IS NULL.students(id, name) and enrollments(student_id, course_id). Write a query to find students not enrolled in any course, considering some students may have NULL IDs. Which query correctly handles this?e.student_id IS NULL finds students without courses; adding s.id IS NOT NULL excludes students with NULL IDs to avoid incorrect matches.