JOIN Operations
JOIN Operations
Section titled βJOIN OperationsβWhat it means
Section titled βWhat it meansβA JOIN combines rows from two or more tables based on a related column. INNER JOIN returns only rows with matches in both tables; LEFT JOIN returns all rows from the left table plus matches from the right (NULL where thereβs no match); RIGHT JOIN is the mirror of LEFT; CROSS JOIN returns every combination of rows from both tables (a Cartesian product).
Examples
Section titled βExamplesβ-- INNER JOIN: only customers WITH orders appearSELECT c.Name, o.AmountFROM Customers cINNER JOIN Orders o ON c.Id = o.CustomerId;
-- LEFT JOIN: every customer appears, even those with zero orders (Amount is NULL)SELECT c.Name, o.AmountFROM Customers cLEFT JOIN Orders o ON c.Id = o.CustomerId;
-- Multiple joinsSELECT c.Name, o.Amount, p.Name AS ProductNameFROM Customers cINNER JOIN Orders o ON c.Id = o.CustomerIdINNER JOIN OrderItems oi ON o.Id = oi.OrderIdINNER JOIN Products p ON oi.ProductId = p.Id;
-- Find customers with NO orders at allSELECT c.NameFROM Customers cLEFT JOIN Orders o ON c.Id = o.CustomerIdWHERE o.Id IS NULL;Common mistake
Section titled βCommon mistakeβUsing INNER JOIN when you actually need LEFT JOIN β INNER JOIN silently drops rows from the left table that have no match on the right, which is easy to miss if youβre not specifically checking row counts (e.g. βcustomers with no ordersβ disappear entirely from the results).
-- Silently excludes customers who have never placed an orderSELECT c.Name, COUNT(o.Id) AS order_countFROM Customers cINNER JOIN Orders o ON c.Id = o.CustomerIdGROUP BY c.Name;
-- Correct: LEFT JOIN keeps every customer, showing 0 for those with no ordersSELECT c.Name, COUNT(o.Id) AS order_countFROM Customers cLEFT JOIN Orders o ON c.Id = o.CustomerIdGROUP BY c.Name;Quick practice
Section titled βQuick practiceβ-
Whatβs the key difference between
INNER JOINandLEFT JOIN?Answer
INNER JOINonly returns rows with a match in both tables;LEFT JOINreturns every row from the left table, filling in NULLs for any right-table columns where there's no match. -
How do you find rows in the left table that have no matching row in the right table?
Answer
Use aLEFT JOINand then filter withWHERE right_table.key IS NULLβ this catches only the rows where no match was found. -
What does
CROSS JOINproduce?Answer
Every possible combination of rows from both tables (a Cartesian product) β if table A has 3 rows and table B has 4, the result has 12 rows, with no join condition involved.