Joins Overview
So far, we have worked with data stored in a single table. In real-world databases, data is usually spread across multiple related tables.
SQL JOINs allow us to combine data from multiple tables and view it as a single result.
Why Do We Need Joins?
Databases are designed to avoid duplication. Instead of storing all information in one table, data is split into logical tables.
For example:
- Employee details in one table
- Department details in another table
- Project information in a separate table
To answer real questions, we must join these tables.
Example Tables
Consider the following two tables:
employees
+----+----------+---------------+--------+ | id | name | department_id | salary | +----+----------+---------------+--------+ | 1 | Alice | 101 | 75000 | | 2 | Bob | 102 | 72000 | | 3 | Charlie | 101 | 60000 | | 4 | Diana | 103 | 80000 | +----+----------+---------------+--------+
departments
+---------------+----------------+ | department_id | department_name| +---------------+----------------+ | 101 | IT | | 102 | HR | | 103 | Finance | +---------------+----------------+
What is a JOIN?
A JOIN combines rows from two or more tables based on a related column.
In our example:
employees.department_iddepartments.department_id
These columns create a relationship between the tables.
Basic JOIN Syntax
All joins follow a similar structure:
SELECT columns FROM table1 JOIN table2 ON table1.column = table2.column;
The ON condition defines how rows are matched.
Types of SQL Joins
| Join Type | Description |
|---|---|
| INNER JOIN | Returns matching rows from both tables |
| LEFT JOIN | Returns all rows from left table |
| RIGHT JOIN | Returns all rows from right table |
| FULL JOIN | Returns all rows from both tables |
We will study each join type in detail in the next lessons.
Visual Understanding (Conceptual)
Think of joins like matching circles:
- INNER JOIN → only overlapping part
- LEFT JOIN → entire left circle + overlap
- RIGHT JOIN → entire right circle + overlap
- FULL JOIN → both circles entirely
Simple Join Example
Let’s join employees with their department names.
SELECT e.name, d.department_name FROM employees e INNER JOIN departments d ON e.department_id = d.department_id;
Explanation:
- Tables are joined using department_id
- Each employee gets their department name
- Only matching records are returned
Table Aliases (Important)
Table aliases make queries easier to read.
employees edepartments d
Aliases are especially useful in joins and complex queries.
Common Beginner Mistakes
- Forgetting the ON condition
- Joining tables without related columns
- Confusing LEFT and RIGHT joins
- Not using table aliases
Why Joins Are Critical
Joins allow you to:
- Work with normalized databases
- Combine related information
- Build real-world reports
- Answer complex business questions
What’s Next?
In the next lesson, we will deep dive into INNER JOIN and understand how matching works in detail.