JOINS in MySQL
π AΒ JOIN is used to combine rows from two or more tables based on a related column.
Letβs assume we have two tables:
Customers
id | name | city |
---|---|---|
1 | John | Delhi |
2 | Priya | Mumbai |
3 | Ahmed | Kolkata |
Orders
order_id | customer_id | product |
---|---|---|
101 | 1 | Laptop |
102 | 2 | Mobile |
103 | 1 | Tablet |
104 | 4 | Camera |
1. INNER JOIN
β‘ Returns only rows with matching values in both tables.
SELECT c.name, o.product
FROM Customers c
INNER JOIN Orders o
ON c.id = o.customer_id;
Result:
name | product |
---|---|
John | Laptop |
Priya | Mobile |
John | Tablet |
2. LEFT JOIN (or LEFT OUTER JOIN)
β‘ Returns all rows from left table + matching rows from right table.
β‘ If no match β NULL.
SELECT c.name, o.product
FROM Customers c
LEFT JOIN Orders o
ON c.id = o.customer_id;
Result:
name | product |
---|---|
John | Laptop |
Priya | Mobile |
John | Tablet |
Ahmed | NULL |
3. RIGHT JOIN (or RIGHT OUTER JOIN)
β‘ Returns all rows from right table + matching rows from left table.
β‘ If no match β NULL.
SELECT c.name, o.product
FROM Customers c
RIGHT JOIN Orders o
ON c.id = o.customer_id;
Result:
name | product |
---|---|
John | Laptop |
Priya | Mobile |
John | Tablet |
NULL | Camera |
4. FULL JOIN (FULL OUTER JOIN)
β‘ Returns all rows from both tables, matching where possible, else NULL.
π MySQL does not support FULL JOIN
directly β use UNION
.
SELECT c.name, o.product
FROM Customers c
LEFT JOIN Orders o ON c.id = o.customer_id
UNION
SELECT c.name, o.product
FROM Customers c
RIGHT JOIN Orders o ON c.id = o.customer_id;
Result:
name | product |
---|---|
John | Laptop |
Priya | Mobile |
John | Tablet |
Ahmed | NULL |
NULL | Camera |
5. CROSS JOIN
β‘ Returns Cartesian product (all combinations).
SELECT c.name, o.product
FROM Customers c
CROSS JOIN Orders o;
Result: (3 customers Γ 4 orders = 12 rows)
name | product |
---|---|
John | Laptop |
John | Mobile |
John | Tablet |
John | Camera |
Priya | Laptop |
... | ... |
6. SELF JOIN
β‘ A table joins with itself.
Example: Find customers from the same city.
SELECT A.name AS Customer1, B.name AS Customer2, A.city
FROM Customers A, Customers B
WHERE A.city = B.city AND A.id <> B.id;
Result:
Customer1 | Customer2 | city |
---|---|---|
John | Ahmed | Delhi |
β Summary:
- INNER JOIN β Matching only.
- LEFT JOIN β All left + matches.
- RIGHT JOIN β All right + matches.
- FULL JOIN β All rows from both.
- CROSS JOIN β All combinations.
- SELF JOIN β Table joins with itself.