← Back to SQL, page 16

sql-0316 · Medium mid

Design the core tables for an online shop: customers, products, orders, order lines and payments.

Use customers, products, orders (customer, status, timestamps), order_lines (order, product, quantity, unit price paid) and payments (order, amount, method, status, provider reference). Store the price paid on each line, keep money in integer minor units or NUMERIC, and allow several payments per order for retries, partial payments and refunds.

Full answer
text
customers(id PK, email UNIQUE, name, created_at)
products(id PK, sku UNIQUE, name, price_cents, active)
orders(id PK, customer_id FK, status, placed_at, currency)
order_lines(order_id FK, line_no, product_id FK, qty CHECK > 0, unit_price_cents,
            PRIMARY KEY (order_id, line_no))
payments(id PK, order_id FK, amount_cents, method, status, provider_ref UNIQUE, created_at)

Decisions worth explaining:

  • unit_price_cents on the line is a snapshot, so price changes do not rewrite history.
  • status uses a CHECK or a lookup table, and transitions (pending to paid to shipped) are enforced in one place.
  • Payments are a separate table, because one order can have a failed attempt, a success and a later refund.
  • Indexes: orders(customer_id, placed_at) for a customer's order history, order_lines(product_id) for product reports.
  • Addresses are copied onto the order at checkout for the same snapshot reason.

Key points

  • Store the price paid on each order line
  • Use integer cents or NUMERIC for money
  • Allow several payments per order
  • Copy addresses onto orders at checkout
  • Index for the main access paths

Common mistakes

  • Computing order totals from current product prices
  • One payment column on the order that cannot represent refunds

Follow-ups

  • How would you add discounts and taxes?
  • How would you support multiple currencies?

Tips

  • Explain each snapshot decision