Home / Database Types / Article
DATABASELAB TECHNICAL GUIDE

How to Design a Database for an Online Store: Products, Customers, and Orders

SOFTWARE ENGINEERING / RELATIONAL DATABASE DESIGN

Building the Data Foundation of an Online Store

A practical guide to organizing product catalogs, customer accounts, shopping orders, and inventory using relational database principles.

TABLE DESIGN SQL DATA INTEGRITY

An online store may look simple to customers. They browse products, add items to a cart, enter shipping information, and place an order.

Behind that experience is a database responsible for keeping thousands—or millions—of pieces of information organized.

A poorly designed database can cause duplicate customer records, incorrect inventory counts, confusing order histories, and difficult application updates.

A well-designed database makes these operations easier to manage and helps maintain reliable data as the business grows.

This guide explains how to design a practical relational database for an online store using three essential areas: products, customers, and orders.

1. Start with the Store’s Data Requirements

Before creating tables, identify the information the store must remember.

For a basic e-commerce application, the database should answer questions such as:

  • Which products are available for purchase?
  • What is the current price of each product?
  • Which customers have registered accounts?
  • What items were included in a particular order?
  • How much did the customer pay?
  • What is the order’s payment and fulfillment status?
  • How much inventory remains?

These requirements help identify the main entities that should become database tables.

A useful starting structure contains customers, products, orders, and order_items. A production store will usually need additional tables for addresses, payments, product variants, and inventory movements.

2. Understand Primary Keys and Foreign Keys

Relational databases connect information through keys.

A primary key uniquely identifies a row within a table. For example, every customer can have a unique customer_id.

A foreign key references a row in another table. For example, an order can contain a customer_id that references the customers table.

These relationships help prevent invalid references, such as an order pointing to a customer record that does not exist.

DATABASE DESIGN RULE

Store each important fact in the appropriate table, connect related records through keys, and use constraints to protect data integrity.

3. Design the Customers Table

The customers table stores information about people who create accounts or purchase products.

A basic structure might include:

ColumnPurpose
customer_idUnique customer identifier
full_nameCustomer name
emailAccount email address
password_hashSecure password hash, never plaintext
created_atAccount creation timestamp

Email addresses may need a uniqueness constraint for registered accounts. The application should also use an appropriate password-hashing algorithm, such as Argon2id, rather than storing passwords directly.

Guest checkout may require a different approach because not every order must belong to a registered customer.

4. Create the Products Table

The products table describes items offered for sale.

Common fields include a product identifier, name, description, price, status, and creation date.

For a simple store, a product might have one price and one stock-keeping unit.

More complex stores often need separate product-variant records. A T-shirt, for example, may have different sizes and colors, each with its own SKU and inventory quantity.

It is usually better to model these variants separately than to create columns such as small_red_stock and large_blue_stock.

Product prices should use a fixed-precision decimal type or an integer representing the smallest currency unit. Floating-point types can introduce rounding problems in financial calculations.

5. Design Orders and Order Items Separately

One customer can place many orders, and one order can contain many products.

Storing every purchased product in a single text field makes searching, reporting, and inventory management difficult.

Instead, use two related tables.

The orders table stores information about the transaction as a whole, including the customer, order date, status, and total.

The order_items table stores each purchased item, its quantity, and the price charged at the time of purchase.

Keeping the purchase-time price is essential. If a product’s current price changes next month, historical orders must still show what customers originally paid.

RELATIONSHIP BLUEPRINT

CUSTOMERS 1 → MANY ORDERS

ORDERS 1 → MANY ORDER_ITEMS

PRODUCTS 1 → MANY ORDER_ITEMS

Order items connect orders to products, creating a many-to-many relationship between orders and products.

6. Example SQL Database Schema

The following simplified PostgreSQL schema demonstrates the four core tables.

CREATE TABLE customers (
    customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    full_name VARCHAR(150) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE products (
    product_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    price NUMERIC(12, 2) NOT NULL CHECK (price >= 0),
    is_active BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE orders (
    order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id BIGINT REFERENCES customers(customer_id),
    order_status VARCHAR(30) NOT NULL DEFAULT 'pending',
    order_total NUMERIC(12, 2) NOT NULL
        CHECK (order_total >= 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE order_items (
    order_item_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id BIGINT NOT NULL REFERENCES orders(order_id),
    product_id BIGINT NOT NULL REFERENCES products(product_id),
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    unit_price NUMERIC(12, 2) NOT NULL
        CHECK (unit_price >= 0)
);

This is an educational starting point, not a complete production checkout schema. A real application should also define allowed order statuses, currency handling, shipping and tax totals, deletion policies, and transactional checkout logic.

7. Use Normalization to Avoid Duplicate Data

Database normalization is the practice of organizing data to reduce unnecessary duplication and improve consistency.

For example, repeating a customer’s email address in every order can create problems when the customer updates their account.

Instead, orders can reference the customer record through customer_id.

Similarly, product details should generally live in the products table rather than being repeated throughout the database.

However, certain historical details should intentionally be preserved in orders.

Purchased item names, unit prices, shipping addresses, and applicable taxes may need snapshots because these facts must remain accurate even after the original records change.

Good database design balances normalization with the need to preserve transaction history.

8. Plan Inventory Management Carefully

Inventory becomes challenging when multiple customers attempt to purchase the last available item at the same time.

A simple stock quantity field may work for a small prototype, but production systems need reliable concurrency control.

For example, two checkout requests must not both successfully reserve the same final unit.

Database transactions and appropriately designed updates can help prevent overselling.

Some stores maintain an inventory table with available and reserved quantities. Others use an inventory movement ledger that records stock additions, sales, returns, and adjustments.

The correct design depends on the store’s scale and fulfillment requirements.

IMPORTANT CHECKOUT RULE

Creating an order and reserving its inventory should follow a coordinated transaction strategy. Otherwise, simultaneous purchases can create inconsistent stock records.

9. Keep Payments and Shipping in Separate Tables

Orders, payments, and shipments represent different business processes.

One order may have multiple payment attempts, refunds, or partial shipments.

Separate tables make these situations easier to represent.

A payments table might store the order identifier, payment provider reference, amount, currency, status, and timestamps.

Do not store raw payment-card details unless your architecture and compliance obligations specifically permit it. Most stores should use a qualified payment provider and retain only appropriate references.

A shipping table may contain tracking information, carrier details, shipping status, and delivery dates.

Customer addresses can be stored separately, while an order should retain a snapshot of the destination used for that purchase.

10. Add Indexes for Common Queries

Indexes help the database locate matching records efficiently.

An online store frequently searches orders by customer, order items by order, and products by category or availability.

Useful indexes may include:

CREATE INDEX idx_orders_customer
ON orders(customer_id);

CREATE INDEX idx_order_items_order
ON order_items(order_id);

CREATE INDEX idx_order_items_product
ON order_items(product_id);

Primary keys and unique constraints already create supporting indexes in PostgreSQL, so unnecessary duplicate indexes should be avoided.

Indexes improve many read operations but also consume storage and add overhead to writes. Create them according to actual query patterns rather than indexing every column.

11. Example: Retrieve a Customer’s Order History

A relational design makes it straightforward to retrieve information across connected tables.

SELECT
    o.order_id,
    o.created_at,
    o.order_status,
    o.order_total
FROM orders AS o
WHERE o.customer_id = 42
ORDER BY o.created_at DESC;

This query retrieves the order history for the customer with ID 42.

A separate query can join order_items with products to display the contents of a particular order.

For historical accuracy, production systems should display saved purchase-time values rather than relying exclusively on current product details.

12. Protect Customer and Transaction Data

Database security is essential for online stores.

Customer records may contain personal information, while order records contain sensitive transaction details.

Applications should use parameterized queries to reduce SQL injection risks.

Database accounts should have only the permissions required for their tasks.

Connections should be protected using appropriate encryption, and backups should be tested regularly.

Access to customer and payment-related data should be restricted and monitored.

Stores must also consider applicable privacy and data-retention requirements in the regions where they operate.

Common Database Design Mistakes

Storing multiple products in one order field: Use an order-items table instead.

Using floating-point numbers for money: Prefer fixed-precision decimal values or integer minor units.

Overwriting historical prices: Save the actual unit price charged in each order item.

Ignoring simultaneous checkouts: Use transactions and concurrency-safe inventory updates.

Deleting important historical records: Define appropriate retention and deletion rules.

Skipping database constraints: Use primary keys, foreign keys, uniqueness rules, and checks to protect data integrity.

Frequently Asked Questions

Which database is suitable for an online store?

Relational databases such as PostgreSQL and MySQL are common choices because they support structured relationships, transactions, and data-integrity constraints.

Why do orders need a separate order-items

TC

Taryn Crooks

Senior Databaselab Specialist

Senior Agricultural Researcher & Livestock Husbandry Specialist at Databaselab. Dedicated to advancing sustainable flock management, genetic conservation, and precision ovine nutrition.

Leave a Comment