Thuta Learning
SQL
ExercisesData & DatabasesBeginner

Practice Set 2: Joins & Aggregates

SQLLesson 3535 min

What you'll walk away with

  • Explain the grain of a report that joins and then groups
  • Make a top-N query stable by adding a tiebreaker
  • Use the difference between COUNT(*) and COUNT(column) after a LEFT JOIN
  • Show 0 instead of NULL for empty groups with COALESCE

Explain it simply

Explain it simply

Practice Set 1 picked rows from a single table. Practice Set 2 is one step up: link two or three tables, put the rows into groups, and summarise each group with a number.

It is like the shop's bookkeeper at work: sort every sales slip into piles by book, add up the copies in each pile, and pick the three biggest piles. A customer with no slips at all must still be written down as "zero" instead of being forgotten.

Problem → Why → Solution

The problem: the customer with no orders cannot be found

Marketing wants to send a welcome coupon to customers who have never bought anything. Mya Mya from Bago has an account but no orders yet. The developer uses LEFT JOIN correctly, but counts with COUNT(*), and the result has zero rows.

For Mya Mya, LEFT JOIN produces one row whose Orders columns are all NULL. COUNT(*) counts rows, so it counts that row as 1. Her OrderCount is 1, HAVING COUNT(*) = 0 does not match, and not a single coupon goes out.

never-ordered.sql
SELECT c.CustomerName, COUNT(*) AS OrderCount
FROM Customers AS c
LEFT JOIN Orders AS o ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName
HAVING COUNT(*) = 0;
-- (0 rows): Mya Mya's NULL-filled row was counted as 1

COUNT(*) versus COUNT(column)

COUNT(*) counts how many rows the group has, while COUNT(o.OrderID) counts only rows where o.OrderID is not NULL. LEFT JOIN fills unmatched rows with NULL, so to count how many matches there are, count the right-hand table's primary key.

Core concept: join, group, then rank

Every task in this set is solved in three stages. First, join to bring the needed data into one row. Second, GROUP BY and compute aggregates. Third, sort with ORDER BY and, if needed, cut with LIMIT. Running the query at each stage is the easiest way to debug: look at the join result before adding GROUP BY and check that the row count is what you expect.

1. GROUP BY sets the grain

Task 1 groups by a.AuthorID, so one result row is one author; Task 2 groups by b.BookID, so one row is one book. AuthorName or Title is added to GROUP BY only so it can be displayed. Grouping by ID keeps two items with the same name apart.

2. ORDER BY first, then LIMIT

LIMIT 3 takes the first three rows of the already sorted result. LIMIT is written after ORDER BY; reversed, PostgreSQL reports syntax error at or near "ORDER". SQL Server uses TOP 3, while Oracle and standard SQL use FETCH FIRST 3 ROWS ONLY, which PostgreSQL also accepts.

3. Handle ties in a top-N list

In Task 2, Myanmar Sarpay and Kafka on the Shore each sold one copy, so they tie for third place. With ORDER BY TotalSold DESC alone PostgreSQL does not promise which one appears. Adding b.Title as a second sort key means Kafka on the Shore (K before M) is always the one shown.

4. After a LEFT JOIN, count a column

In Task 3 COUNT(o.OrderID) returns 0 for Mya Mya, which matches HAVING COUNT(o.OrderID) = 0. SUM, however, returns NULL rather than 0 when nothing matched, so wrap it as COALESCE(SUM(...), 0).

On Mya Mya's groupResult
COUNT(*)1 (counts the NULL-filled row)
COUNT(o.OrderID)0
SUM(o.Quantity)NULL
COALESCE(SUM(o.Quantity), 0)0
Mental model: sort slips into piles, then count
  1. Gather slip rows with joins
  2. Pile them by ID (GROUP BY)
  3. Count or sum each pile
  4. Keep piles with HAVING
  5. Sort, then cut with LIMIT

Run the join once before adding GROUP BY; most mistakes show up right there.

General pattern

sql
SELECT p.label, COUNT(c.id) AS n, COALESCE(SUM(c.amount), 0) AS total
FROM parent AS p
LEFT JOIN child AS c ON c.parent_id = p.id
GROUP BY p.id, p.label
HAVING COUNT(c.id) >= min_count
ORDER BY total DESC, p.label
LIMIT n_rows;

To keep every parent, including those without children, use LEFT JOIN, count the child's ID, and wrap SUM in COALESCE. Always end ORDER BY with a unique tiebreaker before applying LIMIT.

Sample answers to the three tasks

The tasks: (1) how many books each author has written, (2) the three books with the most copies sold, (3) customers who have never placed an order. In the Part 1 data all three customers have orders, so the original Task 3 returned zero rows and could not show whether it was right. That is why the script starts by adding Mya Mya from Bago. The original queries were also changed to group by ID instead of name and to add ORDER BY tiebreakers.

practice-set-2.sql
-- Setup for Task 3: a customer who has not ordered yet
INSERT INTO Customers VALUES (4, 'Mya Mya', 'myamya@mail.com', 'Bago');

-- Task 1: number of books per author
SELECT a.AuthorName, COUNT(b.BookID) AS TotalBooks
FROM Authors AS a
INNER JOIN Books AS b ON b.AuthorID = a.AuthorID
GROUP BY a.AuthorID, a.AuthorName
ORDER BY TotalBooks DESC, a.AuthorName;

-- Task 2: top 3 books by copies sold
SELECT b.Title, SUM(o.Quantity) AS TotalSold
FROM Orders AS o
INNER JOIN Books AS b ON o.BookID = b.BookID
GROUP BY b.BookID, b.Title
ORDER BY TotalSold DESC, b.Title
LIMIT 3;

-- Task 3: customers with zero orders
SELECT c.CustomerName, COUNT(o.OrderID) AS OrderCount
FROM Customers AS c
LEFT JOIN Orders AS o ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName
HAVING COUNT(o.OrderID) = 0;

Code breakdown

  1. Make Task 3 testableINSERT INTO Customers VALUES (4, 'Mya Mya', 'myamya@mail.com', 'Bago');

    Without a customer who has no orders, a query that looks for such customers cannot be tested. Test data must contain both a "yes" case and a "no" case.

  2. Tie on book countORDER BY TotalBooks DESC, a.AuthorName;

    Murakami and Rowling both have two books, so the name decides the order and Haruki Murakami comes first.

  3. Group per bookGROUP BY b.BookID, b.Title

    Order lines are piled by book and SUM(o.Quantity) adds up the copies. Norwegian Wood sold 3 copies in one order, so it is first.

  4. Stable top 3ORDER BY TotalSold DESC, b.Title

    Kafka on the Shore and Myanmar Sarpay tie at one copy for third place; the title breaks the tie, so LIMIT 3 keeps Kafka on the Shore on every run.

  5. Count matches, not rowsHAVING COUNT(o.OrderID) = 0;

    COUNT(o.OrderID) skips NULLs, so Mya Mya gets 0. With COUNT(*) she would get 1 and vanish from the result.

You should see
-- INSERT 0 1

-- Task 1
   authorname    | totalbooks
-----------------+------------
 Haruki Murakami |          2
 J.K Rowling     |          2
 Aung Aung       |          1
(3 rows)

-- Task 2
       title        | totalsold
--------------------+-----------
 Norwegian Wood     |         3
 Harry Potter       |         2
 Kafka on the Shore |         1
(3 rows)

-- Task 3
 customername | ordercount
--------------+------------
 Mya Mya      |          0
(1 row)

Bonus drill: top 3 by revenue instead of copies

Task 2 counts copies sold, but the owner may care more about revenue. Replacing SUM(o.Quantity) with SUM(o.Quantity * b.Price) changes the ranking: Harry Potter sold only two copies, yet its high price lifts it to second place, and Kafka on the Shore takes third. There is no revenue tie this time, but the b.Title tiebreaker stays, because a tie can appear as soon as the data changes.

top-revenue.sql
SELECT b.Title, SUM(o.Quantity * b.Price) AS Revenue
FROM Orders AS o
INNER JOIN Books AS b ON o.BookID = b.BookID
GROUP BY b.BookID, b.Title
ORDER BY Revenue DESC, b.Title
LIMIT 3;
--  Norwegian Wood     | 36000.00
--  Harry Potter       | 30000.00
--  Kafka on the Shore | 13000.00

In real projects

In real projects

Reports such as "top 10 best sellers", "best salesperson this month" and "signups who have not ordered yet" use the three patterns in this lesson directly. On dashboards, a top-N list without a tiebreaker can show a different item in third place every time the page is refreshed, and users report it as a bug.

Financial reports must show "no sales" as 0, not NULL, because empty cells cause trouble when the data is exported to a spreadsheet and summed. Whenever analysts build a new report, they also compare the sum across all groups with the total for the whole table, to catch rows that a join duplicated or dropped.

Common mistakes

Common mistakes

Writing LIMIT before ORDER BY

... GROUP BY b.Title LIMIT 3 ORDER BY TotalSold DESC; is a syntax error at or near "ORDER" in PostgreSQL. Write LIMIT after ORDER BY; the clause order is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.

Using COUNT(*) after a LEFT JOIN

As the problem section showed, groups with no match get 1 instead of 0. Count the right-hand table's primary key instead.

A top-N list without a tiebreaker

ORDER BY TotalSold DESC LIMIT 3 does not say which tied row to keep, so the result can differ between runs. Add Title or an ID as the last sort key; if you want to show every tied row instead, use RANK() from the window functions lesson.

Grouping by name instead of ID

With GROUP BY Customers.CustomerName, two different customers both named Su Su are merged into one line such as "Su Su - 4 orders". Group by ID and add the name alongside it.

Mini challenge

Sales summary per city

On the data that already includes Mya Mya, write a report showing, for each city, the number of customers, the number of orders and the revenue. Bago, which has no orders, must appear with 0.

  • Start FROM Customers and LEFT JOIN Orders and Books
  • Count customers with COUNT(DISTINCT c.CustomerID)
  • Count orders with COUNT(o.OrderID)
  • Compute revenue with COALESCE(SUM(o.Quantity * b.Price), 0)
  • Sort by revenue, highest first, then by city name
city-summary.sql
-- Customers already includes (4, 'Mya Mya', 'myamya@mail.com', 'Bago').
SELECT c.City,
       -- TODO: distinct customers AS customers
       -- TODO: matched orders AS orders
       -- TODO: revenue that shows 0 instead of NULL AS revenue
FROM Customers AS c
-- TODO: LEFT JOIN Orders, then LEFT JOIN Books
-- TODO: group per city
-- TODO: highest revenue first, ties by city
;

Expected: Three rows: Yangon - 2 customers - 3 orders - 79000.00; Mandalay - 1 - 1 - 5000.00; Bago - 1 - 0 - 0.

Show hint

Yangon has two customers and Su Su has two orders, so after the join there are three Yangon rows; that is why customers are counted with DISTINCT. Books must be LEFT JOINed too: an INNER JOIN would drop Mya Mya's row.

Show solution
city-summary.sql
SELECT c.City,
       COUNT(DISTINCT c.CustomerID) AS customers,
       COUNT(o.OrderID) AS orders,
       COALESCE(SUM(o.Quantity * b.Price), 0) AS revenue
FROM Customers AS c
LEFT JOIN Orders AS o ON o.CustomerID = c.CustomerID
LEFT JOIN Books AS b ON b.BookID = o.BookID
GROUP BY c.City
ORDER BY revenue DESC, c.City;

Quick quiz 1 / 3

After Customers LEFT JOIN Orders grouped by customer, what do COUNT(*) and COUNT(o.OrderID) return for Mya Mya, who has no orders?

Quick quiz 2 / 3

If Task 2 used ORDER BY TotalSold DESC LIMIT 3 with no tiebreaker, what could happen?

Quick quiz 3 / 3

You want every customer's total spending, including those with no orders, showing 0 when there is none. Which expression is right?

What to remember

  • Build in stages (join, GROUP BY, HAVING, ORDER BY, LIMIT) and run each stage
  • Group by ID and add the name to GROUP BY for display
  • Give top-N queries a unique tiebreaker and write LIMIT after ORDER BY
  • After a LEFT JOIN count the right-hand primary key and wrap SUM in COALESCE
  • Make sure test data contains both a "yes" case and a "no" case

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.

Practice Set 2: Joins & Aggregates | Thuta Learning