MySQL Joins

MySQL Tutorial

MySQL Joins

In MySQL, joins are used to combine rows from two or more tables based on a related column between them. Joins are essential for retrieving data that is distributed across multiple tables.

Types of Joins in MySQL

Join TypeDescription
INNER JOINReturns only rows where matching values exist in both tables
LEFT JOIN (or LEFT OUTER JOIN)Returns all rows from the left table, and matched rows from the right table; unmatched rows from right table are NULL
RIGHT JOIN (or RIGHT OUTER JOIN)Returns all rows from the right table, and matched rows from the left table; unmatched rows from left table are NULL
FULL OUTER JOINReturns rows when there is a match in either table (Not directly supported in MySQL; use UNION)
CROSS JOINReturns Cartesian product of two tables (all combinations)

Example Tables

Students Table

student_idnamedept_id
1John1
2Emma2
3Raj1
4Sara3

Departments Table

dept_iddept_name
1IT
2HR
3Finance
4Sales

INNER JOIN

Returns only matching rows from both tables.

Output:

namedept_name
JohnIT
EmmaHR
RajIT
SaraFinance

LEFT JOIN

Returns all rows from the left table, and matched rows from the right table.

Output: (Same as INNER JOIN here, because all students have a department, but if a student had dept_id = 5, dept_name would be NULL)

namedept_name
JohnIT
EmmaHR
RajIT
SaraFinance

RIGHT JOIN

Returns all rows from the right table, and matched rows from the left table.

Output:

namedept_name
JohnIT
RajIT
EmmaHR
SaraFinance
NULLSales

Notice: “Sales” department has no student → name = NULL

CROSS JOIN

Returns all possible combinations between two tables.

Output: (4 students × 4 departments = 16 rows)

namedept_name
JohnIT
JohnHR
JohnFinance
JohnSales
EmmaIT
EmmaHR

FULL OUTER JOIN (MySQL Workaround)

MySQL doesn’t support FULL OUTER JOIN directly. Use UNION of LEFT JOIN and RIGHT JOIN:


 

Summary Table

Join TypeReturns
INNER JOINOnly matching rows
LEFT JOINAll left table rows + matched right table rows
RIGHT JOINAll right table rows + matched left table rows
FULL OUTERRows when match in either table
CROSS JOINAll combinations (Cartesian product)

You may also like...