MySql Joins

Introduction

In MySQL, the JOIN clause is an essential tool for combining rows from two or more tables based on a related column between them. Understanding how to use different types of JOINs is crucial for efficiently querying relational databases. In this blog post, we will explore the various types of JOINs available in MySQL, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, with practical examples.

Types of JOINs in MySQL

1. INNER JOIN

An INNER JOIN returns records that have matching values in both tables. If there is no match, the row will not be included in the result set.

Example:

Consider two tables, employees and departments.

To find the names of employees and their respective departments:

SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;

2. LEFT JOIN (or LEFT OUTER JOIN)

A LEFT JOIN returns all records from the left table (employees), and the matched records from the right table (departments). The result is NULL from the right side if there is no match.

Example:

SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

3. RIGHT JOIN (or RIGHT OUTER JOIN)

A RIGHT JOIN returns all records from the right table (departments), and the matched records from the left table (employees). The result is NULL from the left side if there is no match.

Example:

SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;

4. FULL OUTER JOIN

A FULL OUTER JOIN returns all records when there is a match in either left (employees) or right (departments) table records. If there is no match, the result is NULL on the side that does not have a match. Note: MySQL does not support FULL OUTER JOIN directly, but you can achieve this using a UNION.

Example:

SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id
UNION
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
RSS
Follow by Email
LinkedIn
Share
Scroll to Top