SELECT c.customer_id, c.customer_name, SUM(o.amount) AS total_spending
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name;
💰 11. Include Customers with Zero Spending
SELECT c.customer_id, c.customer_name, COALESCE(SUM(o.amount), 0) AS total_spending
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name;
🔢 12. JOIN + COUNT()
SELECT c.customer_id, c.customer_name, COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name;
Why
COUNT(o.order_id) instead of COUNT(*)?Because
COUNT(*) would count the LEFT JOIN row even when the customer has no matching order.⚠️ 13. A Very Common JOIN Mistake
SELECT ... WHERE o.amount > 500; -- This removes NULLs and behaves like INNER JOIN
Correct:
LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.amount > 500;
Important concept: With an OUTER JOIN, the location of a filter can change the result.
🔗 14. Joining More Than Two Tables
SELECT c.customer_name, o.order_id, p.product_name, o.amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN products p ON o.product_id = p.product_id;
🏢 15. Real-World Business Example
SELECT p.category, SUM(o.amount) AS total_revenue
FROM orders o
JOIN products p ON o.product_id = p.product_id
GROUP BY p.category
ORDER BY total_revenue DESC;
This is a typical Data Analyst query.
📈 16. JOIN + WHERE + GROUP BY + HAVING
Question:
«Find customers who spent more than ₹50,000.»
SELECT c.customer_id, c.customer_name, SUM(o.amount) AS total_spending
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name
HAVING SUM(o.amount) > 50000
ORDER BY total_spending DESC;
Logical flow: JOIN → GROUP BY → HAVING → ORDER BY
🪞 17. SELF JOIN
A table can also be joined to itself.
SELECT e.employee_name AS employee, m.employee_name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id;
🔢 18. CROSS JOIN
"CROSS JOIN" produces every possible combination of rows.
5 products x 4 regions = 20 rows
🚨 19. The Biggest JOIN Problem: Duplicate Rows
One customer has five orders → customer appears five times. This is the natural result of a one-to-many relationship.
If you want unique customers:
SELECT COUNT(DISTINCT c.customer_id)