🏠 Home / Hub

🗄️ SQL Lesson 03 — JOINs

← Back to SQL Menu

1. JOIN ဘာကြောင့် လိုလဲ?

Database မှာ data ကို table တစ်ခုမှာ မသိမ်းဘဲ ခွဲထားတယ် (normalization):

🗂️ users table — user info
🗂️ orders table — order info (user_id reference ပဲ ပါ)

JOIN = ဒီ table နှစ်ခုကို ချိတ်ပြီး တစ်ချက်ဆွဲဖတ်

users table

idnamecity
1Ko MinYangon
2Ma AyeMandalay
3Ko KyawBago

orders table

iduser_idproducttotal
11Phone500
21Case20
32Laptop1200
44Tablet400

2. INNER JOIN — Both tables match ဖြစ်ရ

-- 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):

namecityproducttotal
Ko MinYangonPhone500
Ko MinYangonCase20
Ma AyeMandalayLaptop1200
Ko Kyaw (id=3) မပါ — orders table မှာ user_id=3 မရှိ
orders id=4 (user_id=4) မပါ — users table မှာ id=4 မရှိ

3. LEFT JOIN — Left table အကုန်ပါ

-- 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:

namecityproducttotal
Ko MinYangonPhone500
Ko MinYangonCase20
Ma AyeMandalayLaptop1200
Ko KyawBagoNULLNULL
Ko Kyaw ပါတယ် — product/total က NULL (no orders)

4. RIGHT JOIN — Right table အကုန်ပါ

-- 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:

nameproducttotal
Ko MinPhone500
Ko MinCase20
Ma AyeLaptop1200
NULLTablet400
Tablet order ပါတယ် — user_id=4 ရဲ့ user မရှိ (NULL)

5. Multiple JOINs

-- 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;

6. JOIN Types Summary

JOIN TypeReturns
INNER JOINBoth tables match ဖြစ်တဲ့ rows ပဲ
LEFT JOINLeft table အကုန် + Right match ဖြစ်တာ (မဖြစ်ရင် NULL)
RIGHT JOINRight table အကုန် + Left match ဖြစ်တာ (မဖြစ်ရင် NULL)
CROSS JOINCartesian product (every combination)
အများဆုံး သုံးတာ: INNER JOIN (match only) နဲ့ LEFT JOIN (all + optional match)
Tip: Table alias (u, o) သုံးပါ — code ဖတ်ရ ပိုလွယ်တယ်

← SQL 02  |  Next: SQL Lesson 04 → Aggregate Functions →

📌 Study Checklist