Skip to content

SQL Join Operation

When using a JOIN clause in an SQL statement, it indicates how two tables are to be joined. This operation is fundamental for combining rows from two or more tables based on a related column between them.

Example Tables

Before diving into JOIN operations, let's consider two example tables: Album and Artist.

Artist

idname
1The Beatles
2Pink Floyd

Album

idtitleartist_id
1Abbey Road1
2The Dark Side of the Moon2

Genre

idname
1Rock
2Psychedelic Rock

Track

idtitlealbum_idgenre_id
1Come Together11
2Speak to Me22

Joining Tables With an ON Clause

The most common way to join tables is by using the ON clause to specify the condition for the join. This method combines rows when the join condition is true.

sql
SELECT Album.title, Artist.name FROM Album
  JOIN Artist ON Album.artist_id = Artist.id

Result:

titlename
Abbey RoadThe Beatles
The Dark Side of the MoonPink Floyd

Joining Tables Without an ON Clause

Joining tables without specifying an ON condition results in a Cartesian product between the two tables. This means each row from the first table is combined with all rows from the second table, which can lead to a large number of combinations.

sql
SELECT Album.title, Artist.name FROM Album
  JOIN Artist

Result:

titlename
Abbey RoadThe Beatles
Abbey RoadPink Floyd
The Dark Side of the MoonThe Beatles
The Dark Side of the MoonPink Floyd

Joining Multiple Tables

SQL allows joining more than two tables in a single query. This is useful for fetching data that spans across several related tables.

sql
SELECT
    Track.title AS track_title,
    Artist.name AS artist_name,
    Album.title AS album_title,
    Genre.name AS genre_name
FROM Track
  JOIN Genre ON Track.genre_id = Genre.id
  JOIN Album ON Track.album_id = Album.id
  JOIN Artist ON Album.artist_id = Artist.id

Result:

track_titleartist_namealbum_titlegenre_name
Come TogetherThe BeatlesAbbey RoadRock
Speak to MePink FloydThe Dark Side of the MoonPsychedelic Rock