MySQL Mini Project
In this project you'll build a small loyalty programme for the shop, step by step. It brings together much of the course: views, CASE, table design with constraints, INSERT ... SELECT, a stored procedure with a transaction, a trigger, and a final report with CTEs and window functions.
The plan:
- A view with each customer's spending.
- Loyalty tiers computed from it.
- A
loyalty_accountstable, filled from the view. - A
place_orderprocedure that checks stock and records the order in one transaction. - A trigger that awards points for every order line automatically.
- A management report.
Every playground starts from a fresh copy of the shop database, so each step first repeats the objects it needs from earlier steps (marked -- from step N). In a real project you'd run each step once, in order, as a migration script.
Step 1: What is each customer worth?
Start with a view that sums the value of each customer's non-cancelled orders. A LEFT JOIN keeps customers who never ordered, and COALESCE turns their NULL total into 0:
CREATE VIEW customer_value AS
SELECT c.customer_id,
CONCAT(c.first_name, ' ', c.last_name) AS customer,
COUNT(DISTINCT o.order_id) AS orders,
COALESCE(ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2), 0) AS spent
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id AND o.status <> 'cancelled'
LEFT JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY c.customer_id, c.first_name, c.last_name;
SELECT * FROM customer_value ORDER BY spent DESC, customer_id;+-------------+---------------+--------+--------+
| customer_id | customer | orders | spent |
+-------------+---------------+--------+--------+
| 1 | Ana Silva | 3 | 128.01 |
| 4 | Daniel Weber | 2 | 55.92 |
| 5 | Elena Rossi | 2 | 53.45 |
| 2 | Ben Carter | 2 | 50.75 |
| 12 | Lucia Garcia | 2 | 42.24 |
| 8 | Hana Sato | 2 | 37.06 |
| 14 | Noah Fischer | 1 | 36.50 |
| 11 | Kofi Mensah | 1 | 34.38 |
| 10 | Julia Novak | 1 | 24.00 |
| 15 | Olivia Moreau | 1 | 18.78 |
| 6 | Farah Khan | 1 | 16.54 |
| 3 | Chloe Martin | 1 | 11.45 |
| 9 | Ivan Petrov | 1 | 10.47 |
| 7 | George Brown | 0 | 0.00 |
| 13 | Mia Jensen | 0 | 0.00 |
+-------------+---------------+--------+--------+
Note that the status test sits in the ON clause: in WHERE it would throw away George and Mia, who have no orders at all.
Step 2: Loyalty tiers
Marketing wants three tiers: gold from 50 spent, silver from 25, bronze for everyone else. A CASE expression over the view does it, and a grouped query shows how big each tier is:
-- from step 1
CREATE VIEW customer_value AS
SELECT c.customer_id, CONCAT(c.first_name, ' ', c.last_name) AS customer,
COUNT(DISTINCT o.order_id) AS orders,
COALESCE(ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2), 0) AS spent
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'
LEFT JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY c.customer_id, c.first_name, c.last_name;
-- step 2
SELECT tier, COUNT(*) AS customers, MIN(spent) AS lowest, MAX(spent) AS highest
FROM (
SELECT spent,
CASE WHEN spent >= 50 THEN 'gold'
WHEN spent >= 25 THEN 'silver'
ELSE 'bronze' END AS tier
FROM customer_value
) AS t
GROUP BY tier
ORDER BY FIELD(tier, 'gold', 'silver', 'bronze');+--------+-----------+--------+---------+
| tier | customers | lowest | highest |
+--------+-----------+--------+---------+
| gold | 4 | 50.75 | 128.01 |
| silver | 4 | 34.38 | 42.24 |
| bronze | 7 | 0.00 | 24.00 |
+--------+-----------+--------+---------+
Step 3: The loyalty_accounts table
Each customer gets one loyalty account. The design uses the constraints from the Database section: the primary key is also a foreign key (one account per customer, deleted with the customer), the tier is an ENUM, and a CHECK keeps points non-negative. The accounts are filled straight from the view with INSERT ... SELECT, one point per whole euro spent:
-- from step 1
CREATE VIEW customer_value AS
SELECT c.customer_id, CONCAT(c.first_name, ' ', c.last_name) AS customer,
COUNT(DISTINCT o.order_id) AS orders,
COALESCE(ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2), 0) AS spent
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'
LEFT JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY c.customer_id, c.first_name, c.last_name;
-- step 3
CREATE TABLE loyalty_accounts (
customer_id INT PRIMARY KEY,
tier ENUM('bronze', 'silver', 'gold') NOT NULL DEFAULT 'bronze',
points INT NOT NULL DEFAULT 0,
joined_on DATE NOT NULL,
CONSTRAINT fk_loyalty_customer FOREIGN KEY (customer_id)
REFERENCES customers (customer_id) ON DELETE CASCADE,
CONSTRAINT chk_points CHECK (points >= 0)
);
INSERT INTO loyalty_accounts (customer_id, tier, points, joined_on)
SELECT customer_id,
CASE WHEN spent >= 50 THEN 'gold' WHEN spent >= 25 THEN 'silver' ELSE 'bronze' END,
FLOOR(spent),
'2025-06-15'
FROM customer_value;
SELECT a.customer_id, v.customer, a.tier, a.points
FROM loyalty_accounts AS a
JOIN customer_value AS v ON v.customer_id = a.customer_id
WHERE a.tier <> 'bronze'
ORDER BY a.points DESC;+-------------+--------------+--------+--------+
| customer_id | customer | tier | points |
+-------------+--------------+--------+--------+
| 1 | Ana Silva | gold | 128 |
| 4 | Daniel Weber | gold | 55 |
| 5 | Elena Rossi | gold | 53 |
| 2 | Ben Carter | gold | 50 |
| 12 | Lucia Garcia | silver | 42 |
| 8 | Hana Sato | silver | 37 |
| 14 | Noah Fischer | silver | 36 |
| 11 | Kofi Mensah | silver | 34 |
+-------------+--------------+--------+--------+
Step 4: Placing an order safely
Placing an order touches three tables: a new row in orders, a line in order_details, and less stock in products. The procedure does all three inside a transaction and refuses the order if there isn't enough stock. An EXIT HANDLER rolls back on any error and passes it on to the caller with RESIGNAL:
DELIMITER //
CREATE PROCEDURE place_order(IN p_customer INT, IN p_product INT, IN p_qty INT, IN p_day DATE)
BEGIN
DECLARE v_stock INT;
DECLARE v_price DECIMAL(8,2);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
SELECT units_in_stock, unit_price INTO v_stock, v_price
FROM products WHERE product_id = p_product
FOR UPDATE; -- lock the product row
IF v_stock IS NULL OR v_stock < p_qty THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Not enough stock';
END IF;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (p_customer, 5, p_day, 'processing');
INSERT INTO order_details (order_id, product_id, quantity, unit_price)
VALUES (LAST_INSERT_ID(), p_product, p_qty, v_price);
UPDATE products SET units_in_stock = units_in_stock - p_qty WHERE product_id = p_product;
COMMIT;
END //
DELIMITER ;
CALL place_order(7, 7, 2, '2025-06-16'); -- George buys 2 chocolate cakes
SELECT o.order_id, o.customer_id, d.product_id, d.quantity, d.unit_price, p.units_in_stock
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
JOIN products AS p ON p.product_id = d.product_id
WHERE o.order_date = '2025-06-16';
CALL place_order(13, 7, 50, '2025-06-16'); -- only 6 cakes left+----------+-------------+------------+----------+------------+----------------+
| order_id | customer_id | product_id | quantity | unit_price | units_in_stock |
+----------+-------------+------------+----------+------------+----------------+
| 23 | 7 | 7 | 2 | 18.00 | 6 |
+----------+-------------+------------+----------+------------+----------------+
ERROR 1644 (45000) at line 37: Not enough stock
The second call failed and nothing was written: the ROLLBACK in the handler undid the transaction, and RESIGNAL reported the original error to the caller.
Step 5: Points by trigger
New orders should earn points automatically, whatever program inserts them. An AFTER INSERT trigger on order_details adds one point per whole euro of each new line to the customer's account:
-- from step 3 (simplified: everybody starts in bronze with 0 points)
CREATE TABLE loyalty_accounts (
customer_id INT PRIMARY KEY,
tier ENUM('bronze', 'silver', 'gold') NOT NULL DEFAULT 'bronze',
points INT NOT NULL DEFAULT 0,
CONSTRAINT fk_loyalty_customer FOREIGN KEY (customer_id)
REFERENCES customers (customer_id) ON DELETE CASCADE
);
INSERT INTO loyalty_accounts (customer_id) SELECT customer_id FROM customers;
-- step 5
DELIMITER //
CREATE TRIGGER trg_award_points
AFTER INSERT ON order_details
FOR EACH ROW
BEGIN
UPDATE loyalty_accounts AS a
JOIN orders AS o ON o.customer_id = a.customer_id
SET a.points = a.points + FLOOR(NEW.quantity * NEW.unit_price * (1 - NEW.discount))
WHERE o.order_id = NEW.order_id;
END //
DELIMITER ;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (13, 6, '2025-06-17', 'processing');
SET @oid = LAST_INSERT_ID();
INSERT INTO order_details (order_id, product_id, quantity, unit_price)
VALUES (@oid, 1, 2, 24.50), -- 49 points
(@oid, 17, 3, 5.49); -- 16 points
SELECT customer_id, tier, points FROM loyalty_accounts WHERE customer_id IN (7, 13);+-------------+--------+--------+
| customer_id | tier | points |
+-------------+--------+--------+
| 7 | bronze | 0 |
| 13 | bronze | 65 |
+-------------+--------+--------+
Mia (13) earned 49 + 16 = 65 points from two lines; George's account didn't change. Because the rule lives in the database, it also applies to orders created by the place_order procedure, an admin script or a future mobile app.
Step 6: The management report
Finally, a monthly report: revenue per month, the running total, the change compared with the previous month, and the best-selling product of each month. Two CTEs keep it readable, and window functions do the month-to-month work:
WITH order_lines AS (
SELECT DATE_FORMAT(o.order_date, '%Y-%m') AS month,
d.product_id,
d.quantity,
d.quantity * d.unit_price * (1 - d.discount) AS value
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
WHERE o.status <> 'cancelled'
),
monthly AS (
SELECT month, ROUND(SUM(value), 2) AS revenue
FROM order_lines
GROUP BY month
),
top_products AS (
SELECT month, product_id,
ROW_NUMBER() OVER (PARTITION BY month ORDER BY SUM(quantity) DESC, product_id) AS pos
FROM order_lines
GROUP BY month, product_id
)
SELECT m.month,
m.revenue,
SUM(m.revenue) OVER (ORDER BY m.month) AS running_total,
m.revenue - LAG(m.revenue) OVER (ORDER BY m.month) AS vs_previous,
p.name AS best_seller
FROM monthly AS m
JOIN top_products AS t ON t.month = m.month AND t.pos = 1
JOIN products AS p ON p.product_id = t.product_id
ORDER BY m.month;+---------+---------+---------------+-------------+--------------------+
| month | revenue | running_total | vs_previous | best_seller |
+---------+---------+---------------+-------------+--------------------+
| 2025-01 | 139.87 | 139.87 | NULL | Dark Chocolate Bar |
| 2025-02 | 66.09 | 205.96 | -73.78 | Sea Salt Crisps |
| 2025-03 | 96.98 | 302.94 | 30.89 | Butter Croissant |
| 2025-04 | 89.14 | 392.08 | -7.84 | Avocado (each) |
| 2025-05 | 82.85 | 474.93 | -6.29 | Butter Croissant |
| 2025-06 | 44.62 | 519.55 | -38.23 | Sea Salt Crisps |
+---------+---------+---------------+-------------+--------------------+
January was the best month; June has only started (its orders are still being processed), so the drop there isn't alarming yet.
Ideas to extend the project
- Add a stored procedure
recalculate_tiers()that updates every account's tier from its points. - Add a
points_ledgertable (customer, change, reason, date) and let the trigger write to it, so that every point can be explained. - Make the trigger handle
DELETEonorder_detailstoo, taking points back when a line is removed. - Restrict access: create a
reportingrole that may onlySELECTfrom thecustomer_valueview.
Test yourself
In step 1, why is o.status <> 'cancelled' in the ON clause instead of WHERE?
- ON is faster
- In WHERE it would remove customers without any orders
- WHERE can't compare text
- It makes no difference
What does the EXIT HANDLER in place_order do when SIGNAL raises 'Not enough stock'?
- Ignores the error and commits
- Rolls back the transaction and re-raises the error
- Retries the order
- Deletes the product
Why put the points rule in a trigger rather than in one application?
- Triggers are faster than any application
- It applies to every insert, whichever program makes it
- Triggers can't fail
- Procedures can't update tables