How Joins Work

Updated · 11 min read
mediumPostgreSQL 18sqljoinsinner-joinleft-joinhash-joininterview

A join combines rows from two tables by matching a column they share, so one query can answer a question whose facts live in different tables. A payment row says student_id 103, not "Navika". To list each payment with the student's name, the database must find, for every payment, the student whose student_id matches. That matching is a join, and it's the single most important idea in working with relational data. This lesson explains why tables are split in the first place, walks a join through step by step, introduces every kind of join, and shows how the database actually does the work.

In One Minute

  • Data is split into tables so each fact is stored once; joins put the facts back together.
  • FROM a JOIN b ON a.key = b.key pairs each row of a with the rows of b whose key matches.
  • INNER JOIN keeps only matched pairs; LEFT JOIN also keeps every row of the left table, with NULL where nothing matched.
  • Other kinds: RIGHT, FULL OUTER, self joins and CROSS JOIN, each with its own lesson.
  • The database runs a join with a nested loop, hash join or merge join, whichever is fastest.

Why Data Lives in Separate Tables

Each fact is stored once, in the table it belongs to. Navika's city is a fact about Navika, so it's in students; the amount of payment 6 is a fact about that payment, so it's in payments. The payment records only who paid, as student_id 103. Storing her name and city in every payment row instead would repeat them, and the day she moved, some copies would be updated and others missed. Tables, Rows and Columns covered this design; joins are its other half.

SQL▶ Try it
SELECT payment_id, student_id, amount_usd
FROM payments
ORDER BY payment_id;
Output
 payment_id | student_id | amount_usd
------------+------------+------------
          1 |        101 |     450.00
          2 |        101 |     250.00
          3 |        101 |     250.00
          4 |        101 |     550.00
          5 |        101 |     200.00
          6 |        103 |     225.00
          7 |        103 |     225.00
(7 rows)

To show names, each student_id here must be looked up in students.

A Join, Step by Step

SQL
SELECT columns
FROM left_table
JOIN right_table ON left_table.key = right_table.key;

Think of a join as pairing every row on the left with every row on the right, then keeping the pairs where the ON condition is true. Here are the pairs for two payments, built by hand:

SQL▶ Try it
SELECT p.payment_id, p.student_id AS payment_student,
       s.student_id, s.first_name,
       p.student_id = s.student_id AS matches
FROM payments AS p
CROSS JOIN students AS s
WHERE p.payment_id IN (1, 6)
ORDER BY p.payment_id, s.student_id;
Output
 payment_id | payment_student | student_id | first_name | matches
------------+-----------------+------------+------------+---------
          1 |             101 |        101 | Srihitha   | t
          1 |             101 |        102 | Advitha    | f
          1 |             101 |        103 | Navika     | f
          6 |             103 |        101 | Srihitha   | f
          6 |             103 |        102 | Advitha    | f
          6 |             103 |        103 | Navika     | t
(6 rows)

Each payment meets all three students. Payment 1 matches Srihitha only; payment 6 matches Navika only. A join keeps exactly the t rows. (AS p and AS s are table aliases, short names that save typing; p.student_id means "the student_id column of p".) Now the real join, for all seven payments:

SQL▶ Try it
SELECT p.payment_id, s.first_name, p.amount_usd
FROM payments AS p
JOIN students AS s ON s.student_id = p.student_id
ORDER BY p.payment_id;
Output
 payment_id | first_name | amount_usd
------------+------------+------------
          1 | Srihitha   |     450.00
          2 | Srihitha   |     250.00
          3 | Srihitha   |     250.00
          4 | Srihitha   |     550.00
          5 | Srihitha   |     200.00
          6 | Navika     |     225.00
          7 | Navika     |     225.00
(7 rows)
Each payment is compared with each student; only pairs where the student_id values match are kept

The payments that point to Srihitha each found her; Navika's two found her. Advitha has no payments, so no pair with her was ever true, and she doesn't appear. That's an inner join: only matched pairs survive. JOIN on its own means INNER JOIN.

Keeping Rows That Don't Match: LEFT JOIN

A LEFT JOIN keeps every row of the left table, even when nothing on the right matches. Start from students this time:

SQL▶ Try it
SELECT s.first_name, p.payment_id, p.amount_usd
FROM students AS s
LEFT JOIN payments AS p ON p.student_id = s.student_id
ORDER BY s.student_id, p.payment_id;
Output
 first_name | payment_id | amount_usd
------------+------------+------------
 Srihitha   |          1 |     450.00
 Srihitha   |          2 |     250.00
 Srihitha   |          3 |     250.00
 Srihitha   |          4 |     550.00
 Srihitha   |          5 |     200.00
 Advitha    |       NULL |       NULL
 Navika     |          6 |     225.00
 Navika     |          7 |     225.00
(8 rows)

Advitha is back, once, with NULL in every payment column: "this student, no matching payment". The rule for each left row:

Left row (student)Matches on the rightRows in the result
Srihitha5 payments5, one per payment
Advithanone1, with NULL payment columns
Navika2 payments2
INNER JOIN keeps 7 matched pairs; LEFT JOIN also keeps Advitha, with NULLs

The Kinds of Join

JoinKeepsLesson
INNER JOINOnly matched pairsINNER JOIN
LEFT JOINEvery left row, plus matchesLEFT JOIN
RIGHT JOINEvery right row, plus matchesRIGHT JOIN
FULL OUTER JOINEvery row from both sidesFULL OUTER JOIN
CROSS JOINEvery combination, no ONCROSS JOIN
Self joinA table joined to itselfSelf Join

LEFT, RIGHT and FULL joins are outer joins: they keep rows that found no partner. The word OUTER is optional, so LEFT JOIN and LEFT OUTER JOIN are the same.

About Venn diagrams. Joins are often drawn as two overlapping circles. That picture suits UNION and INTERSECT, which compare whole rows, but it misleads for joins: a join doesn't take rows "in both tables"; it pairs rows and can repeat them, as Srihitha's five rows show. Think in pairs, as in the step-by-step table above, and joins never surprise you.

The four joins at a glance: which side's rows each one keeps

Under the Hood: How the Database Runs a Join

The database doesn't really build every pair; it uses one of three methods, and picks the fastest for your data:

MethodHow it worksGood when
Nested loopFor each row on one side, look up matches on the other, often with an indexOne side is small, or the other side has an index on the key
Hash joinBuild a hash table of one side by key, then scan the other side and look each key upLarge tables with no useful index, joined with =
Merge joinSort both sides by the key, then walk through them togetherBoth sides are already sorted, or are large

EXPLAIN shows which one PostgreSQL chose:

SQL▶ Try it
EXPLAIN (COSTS OFF)
SELECT s.first_name, p.amount_usd
FROM students AS s
JOIN payments AS p ON p.student_id = s.student_id;
Output
                 QUERY PLAN
--------------------------------------------
 Hash Join
   Hash Cond: (p.student_id = s.student_id)
   ->  Seq Scan on payments p
   ->  Hash
         ->  Seq Scan on students s
(5 rows)

Read it from the inside out: scan students and build a hash table keyed on student_id, then scan payments and look up each payment's student_id in it. Seven lookups instead of 21 comparisons. On a table with millions of payments, choosing well is the difference between milliseconds and minutes; Reading EXPLAIN covers this properly.

Nested loop, hash join and merge join, with the real plan PostgreSQL chose

Common Mistakes

Forgetting the ON condition's meaning. ON s.student_id = p.student_id matches the key; matching the wrong columns, such as s.student_id = p.payment_id, runs fine and returns nonsense.

Expecting one row per student. A join repeats a row once per match.

Using an inner join when rows may have no match. Advitha silently disappears. Use LEFT JOIN when every left row must appear.

Ambiguous column names. Both tables have student_id, so a bare student_id in SELECT fails with column reference "student_id" is ambiguous. Qualify it: s.student_id.

Interview Corner

What is a join?

A way to combine rows from two tables by matching a column they share, such as student_id. Each row of one table is paired with the rows of the other whose key matches the ON condition.

What's the difference between an INNER JOIN and a LEFT JOIN?

An inner join returns only matched pairs. A left join returns every row of the left table, with NULL in the right table's columns when there's no match.

Why are Venn diagrams a misleading way to explain joins?

A join pairs rows and can repeat them; it doesn't select rows "in both tables". Venn diagrams fit set operations like INTERSECT, not joins.

Name the join algorithms a database uses.

Nested loop, hash join and merge join. The planner picks one based on table sizes, indexes and sort order.

Practice

Challenge: List every course with the students enrolled in it: the course title and the enrolled student_id, sorted by course_id and then student_id. Make sure courses with no students still appear.

Show solution
SQL▶ Try it
SELECT c.title, e.student_id
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.course_id
ORDER BY c.course_id, e.student_id;
Output
       title       | student_id
-------------------+------------
 Java Basics       |        101
 Java Basics       |        102
 Java OOP          |        101
 Java Collections  |        101
 SQL Basics        |        101
 SQL Basics        |        102
 JavaScript Basics |        103
 Git Basics        |       NULL
(8 rows)

Java Basics and SQL Basics appear twice, once per student. Git Basics has no enrollments, so the LEFT JOIN keeps it once, with NULL.

Quick check: How joins work

3 questions
1Srihitha has 5 payments. How many rows does she get in students JOIN payments?
2Advitha has no payments. Where does she appear?
3Which is NOT a join algorithm?

Key Takeaways

You want toWrite
Matched rows onlyFROM payments p JOIN students s ON s.student_id = p.student_id
Every left rowFROM students s LEFT JOIN payments p ON p.student_id = s.student_id
See the join methodEXPLAIN SELECT ...

Was this tutorial helpful?

Lesson 35 of 115