๐ง 1. What is a JOIN?
JOIN is used to combine data from multiple tables
๐ If data is stored in different tables โ JOIN helps you connect them
๐ Example Tables
๐จโ๐ผ employees
emp_id name dept_id
1 Amit 101
2 Neha 102
3 Ravi 101
๐ข departments
dept_id dept_name
101 IT
102 HR
๐ 2. INNER JOIN (Most Used ๐ฅ)
๐ Returns only matching records
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id;
โ Only employees with valid department
โฌ ๏ธ 3. LEFT JOIN
๐ Returns all records from left table + matched from right
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id;
โ Even if department is missing โ employee will still show
โก๏ธ 4. RIGHT JOIN
๐ Returns all records from right table + matched from left
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d
ON e.dept_id = d.dept_id;
๐ 5. FULL JOIN
๐ Returns all records from both tables
SELECT e.name, d.dept_name
FROM employees e
FULL JOIN departments d
ON e.dept_id = d.dept_id;
(Note: Not supported in MySQL directly โ use UNION instead)
โก 6. Quick Summary
โข INNER -> Only matching rows
โข LEFT -> All left + matched right
โข RIGHT -> All right + matched left
โข FULL -> Everything
๐ฏ 7. Practice Tasks
1. Get employee name with department name
2. Show all employees even if no department
3. Show all departments even if no employees
4. Find employees without department
5. Count employees per department (using JOIN)
๐ฅ Practice Task Solutions ๐
โ 1. Get employee name with department name (INNER JOIN)
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id;
โ 2. Show all employees even if no department (LEFT JOIN)
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id;
โ 3. Show all departments even if no employees (RIGHT JOIN)
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d
ON e.dept_id = d.dept_id;
๐ (Alternative using LEFT JOIN โ interview friendly)
SELECT e.name, d.dept_name
FROM departments d
LEFT JOIN employees e
ON e.dept_id = d.dept_id;
โ 4. Find employees without department
SELECT e.name
FROM employees e
LEFT JOIN departments d
ON e.dept_id = d.dept_id
WHERE d.dept_id IS NULL;
โ 5. Count employees per department (using JOIN)
SELECT d.dept_name, COUNT(e.emp_id) AS total_emp
FROM departments d
LEFT JOIN employees e
ON d.dept_id = e.dept_id
GROUP BY d.dept_name;
โก Mini Challenge ๐ฅ
๐ Find departments with no employees
โก Mini Challenge Solution ๐
SELECT d.dept_name
FROM departments d
LEFT JOIN employees e
ON d.dept_id = e.dept_id
WHERE e.emp_id IS NULL;
Double Tap โค๏ธ For More