E-commerce Schema Case Study

Requirements

  • Customers register with a unique email and can have several addresses.
  • Products belong to one category and have a price and stock.
  • An order belongs to a customer, ships to one of their addresses and contains several products.
  • The price paid must be kept even if the product price changes later.

Schema

Example

Create the six tables and two indexes, then list the tables:

CREATE TABLE Category (CategoryID INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL UNIQUE);
CREATE TABLE Customer (
  CustomerID INTEGER PRIMARY KEY,
  Email VARCHAR(255) NOT NULL UNIQUE,
  FullName VARCHAR(100) NOT NULL
);
CREATE TABLE Address (
  AddressID INTEGER PRIMARY KEY,
  CustomerID INT NOT NULL REFERENCES Customer(CustomerID),
  Line1 VARCHAR(200) NOT NULL, City VARCHAR(50) NOT NULL, PinCode VARCHAR(10)
);
CREATE TABLE Product (
  ProductID INTEGER PRIMARY KEY,
  CategoryID INT NOT NULL REFERENCES Category(CategoryID),
  Name VARCHAR(100) NOT NULL,
  Price DECIMAL(10,2) NOT NULL CHECK (Price >= 0),
  Stock INT NOT NULL DEFAULT 0 CHECK (Stock >= 0)
);
CREATE TABLE CustomerOrder (
  OrderID INTEGER PRIMARY KEY,
  CustomerID INT NOT NULL REFERENCES Customer(CustomerID),
  ShipToAddressID INT NOT NULL REFERENCES Address(AddressID),
  Status VARCHAR(20) NOT NULL DEFAULT 'placed' CHECK (Status IN ('placed','shipped','delivered','cancelled')),
  PlacedAt TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE OrderItem (
  OrderID INT REFERENCES CustomerOrder(OrderID),
  ProductID INT REFERENCES Product(ProductID),
  Quantity INT NOT NULL CHECK (Quantity > 0),
  UnitPrice DECIMAL(10,2) NOT NULL,          -- price at time of purchase
  PRIMARY KEY (OrderID, ProductID)
);
CREATE INDEX IX_Order_Customer ON CustomerOrder(CustomerID);
CREATE INDEX IX_Product_Category ON Product(CategoryID);

SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;

Result: 6 rows

name
Address
Category
Customer
CustomerOrder
OrderItem
Product

Design Decisions

  • UnitPrice is copied into OrderItem: a deliberate, documented redundancy so history is correct.
  • CustomerOrder avoids the reserved word Order.
  • CHECK constraints keep prices, stock and status valid at the database level.
  • Foreign keys used in joins are indexed.