๐ SQL Fundamentals Part-4: JOINS
In real databases, data is stored in multiple tables, not one big table. JOINS allow you to combine data from different tables.
Example:
Customers Table
customer_id | name
1 | Rahul
2 | Priya
Orders Table
order_id | customer_id | amount
101 | 1 | 500
102 | 2 | 300
To see customer name + order amount, we must use JOIN.
Basic JOIN Syntax
SELECT columns
FROM table1
JOIN table2
ON table1.column = table2.column;
ON defines the relationship between tables.
1๏ธโฃ INNER JOIN
Returns only matching records from both tables.
SELECT customers.name, orders.amount
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;
Result:
name | amount
Rahul | 500
Priya | 300
๐ If a customer has no order, they will not appear.
2๏ธโฃ LEFT JOIN (Very Common โญ)
Returns: All rows from left table, Matching rows from right table, If no match โ NULL
SELECT customers.name, orders.amount
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id;
Result:
name | amount
Rahul | 500
Priya | 300
Amit | NULL
๐ Amit has no order.
3๏ธโฃ RIGHT JOIN
Opposite of LEFT JOIN. Returns: All rows from right table, Matching rows from left table
SELECT customers.name, orders.amount
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id;
Used less frequently in analytics.
4๏ธโฃ FULL JOIN
Returns: All records from both tables, If no match โ NULL
SELECT customers.name, orders.amount
FROM customers
FULL JOIN orders
ON customers.customer_id = orders.customer_id;
5๏ธโฃ SELF JOIN
A table joins with itself. Used when rows relate to other rows in the same table.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;
JOIN Visual Understanding
โข INNER JOIN: Only matching rows
โข LEFT JOIN: All left + matching right
โข RIGHT JOIN: All right + matching left
โข FULL JOIN: All rows from both
โข SELF JOIN: Table joined with itself
Real Data Analyst Examples
-- Customer order report
SELECT c.name, o.amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;
-- Products with category
SELECT p.product_name, c.category
FROM products p
JOIN categories c
ON p.category_id = c.category_id;
-- Sales by region
SELECT r.region_name, SUM(s.amount)
FROM sales s
JOIN regions r
ON s.region_id = r.region_id
GROUP BY r.region_name;
Used daily in Power BI dashboards, analytics queries, and reports.
Mini Practice Tasks
1. Show customer names with their order amount.
2. Show all customers even if they have no orders.
3. Show employees with their manager names.
4. Show products with their category name.
Common Interview Questions
โ Difference between INNER JOIN and LEFT JOIN
โ When to use SELF JOIN
โ Why LEFT JOIN is used in analytics
โ Difference between JOIN and UNION
โ Join execution order
Double Tap โฅ๏ธ For More
Post #2351
4.54K
- โค 19