Worksheet: Planning Your First JOIN on Paper
JOINs are easier to write once you have answered a few questions on paper. Print this worksheet or copy it into a notes file, fill in each box, and only then open your database tool.
Box 1: the question in plain words
Write the question your query should answer, as if asking a person.
| Field | Your answer |
|---|---|
| My question | |
| Example | "Show each book with the name of its author." |
Box 2: the tables involved
| Field | Your answer |
|---|---|
| First table (where most of the rows come from) | |
| Second table (where extra details come from) | |
| Are there more tables? List them |
Tip: the first table is usually the "many" side, such as books, and the second the "one" side, such as authors.
Box 3: the linking columns
| Field | Your answer |
|---|---|
| Column in the first table | |
| Column in the second table it matches | |
| Is this a primary key / foreign key pair? |
In the example: books.author_id matches authors.id.
Box 4: which join type?
Tick one.
- [ ] INNER JOIN: only rows that have a match on both sides.
- [ ] LEFT JOIN: all rows from the first table, matched or not.
Ask yourself: "If a book has no author recorded, should it still appear?" Yes means LEFT JOIN.
Box 5: the columns to show
| Column | From which table? |
|---|
Write them as table.column to avoid confusion when both tables have a column with the same name, such as id or name.
Box 6: predict the result
| Field | Your answer |
|---|---|
| How many rows do I expect? | |
| Which rows might be missing or show NULLs? |
The JOIN row counting notes help with this box.
Box 7: write the query
SELECT ______, ______
FROM ______
______ JOIN ______ ON ______ = ______;
Box 8: check
| Check | Done? |
|---|---|
| The row count matches my prediction | |
| No unexpected duplicates | |
| NULLs only where I expected them |
Instructions for using the worksheet
- Fill in the boxes in order. Skipping straight to Box 7 is the most common cause of confusing results.
- If Box 6 and Box 8 disagree, return to Box 3: the linking columns are usually the culprit.
- Keep your filled-in worksheets. After five or six, you will find you can do the whole thing in your head.
Example, filled in briefly
Question: books with author names. Tables: books, authors. Link: books.author_id = authors.id. Join: LEFT, so books with no author still show. Columns: books.title, authors.name. Prediction: one row per book.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.