TExcelTAD
Home › PostgreSQL › PostgreSQL Exercises

PostgreSQL Exercises

Time to practise on the TAD Books database. Each exercise has a starter playground that already runs: it returns the right columns but not yet the right rows or values. Change the query, press ▶ Run, and compare your result with the "Expected" description. The solutions are hidden; try for a few minutes before you peek.

# Exercise Topics
1 Cheap programming books WHERE, ORDER BY
2 Customers per country GROUP BY, HAVING
3 Order totals JOIN, SUM, ROUND
4 Never ordered LEFT JOIN or NOT EXISTS
5 Best-selling author joins, aggregates, LIMIT
6 Monthly revenue with running total date_trunc, window functions
7 Restock with a transaction UPDATE, RETURNING, transactions
8 A reusable function PL/pgSQL

1. Cheap programming books

List the title and price of every book in category 4 (Programming) that costs less than 42, most expensive first.

Expected: 2 rows, Learning SQL the Calm Way (39.90) and then Algorithms on a Napkin (35.00).

pgsql · try it yourself
-- TODO: filter on category and price, sort by price descending
SELECT title, price
FROM books
WHERE category_id = 4;
           title           | price
---------------------------+-------
 Learning SQL the Calm Way | 39.90
 Postgres in Practice      | 44.00
 Rust for Curious Minds    | 42.50
 Algorithms on a Napkin    | 35.00
(4 rows)
Show solution
sql
SELECT title, price
FROM books
WHERE category_id = 4 AND price < 42
ORDER BY price DESC;

2. Customers per country

Show each country with its number of customers, but only countries with more than one customer.

Expected: one row, UK | 3.

pgsql · try it yourself
-- TODO: keep only groups with more than one customer
SELECT country, count(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country
LIMIT 3;
 country | customers
---------+-----------
 UK      |         3
 Canada  |         1
 France  |         1
(3 rows)
Show solution
sql
SELECT country, count(*) AS customers
FROM customers
GROUP BY country
HAVING count(*) > 1
ORDER BY customers DESC;

3. Order totals

For each of the orders 1 to 5, show the order id, the customer's first name and the order total (quantity * unit_price summed over its lines).

Expected: order 1 belongs to Anna and totals 54.89; order 3 totals 43.46.

pgsql · try it yourself
-- TODO: join customers and order_items, then sum per order
SELECT o.id, o.customer_id
FROM orders o
WHERE o.id <= 5
ORDER BY o.id;
 id | customer_id
----+-------------
  1 |           1
  2 |           2
  3 |           1
  4 |           3
  5 |           4
(5 rows)
Show solution
sql
SELECT o.id, c.first_name, sum(oi.quantity * oi.unit_price) AS total
FROM orders o
JOIN customers c    ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.id <= 5
GROUP BY o.id, c.first_name
ORDER BY o.id;

4. Never ordered

Find the books (id and title) that do not appear in any order.

Expected: 3 rows: ids 2, 12 and 16.

pgsql · try it yourself
-- TODO: keep only books without order lines
SELECT b.id, b.title
FROM books b
ORDER BY b.id
LIMIT 3;
 id |       title
----+--------------------
  1 | The Salt Road
  2 | Harbor Lights
  3 | Signal from Kepler
(3 rows)
Show solution
sql
SELECT b.id, b.title
FROM books b
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.book_id = b.id)
ORDER BY b.id;

5. Best-selling author

Which author sold the most copies (sum of quantity) across all orders that were not cancelled? Show the name and the number of copies.

Expected: Aiko Tanaka | 10.

pgsql · try it yourself
-- TODO: join order_items -> books -> authors, exclude cancelled orders, group and pick the top one
SELECT a.name, 0 AS copies
FROM authors a
LIMIT 1;
     name     | copies
--------------+--------
 Maria Okafor |      0
(1 row)
Show solution
sql
SELECT a.name, sum(oi.quantity) AS copies
FROM order_items oi
JOIN orders o  ON o.id = oi.order_id
JOIN books b   ON b.id = oi.book_id
JOIN authors a ON a.id = b.author_id
WHERE o.status <> 'cancelled'
GROUP BY a.id, a.name
ORDER BY copies DESC
LIMIT 1;

6. Monthly revenue with running total

For delivered orders, show each month (YYYY-MM), its revenue, and a running total of revenue across the year.

Expected: the first row is 2024-01 | 90.89 | 90.89; the last row (2024-09) has a running total of 650.85.

pgsql · try it yourself
-- TODO: add revenue per month and a running total with sum(...) OVER (ORDER BY ...)
SELECT to_char(o.order_date, 'YYYY-MM') AS month
FROM orders o
WHERE o.status = 'delivered'
GROUP BY month
ORDER BY month;
  month
---------
 2024-01
 2024-02
 2024-03
 2024-04
 2024-05
 2024-06
 2024-07
 2024-08
 2024-09
(9 rows)
Show solution
sql
SELECT to_char(o.order_date, 'YYYY-MM') AS month,
       sum(oi.quantity * oi.unit_price) AS revenue,
       sum(sum(oi.quantity * oi.unit_price)) OVER (ORDER BY to_char(o.order_date, 'YYYY-MM')) AS running_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered'
GROUP BY month
ORDER BY month;

7. Restock with a transaction

Inside a transaction, add 10 copies to every book that has fewer than 3 in stock and return the titles and new stock. Then add a row to a restock_log (book_id, added) table for each restocked book and commit.

Expected: 4 books are restocked (stock 10, 10, 11 and 12) and the log has 4 rows.

pgsql · try it yourself
CREATE TABLE restock_log (book_id integer, added integer);

BEGIN;
-- TODO: UPDATE ... RETURNING, then INSERT INTO restock_log
COMMIT;

SELECT count(*) AS logged FROM restock_log;
CREATE TABLE
BEGIN
COMMIT
 logged
--------
      0
(1 row)
Show solution
sql
CREATE TABLE restock_log (book_id integer, added integer);

BEGIN;
WITH restocked AS (
    UPDATE books SET stock = stock + 10 WHERE stock < 3
    RETURNING id, title, stock
),
logged AS (
    INSERT INTO restock_log (book_id, added)
    SELECT id, 10 FROM restocked
)
SELECT title, stock FROM restocked ORDER BY title;
COMMIT;

SELECT count(*) AS logged FROM restock_log;

The data-modifying CTE does the update and the log insert in one statement, so the log can never get out of step with the stock change. Two separate statements inside the transaction would also work, as long as the second one can identify exactly the restocked rows.

8. A reusable function

Write a function order_total(order_id integer) that returns the total value of an order (0 if it has no lines) and use it to list orders 16 to 20 with their totals.

Expected: order 16 totals 34.75 and order 20 totals 14.99.

pgsql · try it yourself
-- TODO: compute the real total inside the function
CREATE FUNCTION order_total(p_order_id integer) RETURNS numeric
LANGUAGE sql STABLE
RETURN 0;

SELECT id, status, order_total(id) AS total
FROM orders
WHERE id >= 16
ORDER BY id;
CREATE FUNCTION
 id |  status   | total
----+-----------+-------
 16 | shipped   |     0
 17 | shipped   |     0
 18 | pending   |     0
 19 | pending   |     0
 20 | cancelled |     0
(5 rows)
Show solution
sql
CREATE FUNCTION order_total(p_order_id integer) RETURNS numeric
LANGUAGE sql STABLE
RETURN (SELECT coalesce(sum(quantity * unit_price), 0)
        FROM order_items WHERE order_id = p_order_id);

SELECT id, status, order_total(id) AS total
FROM orders
WHERE id >= 16
ORDER BY id;

Test yourself

You need 'countries with more than one customer'. Which clause holds count(*) > 1?

  1. WHERE
  2. HAVING
  3. ORDER BY
  4. LIMIT

Which approach finds books that were never ordered without being confused by NULLs?

  1. WHERE id NOT IN (SELECT book_id ...)
  2. WHERE NOT EXISTS (SELECT 1 FROM order_items WHERE book_id = b.id)
  3. WHERE book_id IS NULL without a join
  4. INNER JOIN order_items