MySQL JOIN
The JOIN
The clause in MySQL combines rows from two or more tables based on a related column. Joins are essential when retrieving data from multiple tables in a relational database.
Types of Joins
- INNER JOIN: Returns only the rows with matching values in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and the matching rows from the right table. Unmatched rows from the right table will have
NULL
values. - RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and the matching rows from the left table. Unmatched rows from the left table will have
NULL
values. - FULL JOIN (or FULL OUTER JOIN): Combines the results of both LEFT JOIN and RIGHT JOIN. Rows from either table that do not match will still appear, with
NULL
values for missing data (not supported natively in MySQL but can be simulated). - CROSS JOIN: Returns the Cartesian product of two tables.
- SELF JOIN: Joins a table to itself.
1. INNER JOIN
Syntax
Example
Get a list of employees and their department names:
Result
2. LEFT JOIN
Syntax
Example
Get a list of all employees, including those without departments:
Result
3. RIGHT JOIN
Syntax
Example
Get a list of all departments, including those with no employees:
Result
4. FULL JOIN (Simulated)
Since MySQL does not support FULL JOIN
natively, it can be simulated using UNION
.
Example
Get all employees and departments, even if there are no matches:
5. CROSS JOIN
Syntax
Example
Combine all employees with all projects:
Result
6. SELF JOIN
A self-join is when a table is joined to itself. It is useful for hierarchical or relational data.
Example
Find employees and their managers:
Best Practices for Using Joins
Use Aliases:
- Shorten table names for readability, e.g.,
employees e
.
- Shorten table names for readability, e.g.,
Filter Early:
- Use
WHERE
clauses to reduce the number of rows processed.
- Use
Be Cautious with CROSS JOIN:
- Ensure you need the Cartesian product; it can generate a massive result set.
Index Related Columns:
- Index the columns used in the
ON
condition for better performance.
- Index the columns used in the
Sample Data for Testing
Table: employees
Table: departments
Let me know if you'd like further examples or need help with advanced queries!