SQL Joins
SQL Joins – Combining Tables for Richer Insights
In previous blogs, we learned how to retrieve, filter, and summarize data. But real-world databases usually have multiple tables, like employees, departments, sales, and customers. To get meaningful insights, you need to combine tables, and that’s where SQL joins come in.
In this blog, we’ll explore the different types of joins with practical examples.
1. What Is a SQL Join?
A join allows you to query data from two or more tables based on a related column.
Common example: You have an employees table and a departments table. To see employee names along with their department names, you need a join.
2. INNER JOIN
Returns rows that match in both tables.
Example: Employees with Their Departments
SELECT e.first_name, e.last_name, d.department_nameFROM employees eINNER JOIN departments dON e.department_id = d.department_id;
-
Only shows employees who are assigned to a department.
-
ONspecifies the matching column.
| first_name | last_name | department_name |
|---|---|---|
| John | Doe | Sales |
| Jane | Smith | IT |
3. LEFT JOIN (or LEFT OUTER JOIN)
NULL is returned.Example: All Employees and Their Departments
SELECT e.first_name, e.last_name, d.department_nameFROM employees eLEFT JOIN departments dON e.department_id = d.department_id;
-
Includes employees without a department.
| first_name | last_name | department_name |
|---|---|---|
| John | Doe | Sales |
| Mike | Ross | NULL |
4. RIGHT JOIN (or RIGHT OUTER JOIN)
Returns all rows from the right table and matching rows from the left table.
Example: All Departments and Their Employees
SELECT e.first_name, e.last_name, d.department_nameFROM employees eRIGHT JOIN departments dON e.department_id = d.department_id;
-
Includes departments with no employees assigned.
. FULL OUTER JOIN
Returns all rows from both tables, matching when possible, and NULL when there’s no match.
SELECT e.first_name, e.last_name, d.department_nameFROM employees eFULL OUTER JOIN departments dON e.department_id = d.department_id;
-
Shows all employees and all departments, matched where possible.
6. CROSS JOIN
SELECT e.first_name, d.department_nameFROM employees eCROSS JOIN departments d;
-
Every employee paired with every department.
7. Tips for Using Joins
-
Always specify the matching column with
ON. -
Use aliases (
eforemployees,dfordepartments) for readability. -
Joins can be combined with
WHERE,GROUP BY, andORDER BYfor powerful queries.
SQL joins are essential for combining related data across multiple tables. With joins, you can:
-
See richer insights about employees, customers, or sales.
-
Handle missing data with
LEFT,RIGHT, orFULL OUTER JOIN. -
Build complex queries for reporting and analytics.
Comments
Post a Comment