TExcelTAD
Home › PostgreSQL › PostgreSQL Mini Project

PostgreSQL Mini Project

In this project you build the sales dashboard and loyalty programme for TAD Books, step by step. It brings together much of the course: views, joins, aggregates, CASE, CTEs, window functions, generate_series, JSONB, PL/pgSQL functions and triggers.

By the end you will have:

  1. a reusable order_totals view,
  2. customer lifetime values and segments,
  3. a monthly revenue report with growth figures,
  4. best sellers per category,
  5. a sales_summary() function that returns JSON for a web dashboard,
  6. loyalty points that are awarded automatically by a trigger.

Every playground starts from a fresh database, so each step first re-creates the objects it needs from the earlier steps. The reporting date is fixed at 2025-01-01 so the results never change.

Step 1: One row per order

Almost every report needs "the total of an order", so we define it once as a view. A LEFT JOIN keeps orders without lines (there are none today, but a robust view shouldn't lose them):

pgsql · try it yourself
CREATE VIEW order_totals AS
SELECT o.id AS order_id, o.customer_id, o.order_date, o.status,
       count(oi.book_id)                              AS lines,
       coalesce(sum(oi.quantity), 0)                  AS copies,
       coalesce(sum(oi.quantity * oi.unit_price), 0)  AS total
FROM orders o
LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;

SELECT * FROM order_totals WHERE order_id <= 6 ORDER BY order_id;

SELECT status, count(*) AS orders, sum(total) AS value
FROM order_totals
GROUP BY status
ORDER BY value DESC;
CREATE VIEW
 order_id | customer_id | order_date |  status   | lines | copies | total
----------+-------------+------------+-----------+-------+--------+-------
        1 |           1 | 2024-01-05 | delivered |     2 |      2 | 54.89
        2 |           2 | 2024-01-19 | delivered |     1 |      2 | 36.00
        3 |           1 | 2024-02-02 | delivered |     3 |      4 | 43.46
        4 |           3 | 2024-02-14 | delivered |     1 |      1 | 15.20
        5 |           4 | 2024-03-03 | cancelled |     1 |      1 | 44.00
        6 |           5 | 2024-03-21 | delivered |     2 |      2 | 39.00
(6 rows)

  status   | orders | value
-----------+--------+--------
 delivered |     14 | 650.85
 shipped   |      2 |  85.71
 pending   |      2 |  83.47
 cancelled |      2 |  58.99
(4 rows)

From now on, "revenue" means the total of orders that are not cancelled.

Step 2: Customer lifetime value

How much has each customer spent, how many orders did they place and when was the last one? A LEFT JOIN from customers keeps the people who never ordered, with a spend of 0:

pgsql · try it yourself
CREATE VIEW order_totals AS
SELECT o.id AS order_id, o.customer_id, o.order_date, o.status,
       count(oi.book_id) AS lines, coalesce(sum(oi.quantity), 0) AS copies,
       coalesce(sum(oi.quantity * oi.unit_price), 0) AS total
FROM orders o LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;

CREATE VIEW customer_value AS
SELECT c.id, c.first_name || ' ' || c.last_name AS customer, c.country,
       count(t.order_id)          AS orders,
       coalesce(sum(t.total), 0)  AS spent,
       max(t.order_date)          AS last_order
FROM customers c
LEFT JOIN order_totals t ON t.customer_id = c.id AND t.status <> 'cancelled'
GROUP BY c.id;

SELECT * FROM customer_value ORDER BY spent DESC, id;
CREATE VIEW
CREATE VIEW
 id |    customer    |   country   | orders | spent  | last_order
----+----------------+-------------+--------+--------+------------
  2 | Ben Carter     | UK          |      3 | 197.40 | 2024-11-11
  1 | Anna Kowalski  | Poland      |      3 | 127.30 | 2024-07-09
 10 | Jamal Wright   | USA         |      1 |  79.00 | 2024-06-22
  5 | Emma Johansson | Sweden      |      2 |  73.75 | 2024-10-05
  9 | Isla Murray    | UK          |      2 |  69.45 | 2024-12-02
  6 | Farid Haddad   | Lebanon     |      1 |  66.00 | 2024-04-08
 14 | Noah Brown     | Canada      |      1 |  50.96 | 2024-10-28
  4 | David Kim      | South Korea |      1 |  42.50 | 2024-09-14
 11 | Keiko Sato     | Japan       |      1 |  42.00 | 2024-08-02
  8 | Hugo Silva     | Portugal    |      1 |  31.49 | 2024-05-15
 12 | Liam O'Brien   | Ireland     |      1 |  24.98 | 2024-08-30
  3 | Chloé Dubois   | France      |      1 |  15.20 | 2024-02-14
  7 | Gina Rossi     | Italy       |      0 |      0 |
 13 | Mia Fischer    | Germany     |      0 |      0 |
 15 | Olivia Martin  | UK          |      0 |      0 |
(15 rows)

Note the condition t.status <> 'cancelled' sits in the ON clause, not in WHERE, so customers with only cancelled orders are still listed (the LEFT JOIN trap from the joins lessons).

Step 3: Customer segments

Marketing wants four groups. A CASE expression assigns each customer to the first matching segment, measured against the report date 2025-01-01:

Segment Rule
vip spent at least 100
active ordered within the last 120 days
lapsed has ordered, but not recently
prospect never ordered
pgsql · try it yourself
CREATE VIEW order_totals AS
SELECT o.id AS order_id, o.customer_id, o.order_date, o.status,
       coalesce(sum(oi.quantity * oi.unit_price), 0) AS total
FROM orders o LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;

CREATE VIEW customer_value AS
SELECT c.id, c.first_name || ' ' || c.last_name AS customer,
       count(t.order_id) AS orders, coalesce(sum(t.total), 0) AS spent, max(t.order_date) AS last_order
FROM customers c
LEFT JOIN order_totals t ON t.customer_id = c.id AND t.status <> 'cancelled'
GROUP BY c.id;

WITH segmented AS (
    SELECT *,
           CASE
               WHEN spent >= 100 THEN 'vip'
               WHEN last_order >= DATE '2025-01-01' - 120 THEN 'active'
               WHEN orders > 0 THEN 'lapsed'
               ELSE 'prospect'
           END AS segment
    FROM customer_value
)
SELECT segment, count(*) AS customers,
       string_agg(customer, ', ' ORDER BY customer) AS who
FROM segmented
GROUP BY segment
ORDER BY array_position(ARRAY['vip', 'active', 'lapsed', 'prospect'], segment);
CREATE VIEW
CREATE VIEW
 segment  | customers |                                      who
----------+-----------+--------------------------------------------------------------------------------
 vip      |         2 | Anna Kowalski, Ben Carter
 active   |         4 | David Kim, Emma Johansson, Isla Murray, Noah Brown
 lapsed   |         6 | Chloé Dubois, Farid Haddad, Hugo Silva, Jamal Wright, Keiko Sato, Liam O'Brien
 prospect |         3 | Gina Rossi, Mia Fischer, Olivia Martin
(4 rows)

Step 4: Monthly revenue report

A good report shows every month, even one without sales, plus a running total and the change from the previous month. generate_series creates the calendar, lag looks one month back:

pgsql · try it yourself
WITH months AS (
    SELECT generate_series(DATE '2024-01-01', DATE '2024-12-01', INTERVAL '1 month')::date AS month
),
revenue AS (
    SELECT date_trunc('month', o.order_date)::date AS month,
           sum(oi.quantity * oi.unit_price) AS revenue
    FROM orders o JOIN order_items oi ON oi.order_id = o.id
    WHERE o.status <> 'cancelled'
    GROUP BY 1
)
SELECT to_char(m.month, 'Mon') AS month,
       coalesce(r.revenue, 0) AS revenue,
       sum(coalesce(r.revenue, 0)) OVER (ORDER BY m.month) AS year_to_date,
       coalesce(r.revenue, 0) - lag(coalesce(r.revenue, 0)) OVER (ORDER BY m.month) AS change
FROM months m
LEFT JOIN revenue r ON r.month = m.month
ORDER BY m.month;
 month | revenue | year_to_date | change
-------+---------+--------------+---------
 Jan   |   90.89 |        90.89 |
 Feb   |   58.66 |       149.55 |  -32.23
 Mar   |   39.00 |       188.55 |  -19.66
 Apr   |  183.40 |       371.95 |  144.40
 May   |   31.49 |       403.44 | -151.91
 Jun   |  108.98 |       512.42 |   77.49
 Jul   |   28.95 |       541.37 |  -80.03
 Aug   |   66.98 |       608.35 |   38.03
 Sep   |   42.50 |       650.85 |  -24.48
 Oct   |   85.71 |       736.56 |   43.21
 Nov   |   44.00 |       780.56 |  -41.71
 Dec   |   39.47 |       820.03 |   -4.53
(12 rows)

Step 5: Best sellers per category

Which two books sold the most copies in each category? dense_rank over a partition per category gives ties the same position, and the outer query keeps the top two:

pgsql · try it yourself
WITH sales AS (
    SELECT c.name AS category, b.title, sum(oi.quantity) AS copies
    FROM order_items oi
    JOIN orders o     ON o.id = oi.order_id AND o.status <> 'cancelled'
    JOIN books b      ON b.id = oi.book_id
    JOIN categories c ON c.id = b.category_id
    GROUP BY c.name, b.title
),
ranked AS (
    SELECT *, dense_rank() OVER (PARTITION BY category ORDER BY copies DESC) AS pos
    FROM sales
)
SELECT category, pos, title, copies
FROM ranked
WHERE pos <= 2
ORDER BY category, pos, title;
    category     | pos |           title           | copies
-----------------+-----+---------------------------+--------
 Children        |   1 | Ten Tiny Dragons          |      7
 Children        |   2 | Moon Socks                |      5
 Fiction         |   1 | The Salt Road             |      3
 Fiction         |   2 | Paper Lanterns            |      2
 History         |   1 | A Short History of Tea    |      2
 History         |   2 | Empires of Sand           |      1
 Mystery         |   1 | The Map Thief             |      3
 Mystery         |   2 | Murder at Low Tide        |      2
 Mystery         |   2 | The Quiet Witness         |      2
 Programming     |   1 | Algorithms on a Napkin    |      2
 Programming     |   1 | Learning SQL the Calm Way |      2
 Programming     |   1 | Postgres in Practice      |      2
 Programming     |   1 | Rust for Curious Minds    |      2
 Science Fiction |   1 | Signal from Kepler        |      4
 Science Fiction |   2 | Clockwork Garden          |      3
(15 rows)

Step 6: A JSON summary for the dashboard

The web dashboard wants one JSON document with the key figures. A SQL function that takes a date range wraps everything up, so the application only runs SELECT sales_summary(…):

pgsql · try it yourself
CREATE FUNCTION sales_summary(from_date date, to_date date)
RETURNS jsonb
LANGUAGE sql STABLE
AS $
    WITH lines AS (
        SELECT o.id AS order_id, o.customer_id, oi.book_id, oi.quantity, oi.quantity * oi.unit_price AS amount
        FROM orders o JOIN order_items oi ON oi.order_id = o.id
        WHERE o.status <> 'cancelled' AND o.order_date BETWEEN from_date AND to_date
    ),
    top_book AS (
        SELECT b.title, sum(l.quantity) AS copies
        FROM lines l JOIN books b ON b.id = l.book_id
        GROUP BY b.title ORDER BY copies DESC, b.title LIMIT 1
    )
    SELECT jsonb_build_object(
        'period',     jsonb_build_object('from', from_date, 'to', to_date),
        'orders',     (SELECT count(DISTINCT order_id) FROM lines),
        'customers',  (SELECT count(DISTINCT customer_id) FROM lines),
        'revenue',    (SELECT coalesce(sum(amount), 0) FROM lines),
        'avg_order',  (SELECT round(sum(amount) / nullif(count(DISTINCT order_id), 0), 2) FROM lines),
        'top_book',   (SELECT to_jsonb(top_book) FROM top_book)
    )
$;

SELECT jsonb_pretty(sales_summary('2024-01-01', '2024-06-30')) AS first_half;
SELECT sales_summary('2024-07-01', '2024-12-31') ->> 'revenue' AS second_half_revenue;
CREATE FUNCTION
           first_half
--------------------------------
 {                             +
     "orders": 10,             +
     "period": {               +
         "to": "2024-06-30",   +
         "from": "2024-01-01"  +
     },                        +
     "revenue": 512.42,        +
     "top_book": {             +
         "title": "Moon Socks",+
         "copies": 3           +
     },                        +
     "avg_order": 51.24,       +
     "customers": 8            +
 }
(1 row)

 second_half_revenue
---------------------
 307.61
(1 row)

jsonb_pretty formats the document over several lines; psql marks each continued line with a +.

Step 7: Loyalty points with a trigger

Finally, the loyalty programme: customers earn one point per full euro of an order when it is delivered. A trigger on orders awards the points the moment the status changes, so no application code can forget it:

pgsql · try it yourself
CREATE TABLE loyalty_points (
    customer_id integer NOT NULL REFERENCES customers (id),
    order_id    integer NOT NULL UNIQUE REFERENCES orders (id),
    points      integer NOT NULL CHECK (points >= 0)
);

CREATE FUNCTION award_points() RETURNS trigger
LANGUAGE plpgsql AS $
DECLARE
    order_value numeric;
BEGIN
    SELECT coalesce(sum(quantity * unit_price), 0) INTO order_value
    FROM order_items WHERE order_id = NEW.id;

    INSERT INTO loyalty_points (customer_id, order_id, points)
    VALUES (NEW.customer_id, NEW.id, floor(order_value))
    ON CONFLICT (order_id) DO NOTHING;   -- never award the same order twice

    RAISE NOTICE 'order %: % points for customer %', NEW.id, floor(order_value), NEW.customer_id;
    RETURN NEW;
END;
$;

CREATE TRIGGER orders_award_points
AFTER UPDATE OF status ON orders
FOR EACH ROW
WHEN (NEW.status = 'delivered' AND OLD.status IS DISTINCT FROM 'delivered')
EXECUTE FUNCTION award_points();

-- The two shipped orders arrive:
UPDATE orders SET status = 'delivered' WHERE status = 'shipped';
-- Updating an already delivered order awards nothing:
UPDATE orders SET status = 'delivered' WHERE id = 1;

SELECT c.first_name, sum(lp.points) AS points
FROM loyalty_points lp JOIN customers c ON c.id = lp.customer_id
GROUP BY c.first_name
ORDER BY points DESC;
CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
NOTICE:  order 16: 34 points for customer 5
NOTICE:  order 17: 50 points for customer 14
UPDATE 2
UPDATE 1
 first_name | points
------------+--------
 Noah       |     50
 Emma       |     34
(2 rows)

The WHEN condition on the trigger fires it only for real transitions into delivered, and the UNIQUE (order_id) constraint with ON CONFLICT DO NOTHING is a second safety net.

Ideas to extend the project

  • Turn customer_value into a materialized view and refresh it nightly; add an index on spent.
  • Let customers redeem points: a procedure that inserts a negative entry and refuses to go below zero.
  • Add row-level security so each sales agent sees only the customers of their own country.
  • Write the monthly report as a function monthly_report(year integer).

Test yourself

Why is t.status <> 'cancelled' placed in the ON clause of the LEFT JOIN in Step 2?

  1. It is faster
  2. So customers without (non-cancelled) orders are still kept
  3. WHERE can't compare text
  4. It is required by GROUP BY

What makes the monthly report in Step 4 include months without sales?

  1. A RIGHT JOIN on orders
  2. generate_series creating every month, then a LEFT JOIN to the revenue
  3. ORDER BY month
  4. The lag() function

Which part of Step 7 prevents points from being awarded twice for the same order?

  1. RAISE NOTICE
  2. The trigger's WHEN condition plus the UNIQUE (order_id) constraint with ON CONFLICT DO NOTHING
  3. floor()
  4. AFTER instead of BEFORE