Final project: the database of a small shop
The time has come to show everything you have learned. In this project you will design from scratch the database of a small shop of your own (a bakery, a bookshop, a clothes shop, whatever you prefer), fill it with test data and build the reports its owner would need. Until now you worked on a shop that was already built; now the design is yours, and that is why this project brings together all eight weeks: modeling, constraints, safe insertion, queries with JOIN, aggregations, CTEs, window functions, views, indexes and transactions.
Requirements
- Create a new database (for example project_shop) or your own schema; do not modify the course shop tables.
- At least 4 related tables: customers, products, orders and order lines (or the equivalent for your business), plus one extra table of your choice (categories, suppliers, reviews).
- Every table with a primary key, foreign keys, correct types (NUMERIC for money, DATE for dates) and at least one meaningful NOT NULL, UNIQUE and CHECK.
- Test data: at least 8 customers, 10 products, 15 orders and 30 lines, with some customer without orders, some product without sales and some deliberate NULL.
- 8 reports (queries) with the requirements below, saved in a file project_reports.sql.
- One view, one index justified with EXPLAIN and one transaction that registers a complete order.
The 8 reports
- 1) Total sales per month (without cancelled orders), sorted by date.
- 2) The 5 best-selling products by units, with their revenue.
- 3) Customers with their number of orders and total spent, including those who never bought (LEFT JOIN).
- 4) Products that have never been sold.
- 5) Average ticket per customer and customers whose spending exceeds the global average ticket (CTE).
- 6) Per category, the product with the most revenue (ROW_NUMBER with PARTITION BY).
- 7) Month-by-month cumulative revenue (SUM with OVER) and change from the previous month (LAG).
- 8) An order status report in a single row with CASE or FILTER.
Suggested steps
First write on paper the nouns of your business and the relationships (a customer has many orders; an order has many products through the lines). Draw the tables with their keys. Then create the schema in a file project_schema.sql, run it from scratch every time you change something (start with DROP TABLE IF EXISTS in reverse order) and load the data in project_data.sql. Build the reports one by one, checking each result with hand calculations on a few rows. Finish with the view, the index and the transaction. Working with scripts, and not by clicking around, lets you rebuild everything in seconds and is the professional habit.
-- project_schema.sql : a starting skeleton for a small bakery (adapt it to YOUR shop)
DROP TABLE IF EXISTS sale_lines;
DROP TABLE IF EXISTS sales;
DROP TABLE IF EXISTS items;
DROP TABLE IF EXISTS item_categories;
DROP TABLE IF EXISTS clients;
CREATE TABLE clients (
client_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
joined_on DATE NOT NULL DEFAULT CURRENT_DATE
);
CREATE TABLE item_categories (
category_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL UNIQUE
);
CREATE TABLE items (
item_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL,
category_id INTEGER NOT NULL REFERENCES item_categories (category_id),
price NUMERIC(8,2) NOT NULL CHECK (price > 0),
stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0)
);
CREATE TABLE sales (
sale_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
client_id INTEGER NOT NULL REFERENCES clients (client_id),
sale_date DATE NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'cancelled'))
);
CREATE TABLE sale_lines (
sale_id INTEGER NOT NULL REFERENCES sales (sale_id),
item_id INTEGER NOT NULL REFERENCES items (item_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(8,2) NOT NULL,
PRIMARY KEY (sale_id, item_id)
);
CREATE INDEX idx_sales_client ON sales (client_id);
CREATE INDEX idx_sale_lines_item ON sale_lines (item_id);-- project_reports.sql : two of the eight reports, as a model of the expected quality
-- Report 1: monthly sales without cancelled sales
SELECT DATE_TRUNC('month', s.sale_date)::DATE AS month,
COUNT(DISTINCT s.sale_id) AS sales,
SUM(l.quantity * l.unit_price) AS revenue
FROM sales s
JOIN sale_lines l ON l.sale_id = s.sale_id
WHERE s.status <> 'cancelled'
GROUP BY 1
ORDER BY 1;
-- Report 7: cumulative revenue and change versus the previous month
WITH monthly AS (
SELECT DATE_TRUNC('month', s.sale_date)::DATE AS month,
SUM(l.quantity * l.unit_price) AS revenue
FROM sales s JOIN sale_lines l ON l.sale_id = s.sale_id
WHERE s.status <> 'cancelled'
GROUP BY 1
)
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS cumulative,
revenue - LAG(revenue) OVER (ORDER BY month) AS change_vs_previous
FROM monthly
ORDER BY month;
-- Transaction: register a complete sale or nothing at all
BEGIN;
INSERT INTO sales (client_id, sale_date, status) VALUES (1, CURRENT_DATE, 'paid');
INSERT INTO sale_lines (sale_id, item_id, quantity, unit_price)
VALUES (currval(pg_get_serial_sequence('sales', 'sale_id')), 1, 2, 3.50);
UPDATE items SET stock = stock - 2 WHERE item_id = 1; -- the CHECK rejects negative stock
COMMIT;Completion criteria
- The scripts project_schema.sql and project_data.sql run from start to finish without errors on an empty database.
- You tried to violate each constraint (negative price, nonexistent customer, repeated value) and got the expected error.
- The 8 reports return results that you verified by hand on at least one row.
- There is a useful view, an index with an EXPLAIN before and after, and a transaction tested with COMMIT and with ROLLBACK.
- There are no SELECT * queries in the reports nor UPDATE or DELETE without WHERE.
- You wrote 5 lines explaining a design decision you made (for example, why you store unit_price in the line).
理解度チェック
問題 1 / 7Which clause do you use to filter groups by an aggregated result?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字