Today, let's understand SQL JOINS in detail: ๐
SQL JOINs are used to combine rows from two or more tables based on related columns.
๐ข 1. INNER JOIN
Returns only the matching rows from both tables.
Example:
SELECT Employees.name, Departments.dept_name
FROM Employees
INNER JOIN Departments
ON Employees.dept_id = Departments.id;
๐ Use Case: Employees with assigned departments only.
๐ต 2. LEFT JOIN (LEFT OUTER JOIN)
Returns all rows from the left table, and matching rows from the right table. If no match, returns NULL.
Example:
SELECT Employees.name, Departments.dept_name
FROM Employees
LEFT JOIN Departments
ON Employees.dept_id = Departments.id;
๐ Use Case: All employees, even those without a department.
๐ 3. RIGHT JOIN (RIGHT OUTER JOIN)
Returns all rows from the right table, and matching rows from the left table. If no match, returns NULL.
Example:
SELECT Employees.name, Departments.dept_name
FROM Employees
RIGHT JOIN Departments
ON Employees.dept_id = Departments.id;
๐ Use Case: All departments, even those without employees.
๐ด 4. FULL OUTER JOIN
Returns all rows from both tables. Non-matching rows show NULL.
Example:
SELECT Employees.name, Departments.dept_name
FROM Employees
FULL OUTER JOIN Departments
ON Employees.dept_id = Departments.id;
๐ Use Case: See all employees and departments, matched or not.
๐ Tips:
โฆ Always specify the join condition (ON)
โฆ Use table aliases to simplify long queries
โฆ NULLs can appear if there's no match in a join
๐ SQL Roadmap: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v/1506
๐ฌ Double Tap โค๏ธ For More!
Post #2434
12K
- โค 18
- ๐ 2
- ๐ 2