CodeEraFree roadmap

Blogs

Introduction to SQL Joins: Inner, Outer, Left, Right, and Cross

SQL basics  , 2 min read

SQL joins combine data from multiple tables into a single result. There are five joins you should know: Inner, Left, Right, Full Outer and Cross. In the examples, table1 is the left table and table2 is the right table.

1. Inner Join

An Inner Join returns only the rows that have matching values in both tables.

SELECT column(s)
FROM table1
INNER JOIN table2
  ON table1.column = table2.column;

Here, column is the column used to match rows, and column(s) are the columns you want in the result.

2. Left Join

A Left Join returns all rows from the left table, and the matching rows from the right table. When there is no match on the right, the right-side columns are NULL.

SELECT column(s)
FROM table1
LEFT JOIN table2
  ON table1.column = table2.column;

A Right Join is the mirror image: all rows from the right table, and the matching rows from the left. When there is no match on the left, the left-side columns are NULL.

SELECT column(s)
FROM table1
RIGHT JOIN table2
  ON table1.column = table2.column;

4. Full Outer Join

A Full Outer Join returns all rows from both tables, with NULL where there is no match.

SELECT column(s)
FROM table1
FULL OUTER JOIN table2
  ON table1.column = table2.column;

MySQL does not support FULL OUTER JOIN. You can get the same result by combining a LEFT JOIN and a RIGHT JOIN with UNION.

5. Cross Join

A Cross Join returns the Cartesian product: every row of the first table paired with every row of the second. With 4 rows and 5 rows you get 20 rows. It has no ON clause.

SELECT column(s)
FROM table1
CROSS JOIN table2;

Quick comparison

JoinWhich rows you get
INNER JOINOnly rows that match in both tables
LEFT JOINAll left rows, plus matches from the right (NULL if none)
RIGHT JOINAll right rows, plus matches from the left (NULL if none)
FULL OUTER JOINAll rows from both tables
CROSS JOINEvery combination of rows

Joins are the tool that makes relational databases useful. Once these five are clear, most interview join questions become a matter of choosing which side must keep all its rows.

Practice them with the INNER and NATURAL JOIN sets.