Thuta Learning
SQL
ProjectsData & DatabasesBeginner

Bookstore Project - Part 2: Search & Join Queries

SQLLesson 3240 min

What you'll walk away with

  • Combine INNER JOIN with ILIKE for a search box
  • Join three tables and explain what one result row represents
  • Find "what is missing" with LEFT JOIN ... WHERE ... IS NULL
  • Decide whether a LEFT JOIN condition belongs in ON or in WHERE

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.

unsold-books.sql
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 you

Why 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.

QuestionJoinWhy
Book with author nameINNEREvery book has an author
Order historyINNER (x2)Every order has a customer and a book
Never-ordered booksLEFT + IS NULLRows without orders must survive
Mental model: pick the grain, then attach
  1. Decide what one row means
  2. Start FROM that table
  3. Join along the foreign keys
  4. Need unmatched rows? Use LEFT
  5. 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

sql
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.

bookstore-queries.sql
-- 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

  1. Case-insensitive searchWHERE 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.

  2. First join of the historyINNER JOIN Customers AS c ON o.CustomerID = c.CustomerID

    Attaches 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.

  3. Newest firstORDER BY o.OrderDate DESC;

    DESC puts the newest date on top. Without it the default is ASC and the oldest order comes first.

  4. Keep books without ordersLEFT JOIN Orders AS o ON b.BookID = o.BookID

    Fantastic Beasts has no orders, so instead of being dropped it is kept with NULL in every o.* column.

  5. Anti-join filterWHERE o.OrderID IS NULL;

    Keeps only the rows that had no match. It must be IS NULL; = NULL is never true.

You should see
-- 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.

on-vs-where.sql
-- 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
yangon-history.sql
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
yangon-history.sql
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

On the Part 1 data, how many rows does SELECT Title FROM Books WHERE Title LIKE '%harry%'; return in PostgreSQL?

Quick quiz 2 / 3

In the order history query (Orders + Customers + Books), how many rows show Su Su?

Quick quiz 3 / 3

Which query correctly finds books that have no orders?

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Bookstore Project - Part 2: Search & Join Queries | Thuta Learning