Multiple Table Joins: Mistakes
Module: Joins & Relationships
SELECT c.name, o.total, p.name
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN products p; -- Missing ON clause
SELECT c.name, o.total, p.name
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN order_items oi ON o.id = oi.order_id
INNER JOIN products p ON oi.product_id = p.id;
Every join needs its own ON clause. Missing ON clause multiplies result by all rows in that table.
Missing ON clause in multi-table join creates cartesian product
SELECT c.name, o.total, p.name
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
INNER JOIN products p ON o.product_id = p.id; -- Wrong join type
SELECT c.name, o.total, p.name
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
LEFT JOIN products p ON o.product_id = p.id;
INNER JOIN to products excludes customers without orders, defeating the LEFT JOIN purpose. Use LEFT JOIN consistently.
INNER JOIN after LEFT JOIN eliminates NULL rows from LEFT JOIN
SELECT customers.name, orders.total, products.name
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
INNER JOIN products ON orders.product_id = products.id;
SELECT c.customer_name, o.total_amount, p.product_name
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
INNER JOIN products p ON o.product_id = p.product_id;
Use short, meaningful aliases (c, o, p) instead of full table names for better readability.
No table aliases makes multi-table queries verbose and hard to read
SELECT *
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN order_items oi ON o.id = oi.order_id
INNER JOIN products p ON oi.product_id = p.id;
SELECT c.customer_name, o.order_date, p.product_name, oi.quantity
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN order_items oi ON o.id = oi.order_id