Explain it simply
Explain it simply
Part 1 built four tidy record books. But the order book only holds numbers like "customer 1, book 102", which mean nothing to a person reading them. A join lays two books side by side and reads the lines with matching numbers together.
In Part 2 you answer four questions the shop's website needs: who wrote the book called Harry, what is out of stock, who bought what, and which book has nobody bought yet.
Problem → Why → Solution
The problem: the book that vanished
The owner says: "I want to discount the books nobody has bought." Out of habit the developer reaches for INNER JOIN and writes the query below. The result has zero rows. There is no error, so the report says "every book sold at least once".
In fact Fantastic Beasts has never been sold. INNER JOIN drops books without orders during the join itself, so WHERE o.OrderID IS NULL has no rows left to test.
SELECT b.Title
FROM Books AS b
INNER JOIN Orders AS o ON b.BookID = o.BookID -- keeps only books WITH orders
WHERE o.OrderID IS NULL; -- so nothing can be NULL here
-- (0 rows), and no error to warn youWhy there is no error
The query is valid and PostgreSQL does exactly what it says: INNER JOIN means "keep only rows that match on both sides". To look for something missing you need LEFT JOIN, which keeps unmatched rows and fills the other side with NULL. Picking the wrong join type is a logic bug, so only checking the result catches it.
Core concept: the join type decides which rows survive
Ask two questions every time you write a join. First: what does one result row represent (the grain)? In the order history one row is one order, so the query starts FROM Orders and attaches customer and book details beside it. Second: should rows without a match be kept or dropped? That is the choice between INNER and LEFT.
1. INNER JOIN keeps matches only
In Books INNER JOIN Authors, a book with no author would disappear. Part 1 made AuthorID NOT NULL with a foreign key, so every book is guaranteed an author and INNER JOIN hides nothing. Constraints make join behaviour predictable too.
2. LEFT JOIN keeps every left row
In Books LEFT JOIN Orders, books without orders survive with NULL in every Orders column, such as o.OrderID and o.Quantity. WHERE o.OrderID IS NULL keeps only those rows; this is called an anti-join. Test OrderID because it is a primary key and can never be NULL on a real order.
3. Each extra join links one more table
The order history joins Orders to Customers once and to Books once, and each ON condition follows one foreign key. Because each order matches exactly one customer and one book, the row count stays at four.
4. ILIKE for a search box
PostgreSQL's LIKE is case-sensitive: LIKE '%harry%' does not find 'Harry Potter'. Users type in lowercase, so the search uses ILIKE. ILIKE is PostgreSQL-only; elsewhere write LOWER(Title) LIKE '%harry%'. MySQL's default collations usually compare LIKE case-insensitively already.
| Question | Join | Why |
|---|---|---|
| Book with author name | INNER | Every book has an author |
| Order history | INNER (x2) | Every order has a customer and a book |
| Never-ordered books | LEFT + IS NULL | Rows without orders must survive |
- Decide what one row means
- Start FROM that table
- Join along the foreign keys
- Need unmatched rows? Use LEFT
- Check the row count
If the row count grows or shrinks unexpectedly after a join, recheck the join type or the ON condition.
General pattern
SELECT x.col, y.col, z.col
FROM main_table AS x
INNER JOIN table_y AS y ON x.y_id = y.id
INNER JOIN table_z AS z ON x.z_id = z.id
WHERE x.text_col ILIKE '%term%'
ORDER BY x.sort_col DESC;
-- rows in a with no match in b (anti-join)
SELECT a.col FROM a
LEFT JOIN b ON b.a_id = a.id
WHERE b.id IS NULL;Aliases (AS x) keep the query short and show which table every column comes from. In an anti-join, the column tested with IS NULL should be the right-hand table's primary key.
Four Bookstore queries
All four queries run on exactly the Part 1 data. Instead of spelling out names like Books.Title, the queries use the aliases b, a, c and o to keep things short. The search uses ILIKE '%harry%' rather than LIKE '%Harry%', so it matches whatever case the user types. Notice that the output headers read authorname and customername, because PostgreSQL lowercases unquoted names.
-- 1. Search box: title contains "harry" (any case), with the author
SELECT b.Title, a.AuthorName, b.Price
FROM Books AS b
INNER JOIN Authors AS a ON b.AuthorID = a.AuthorID
WHERE b.Title ILIKE '%harry%'
ORDER BY b.Price ASC;
-- 2. Out-of-stock list
SELECT Title, Stock FROM Books WHERE Stock = 0;
-- 3. Order history, newest first
SELECT c.CustomerName, b.Title, o.Quantity, o.OrderDate
FROM Orders AS o
INNER JOIN Customers AS c ON o.CustomerID = c.CustomerID
INNER JOIN Books AS b ON o.BookID = b.BookID
ORDER BY o.OrderDate DESC;
-- 4. Books that were never ordered
SELECT b.Title
FROM Books AS b
LEFT JOIN Orders AS o ON b.BookID = o.BookID
WHERE o.OrderID IS NULL;Code breakdown
- Case-insensitive search
WHERE b.Title ILIKE '%harry%'% stands for any number of characters, including none, so harry can appear anywhere in the title, and ILIKE makes 'Harry' and 'HARRY' match too.
- First join of the history
INNER JOIN Customers AS c ON o.CustomerID = c.CustomerIDAttaches the customer's name to each order while the grain stays one row per order. Su Su has two orders, so she appears on two rows.
- Newest first
ORDER BY o.OrderDate DESC;DESC puts the newest date on top. Without it the default is ASC and the oldest order comes first.
- Keep books without orders
LEFT JOIN Orders AS o ON b.BookID = o.BookIDFantastic Beasts has no orders, so instead of being dropped it is kept with NULL in every o.* column.
- Anti-join filter
WHERE o.OrderID IS NULL;Keeps only the rows that had no match. It must be IS NULL; = NULL is never true.
-- 1. search
title | authorname | price
--------------+-------------+----------
Harry Potter | J.K Rowling | 15000.00
(1 row)
-- 2. out of stock
title | stock
------------------+-------
Fantastic Beasts | 0
(1 row)
-- 3. order history
customername | title | quantity | orderdate
--------------+--------------------+----------+------------
Su Su | Kafka on the Shore | 1 | 2026-02-01
Hla Hla | Norwegian Wood | 3 | 2026-01-12
Ko Ko | Myanmar Sarpay | 1 | 2026-01-10
Su Su | Harry Potter | 2 | 2026-01-05
(4 rows)
-- 4. never ordered
title
------------------
Fantastic Beasts
(1 row)LEFT JOIN: condition in ON or in WHERE?
Consider the report "show every book, plus its order if the order is on or after 2026-01-10". Put the date condition in ON and it filters the right-hand table before joining, so all five books remain. Put it in WHERE and it filters after the join: rows with a NULL date disappear and the LEFT JOIN behaves like an INNER JOIN.
-- Condition in ON: every book stays (5 rows)
SELECT b.Title, o.OrderID
FROM Books AS b
LEFT JOIN Orders AS o
ON b.BookID = o.BookID AND o.OrderDate >= '2026-01-10'
ORDER BY b.BookID;
-- Harry Potter and Fantastic Beasts show an empty OrderID
-- Condition in WHERE: unmatched books are filtered out (3 rows)
SELECT b.Title, o.OrderID
FROM Books AS b
LEFT JOIN Orders AS o ON b.BookID = o.BookID
WHERE o.OrderDate >= '2026-01-10'
ORDER BY b.BookID;Another way: NOT EXISTS
SELECT Title FROM Books b WHERE NOT EXISTS (SELECT 1 FROM Orders o WHERE o.BookID = b.BookID); gives the same answer, and PostgreSQL usually turns both forms into an anti-join plan. Avoid NOT IN (SELECT BookID FROM Orders): a single NULL in the subquery makes it return no rows at all.
In real projects
In real projects
An e-commerce site's "My orders" page, an admin dashboard's "out of stock" widget, and marketing's list of "customers who bought once and never came back in six months" all use the patterns in this lesson. Anti-joins also find users who never got an onboarding email and orders that have no invoice yet.
In application code these queries are never built by string concatenation. The user's search term is sent as a parameter ($1) and the query says ILIKE '%' || $1 || '%'. As tables grow, a search with a leading % cannot use a plain B-tree index, so PostgreSQL projects usually add the pg_trgm extension with a GIN index.
Common mistakes
Common mistakes
Using INNER JOIN where LEFT JOIN is needed
As the problem section showed, books without orders vanish from the result and nothing warns you. Whenever the question says "missing" or "not yet", reach for LEFT JOIN.
Leaving join columns unqualified
Both Orders and Books have BookID, so SELECT BookID ... fails with column reference "bookid" is ambiguous. In join queries prefix every column with its alias, like b.BookID.
Filtering right-side columns in WHERE after a LEFT JOIN
A condition like WHERE o.OrderDate >= ... removes the NULL rows and throws away what the LEFT JOIN was for. Filter the right-hand table inside ON instead.
Assuming LIKE ignores case
Common for people coming from MySQL: in PostgreSQL LIKE '%harry%' returns zero rows. Use ILIKE or LOWER().
Mini challenge
Order history for Yangon customers
Write a query that shows only the orders of customers who live in Yangon, including each line's amount (Quantity × Price).
- Start FROM Orders and join Customers and Books
- Show CustomerName, Title, Quantity, LineTotal and OrderDate
- Keep only customers whose City is 'Yangon'
- Put the newest order first
SELECT c.CustomerName, b.Title, o.Quantity,
-- TODO: LineTotal = quantity times the book's price
o.OrderDate
FROM Orders AS o
-- TODO: join Customers (alias c) on the customer foreign key
-- TODO: join Books (alias b) on the book foreign key
-- TODO: keep only Yangon customers
-- TODO: newest order first
;Expected: Three rows: Su Su - Kafka on the Shore - 1 - 13000.00 - 2026-02-01; Hla Hla - Norwegian Wood - 3 - 36000.00 - 2026-01-12; Su Su - Harry Potter - 2 - 30000.00 - 2026-01-05. Ko Ko from Mandalay is not included.
Show hint
City lives in Customers, so write WHERE c.City = 'Yangon'. Strings take single quotes; with double quotes PostgreSQL would look for a column with that name.
Show solution
SELECT c.CustomerName, b.Title, o.Quantity,
o.Quantity * b.Price AS LineTotal,
o.OrderDate
FROM Orders AS o
INNER JOIN Customers AS c ON o.CustomerID = c.CustomerID
INNER JOIN Books AS b ON o.BookID = b.BookID
WHERE c.City = 'Yangon'
ORDER BY o.OrderDate DESC;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Before writing a join, decide what one result row represents
- INNER JOIN keeps matches only; LEFT JOIN keeps every left row
- Find missing things with LEFT JOIN + WHERE right_pk IS NULL, or NOT EXISTS
- In a LEFT JOIN, filter the right-hand table inside ON
- PostgreSQL's LIKE is case-sensitive, so a search box uses ILIKE
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group