1SELECT name, title2FROM authors3JOIN booksLEFT JOIN books4ON books.author_id5 = authors.idDBMSname titleHerbert DuneGaiman CoralineGaiman StardustSachar HolesClarke NULLid name1 Herbert2 Gaiman3 Sachar4 Clarkeid title author_id1 Dune 12 Coraline 23 Holes 34 Stardust 2
Back: the query, the DBMS and the resultFront: the authors and books tablesEnvelopes: the query, and each matching pair on its way to the resultAt the back: the query, the DBMS and the result card. In front: the authors table and the books table, linked by books.author_id. For each author the DBMS tests every book against ON books.author_id = authors.id and turns each matching pair into one row: 4 of 16 pairs match. A plain JOIN (INNER JOIN) drops Clarke, who has no book; a LEFT JOIN keeps her with a NULL title. Without ORDER BY, SQL does not promise any order for the rows of an answer. The figure shows them author by author; add ORDER BY authors.id, books.id to ask for that.

Data in two tables

  1. A small library keeps two tables: authors and books. Each author is written down once, in authors, even though Gaiman wrote two books. Storing facts once means a fix to a name happens in one place.

How a JOIN matches rows

INNER and LEFT

What happens

;; step 1/9 · tables
table authors
  id  name
  1   Herbert
  2   Gaiman
  3   Sachar
  4   Clarke

table books
  id  title     author_id
  1   Dune      1
  2   Coraline  2
  3   Holes     3
  4   Stardust  2

Gaiman wrote Coraline and Stardust, yet appears once

Without ORDER BY, SQL does not promise any order for the rows of an answer. The figure shows them author by author; add ORDER BY authors.id, books.id to ask for that. The DBMS does not really test every pair one by one: its planner picks a faster method, such as a hash join or an index. The answer is always the same as testing every pair.