✅ SQL JOINS
What a JOIN is
• A JOIN combines data from two or more tables
• Tables connect using a common column
• That column is usually an ID
• JOIN answers questions one table cannot answer
Why JOINs exist
• Customer details sit in one table
• Orders sit in another table
• JOIN links customers to their orders
Example tables
customers
customer_id | name | city
orders
order_id | customer_id | amount
Connection
• customers.customer_id is primary key
• orders.customer_id is foreign key
• This shared column enables JOIN
Types of JOINs you must know
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• SELF JOIN
INNER JOIN
• Returns only matching rows from both tables
• Drops anything without a match
SELECT name, amount
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;
• Matches customers with their orders
• Shows only customers who placed orders
• Removes customers with no orders
• Removes orders without customers
LEFT JOIN
• Returns all rows from left table
• Matches data from right table
• Shows NULL when no match exists
SELECT name, amount
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id;
• Returns every customer
• Shows order amount if available
• Shows NULL if customer never ordered
RIGHT JOIN
• Returns all rows from right table
• Matches data from left table
• Opposite of LEFT JOIN
SELECT name, amount
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id;
• Returns all orders
• Shows customer name if exists
• Shows NULL for missing customer data
FULL JOIN
• Returns all rows from both tables
• Matches where possible
• Shows NULL when no match
SELECT name, amount
FROM customers
FULL JOIN orders
ON customers.customer_id = orders.customer_id;
• Shows all customers
• Shows all orders
• Includes unmatched data from both sides
SELF JOIN
• Table joins with itself
• Used for hierarchy or comparison
SELECT e.name, m.name AS manager_name
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;
• Matches employee with manager
• Uses same table twice
• Shows reporting hierarchy
JOIN Comparison Summary
• INNER JOIN: Only matching data
• LEFT JOIN: All left table rows
• RIGHT JOIN: All right table rows
• FULL JOIN: Everything from both tables
• SELF JOIN: Table joins itself
Double Tap ♥️ For More