Skip to main content

SQL joins explained for students

7 min readUpdated

A join combines rows from two tables using a column they share. Joins appear in database exams, coursework and interviews, and they are easy once you picture which rows each one keeps.

Two small tables

students
student_idname
1Asha
2Ben
3Chen
enrolments
student_idcourse
1Maths
1Physics
2History
4Art

INNER JOIN: only matches

sql
SELECT s.name, e.course
FROM students s
INNER JOIN enrolments e ON s.student_id = e.student_id;

Returns Asha–Maths, Asha–Physics and Ben–History. Chen has no enrolment and enrolment 4 has no student, so both are left out.

LEFT JOIN: every row from the left

sql
SELECT s.name, e.course
FROM students s
LEFT JOIN enrolments e ON s.student_id = e.student_id;

Same three rows plus Chen with NULL for course. Use it to find missing data: add WHERE e.student_id IS NULL to list students with no enrolment.

RIGHT and FULL OUTER JOIN

A RIGHT JOIN keeps every row from the right table, so the Art enrolment appears with a NULL name. A FULL OUTER JOIN keeps unmatched rows from both sides. Some databases, such as MySQL, do not support FULL OUTER JOIN directly; you combine a LEFT and a RIGHT join with UNION.

JoinKeeps
INNEROnly rows that match on both sides
LEFTAll left rows, plus matches
RIGHTAll right rows, plus matches
FULL OUTERAll rows from both sides

Self join

A table can join to itself, for example to pair each employee with their manager stored in the same table.

sql
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

Common mistakes

  • Leaving out the join condition, which pairs every row with every row.
  • Putting a filter on the right table in WHERE after a LEFT JOIN, which silently turns it into an inner join; put it in ON instead.
  • Ambiguous column names: prefix them with the table alias.
  • Counting with COUNT(*) after a LEFT JOIN, which counts the unmatched rows too; use COUNT(e.course).

Frequently asked questions

Is JOIN the same as INNER JOIN?

Yes. Writing just JOIN means an inner join.

Which join should I use?

Use INNER when you only want matching rows and LEFT when you must keep every row from the main table.

Why do I get duplicate rows?

One row on the left matches several rows on the right, so it appears once per match. That is correct behaviour; group or use DISTINCT if you need one row.

Practise this, step by step

Short lessons with quizzes, practice and interview questions, from your first program to job-ready.

SQL and Databases course: syllabus and 1:1 mentoringSQL from first query to joins, window functions, design and indexes.