users table
| id | name | city |
|---|---|---|
| 1 | Ko Min | Yangon |
| 2 | Ma Aye | Mandalay |
| 3 | Ko Kyaw | Bago |
orders table
| id | user_id | product | total |
|---|---|---|---|
| 1 | 1 | Phone | 500 |
| 2 | 1 | Case | 20 |
| 3 | 2 | Laptop | 1200 |
| 4 | 4 | Tablet | 400 |
-- Get orders with user names SELECT u.name, u.city, o.product, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id; -- INNER JOIN = JOIN (same thing) SELECT u.name, o.product FROM users u JOIN orders o ON u.id = o.user_id;
INNER JOIN result (only matching rows from both):
| name | city | product | total |
|---|---|---|---|
| Ko Min | Yangon | Phone | 500 |
| Ko Min | Yangon | Case | 20 |
| Ma Aye | Mandalay | Laptop | 1200 |
-- All users, even those without orders SELECT u.name, u.city, o.product, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id; -- Find users with NO orders SELECT u.name, u.city FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.id IS NULL;
LEFT JOIN result:
| name | city | product | total |
|---|---|---|---|
| Ko Min | Yangon | Phone | 500 |
| Ko Min | Yangon | Case | 20 |
| Ma Aye | Mandalay | Laptop | 1200 |
| Ko Kyaw | Bago | NULL | NULL |
-- All orders, even those without matching users SELECT u.name, o.product, o.total FROM users u RIGHT JOIN orders o ON u.id = o.user_id;
RIGHT JOIN result:
| name | product | total |
|---|---|---|
| Ko Min | Phone | 500 |
| Ko Min | Case | 20 |
| Ma Aye | Laptop | 1200 |
| NULL | Tablet | 400 |
-- 3 tables joined -- users → orders → products SELECT u.name AS customer, o.id AS order_id, p.name AS product, p.price, o.quantity, p.price * o.quantity AS total FROM users u INNER JOIN orders o ON u.id = o.user_id INNER JOIN products p ON o.product_id = p.id WHERE u.city = 'Yangon' ORDER BY total DESC;
| JOIN Type | Returns |
|---|---|
INNER JOIN | Both tables match ဖြစ်တဲ့ rows ပဲ |
LEFT JOIN | Left table အကုန် + Right match ဖြစ်တာ (မဖြစ်ရင် NULL) |
RIGHT JOIN | Right table အကုန် + Left match ဖြစ်တာ (မဖြစ်ရင် NULL) |
CROSS JOIN | Cartesian product (every combination) |
← SQL 02 | Next: SQL Lesson 04 → Aggregate Functions →