Thuta Learning
SQL
ProjectsData & DatabasesBeginner

Bookstore Project - Part 3: Reports & Cleanup

SQLLesson 3340 min

What you'll walk away with

  • Group joined data with GROUP BY and report COUNT and SUM
  • Tell WHERE from HAVING and filter groups with HAVING
  • Preview with SELECT before UPDATE or DELETE, and target rows by primary key
  • Choose indexes that help the Bookstore queries and know what they cannot help

Explain it simply

Explain it simply

Part 2 produced detailed lists with one line per order. The owner does not want to read four hundred lines; they want summaries such as "how much has each customer spent in total?" and "which author has the most books?".

GROUP BY is like sorting rows into drawers: one drawer per customer, then SUM adds up the money inside each drawer. Besides the reports, Part 3 also does maintenance work: fixing stock and clearing out old data.

Problem → Why → Solution

The problem: one UPDATE without a WHERE

Fifteen copies of Fantastic Beasts arrive, and a developer types the fix in a hurry, running it without selecting the second line that holds the WHERE. PostgreSQL answers UPDATE 5: all five books now have a stock of 15, and the correct record that Myanmar Sarpay had 20 copies is gone.

DELETE is the same. One DELETE FROM Orders; wipes the entire sales history and every Part 3 report drops to zero. In autocommit mode each statement is permanent the moment it finishes; there is no undo button.

restock-oops.sql
UPDATE Books SET Stock = 15
-- WHERE Title = 'Fantastic Beasts';   <- this line was never run
;
-- UPDATE 5   (every book now has Stock = 15)

DELETE FROM Orders;   -- meant: WHERE OrderDate < '2026-01-01'
-- DELETE 4   (all sales history is gone)

Why this is so dangerous

In SQL an UPDATE or DELETE without WHERE means "every row", and because the syntax is valid PostgreSQL gives no warning. The protection is a habit: test the condition with SELECT first, target rows by primary key, and run inside a transaction where you check the affected row count.

Core concept: group, filter, change safely

PostgreSQL works through a report query in stages. FROM and JOIN assemble the rows, WHERE filters individual rows, GROUP BY splits them into groups, COUNT and SUM compute one value per group, and HAVING filters the groups. Only then does SELECT pick the output columns and ORDER BY sort them. Knowing this order tells you immediately where a condition belongs.

text
Report query pipeline
---------------------
FROM + JOIN  ->  WHERE   ->  GROUP BY  ->  HAVING    ->  SELECT  ->  ORDER BY
(all rows)      (rows)      (drawers)     (drawers)     (columns)   (sort)
                Stock > 0   AuthorID      COUNT >= 2    SUM(...)    DESC

1. Group by the ID

Two customers can share a name. GROUP BY c.CustomerName alone would merge two different Su Sus into one total. GROUP BY c.CustomerID, c.CustomerName groups by identity and still lets you show the name.

2. WHERE filters rows, HAVING filters groups

"Authors with two or more books" depends on a group's COUNT, so it must be HAVING COUNT(b.BookID) >= 2; WHERE COUNT(...) fails with aggregate functions are not allowed in WHERE. "Only count books in stock" is a row condition, so it goes in WHERE.

3. Rehearse every change with SELECT

Before an UPDATE or DELETE, run a SELECT with the same WHERE and look at the rows it touches. Titles are not guaranteed unique, so targeting BookID = 105 by primary key is safer. Afterwards compare the count PostgreSQL reports, such as UPDATE 1, with your preview.

4. Index for the queries you actually run

PostgreSQL does not index foreign key columns automatically, so an index on Orders(CustomerID) helps every "orders for this customer" query. A B-tree index on Books(Title) helps Title = '...' and ORDER BY Title, but it cannot help a search with a leading %, such as Part 2's ILIKE '%harry%'.

Mental model: drawers, totals, then pick
  1. Gather rows with joins
  2. Filter rows with WHERE
  3. Sort rows into drawers by ID
  4. Total each drawer, pick with HAVING

For changes: look with SELECT, target by primary key, then change.

General pattern

sql
SELECT g.name, COUNT(c.id) AS how_many, SUM(c.amount) AS total
FROM group_table AS g
INNER JOIN child_table AS c ON c.group_id = g.id
WHERE row_condition
GROUP BY g.id, g.name
HAVING group_condition
ORDER BY total DESC;

SELECT * FROM table_name WHERE id = 42;          -- preview
UPDATE table_name SET col = new_value WHERE id = 42;

Every non-aggregate column in SELECT must appear in GROUP BY (or depend on a grouped primary key). Pair every change with a preview SELECT that uses the same condition.

Two reports, two fixes, two indexes

This runs on the Part 1 data. Read the HAVING COUNT >= 2 result carefully: it returns both Murakami (103, 104) and Rowling (102, 105), because each has exactly two books and >= includes 2; nobody has more than two. Every order is from 2026, so the DELETE removes 0 rows, which is a safe way to rehearse the condition. In the spending report, Su Su = 2 × 15000 + 1 × 13000 = 43000.

bookstore-reports.sql
-- 1. Authors with 2 or more books
SELECT a.AuthorName, COUNT(b.BookID) AS BookCount
FROM Authors AS a
INNER JOIN Books AS b ON a.AuthorID = b.AuthorID
GROUP BY a.AuthorID, a.AuthorName
HAVING COUNT(b.BookID) >= 2
ORDER BY a.AuthorName;

-- 2. Total spending per customer
SELECT c.CustomerName, SUM(o.Quantity * b.Price) AS TotalSpent
FROM Orders AS o
INNER JOIN Customers AS c ON o.CustomerID = c.CustomerID
INNER JOIN Books AS b ON o.BookID = b.BookID
GROUP BY c.CustomerID, c.CustomerName
ORDER BY TotalSpent DESC;

-- 3. Restock: preview the row, then change it by primary key
SELECT BookID, Title, Stock FROM Books WHERE BookID = 105;
UPDATE Books SET Stock = 15 WHERE BookID = 105;

-- 4. Clean up orders placed before 2026 (0 rows match in this sample)
DELETE FROM Orders WHERE OrderDate < '2026-01-01';

-- 5. Indexes for common lookups
CREATE INDEX idx_orders_customer ON Orders (CustomerID);
CREATE INDEX idx_books_title ON Books (Title);

-- 6. Confirm the stock change
SELECT Title, Stock FROM Books ORDER BY BookID;

Code breakdown

  1. Group by identityGROUP BY a.AuthorID, a.AuthorName

    Grouping by AuthorID keeps two authors with the same name apart; including AuthorName lets SELECT show the name.

  2. Filter the groupsHAVING COUNT(b.BookID) >= 2

    Each group is counted first and then tested; Aung Aung, with one book, is dropped here.

  3. Money per order lineSUM(o.Quantity * b.Price) AS TotalSpent

    Quantity × Price is computed per order line and then summed per customer. Price is DECIMAL, so the result keeps two decimal places.

  4. Change by primary keyUPDATE Books SET Stock = 15 WHERE BookID = 105;

    The preview showed exactly one row and the primary key guarantees UPDATE 1. Matching by Title instead would be risky: if two books ever shared a title, both would change.

  5. Index a foreign keyCREATE INDEX idx_orders_customer ON Orders (CustomerID);

    Speeds up "orders for this customer" lookups and the Customers–Orders join once the table grows; with four sample rows you will not see a difference yet.

You should see
-- 1. authors with 2+ books
   authorname    | bookcount
-----------------+-----------
 Haruki Murakami |         2
 J.K Rowling     |         2
(2 rows)

-- 2. spending per customer
 customername | totalspent
--------------+------------
 Su Su        |   43000.00
 Hla Hla      |   36000.00
 Ko Ko        |    5000.00
(3 rows)

-- 3. preview, then UPDATE 1
 bookid |      title       | stock
--------+------------------+-------
    105 | Fantastic Beasts |     0
(1 row)

-- 4. DELETE 0
-- 5. CREATE INDEX, CREATE INDEX

-- 6. stock after the update
       title        | stock
--------------------+-------
 Myanmar Sarpay     |    20
 Harry Potter       |    10
 Norwegian Wood     |     8
 Kafka on the Shore |     5
 Fantastic Beasts   |    15
(5 rows)

Run changes inside a transaction

Even with a preview SELECT, the safer production habit is to run the change inside a transaction started with BEGIN. If the row count PostgreSQL reports matches what you expected, COMMIT; if not, ROLLBACK, and every change in the transaction disappears as if BEGIN had never happened. psql also has helpers such as \set ON_ERROR_ROLLBACK.

safe-update.sql
BEGIN;
UPDATE Books SET Price = Price * 1.10 WHERE AuthorID = 3;
-- PostgreSQL reports UPDATE 2: matches the 2 Murakami books we expected
SELECT Title, Price FROM Books WHERE AuthorID = 3 ORDER BY BookID;
--  Norwegian Wood     | 13200.00
--  Kafka on the Shore | 14300.00
ROLLBACK;   -- changed our mind: prices are back to 12000.00 and 13000.00
SELECT Title, Price FROM Books WHERE AuthorID = 3 ORDER BY BookID;

In PostgreSQL even DDL statements such as CREATE TABLE, ALTER TABLE and a plain CREATE INDEX can run inside a transaction and be rolled back. That is not true everywhere: MySQL and Oracle commit implicitly on DDL. Do not leave a transaction open for long, though, because the rows you changed stay locked and other sessions have to wait.

In real projects

In real projects

"Total spent per customer" is the basis of a customer lifetime value (CLV) report, which marketing uses to find VIP customers. Reports like monthly revenue and revenue per author run every day on dashboards, and once tables grow they are often precomputed as a materialized view or a summary table rebuilt every night.

Teams that change production data review ad-hoc UPDATE statements like code, confirm a backup exists first, and often run them with a second person watching. Cleanup jobs like this lesson's DELETE are split into small batches, for example 10,000 rows at a time, so the table is never locked for long. Each batch is its own short transaction, and the job logs how many rows it removed so the numbers can be checked later.

Common mistakes

Common mistakes

Forgetting WHERE on DELETE or UPDATE

DELETE FROM Orders; removes every order and, in autocommit mode, cannot be undone. Write the WHERE first, rehearse it with SELECT, run inside a transaction and check the row count.

Putting an aggregate condition in WHERE

WHERE COUNT(b.BookID) >= 2 fails with aggregate functions are not allowed in WHERE. WHERE tests single rows before any group exists, so COUNT is not known yet. Use HAVING.

Counting after a join that multiplies rows

Join Authors, Books and Orders and then COUNT(b.BookID), and every book with two orders is counted twice. The sample data hides this because no book has more than one order, but real data exposes it at once. Use COUNT(DISTINCT b.BookID) or aggregate in a subquery before joining.

Expecting a B-tree index to speed up '%term%'

An index on Books(Title) does not help '%harry%'. The index is ordered from the first character, so a match in the middle of the title has no known position. Use a pg_trgm GIN index or full-text search.

Mini challenge

Author price report and monthly revenue

The owner wants two more reports: each author's book count and average price, and the number of orders and revenue per month.

  • Author report: AuthorName, BookCount and AvgPrice (rounded to 2 places with ROUND), highest AvgPrice first
  • Group authors by AuthorID
  • Monthly report: the month via to_char(OrderDate, 'YYYY-MM'), the order count and SUM(Quantity × Price)
  • Sort the monthly report by month
owner-reports.sql
-- Report A: books and average price per author
SELECT a.AuthorName,
       -- TODO: number of books AS BookCount
       -- TODO: average price rounded to 2 places AS AvgPrice
FROM Authors AS a
INNER JOIN Books AS b ON b.AuthorID = a.AuthorID
-- TODO: group by the author's id and name
-- TODO: highest average first
;

-- Report B: orders and revenue per month
SELECT -- TODO: month as 'YYYY-MM', order count, revenue
FROM Orders AS o
INNER JOIN Books AS b ON b.BookID = o.BookID
-- TODO: group by the month, sort by the month
;

Expected: Report A: J.K Rowling 2 14500.00, Haruki Murakami 2 12500.00, Aung Aung 1 5000.00. Report B: 2026-01 has 3 orders and 71000.00; 2026-02 has 1 order and 13000.00.

Show hint

You can wrap an aggregate in a function, as in ROUND(AVG(b.Price), 2). PostgreSQL lets GROUP BY use an output alias (GROUP BY month) or a position (GROUP BY 1).

Show solution
owner-reports.sql
-- Report A: books and average price per author
SELECT a.AuthorName,
       COUNT(b.BookID) AS BookCount,
       ROUND(AVG(b.Price), 2) AS AvgPrice
FROM Authors AS a
INNER JOIN Books AS b ON b.AuthorID = a.AuthorID
GROUP BY a.AuthorID, a.AuthorName
ORDER BY AvgPrice DESC;

-- Report B: orders and revenue per month
SELECT to_char(o.OrderDate, 'YYYY-MM') AS month,
       COUNT(*) AS orders,
       SUM(o.Quantity * b.Price) AS revenue
FROM Orders AS o
INNER JOIN Books AS b ON b.BookID = o.BookID
GROUP BY month
ORDER BY month;

Quick quiz 1 / 3

On the Part 1 data, which authors does the report with HAVING COUNT(b.BookID) >= 2 return?

Quick quiz 2 / 3

You want authors with two or more books, counting only books in stock. Where do the two conditions go?

Quick quiz 3 / 3

There is a plain B-tree index on Books(Title). Which query cannot benefit from it?

What to remember

  • WHERE filters rows; HAVING filters groups
  • Group by ID, not by name, and add the name to GROUP BY to display it
  • Rehearse every UPDATE or DELETE with SELECT, target by primary key, run in a transaction
  • Joins can multiply rows, so consider COUNT(DISTINCT ...) when counting
  • Index foreign key columns; a B-tree is not enough for '%term%' searches

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 3: Reports & Cleanup | Thuta Learning