Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 30 min · revision 3

Worked Example: An Order Management Schema

Walk the shop requirements from ER diagram to running PostgreSQL tables: settle the model, choose the keys, write the DDL, load sample data and read it back.

Contentsand lesson path

What you will learn

  • Derive entities, attributes, relationships and cardinalities from written requirements and draw them as an ER diagram.
  • Map an ER model to tables with primary, foreign, natural and surrogate keys, including junction tables for many-to-many relationships.

Prerequisites: SQL Fundamentals

01. The brief

You are handed the shop requirements you modelled in the first lesson: customers with email, name and optional phone; saved delivery addresses; orders with a readable reference, a placed-at time and one shipping address; order lines with product, quantity and the unit price charged; products with SKU, name and price. Your brief: turn that diagram into a PostgreSQL schema that loads sample data and answers "what is on this order".

The work runs in four moves — settle the model, choose the keys, write the DDL, prove it with data. The mapping rules themselves are few enough to hold in your head: each entity becomes a table, each attribute a column, each one-to-many a reference column on the many side, and each many-to-many pairing a junction table. Everything in this example is one of those four moves. Collections are deliberately left out of the core and become your stretch task at the end, because the order path already exercises every rule you need.

02. Step 1: settle the model

The entities are customers, addresses, orders, order_lines and products. Three decisions in the diagram deserve their reasoning written down, because someone will ask:

  • Addresses are their own entity, not columns on customers, because a customer keeps several and an order names exactly one of them. Two one-to-many relationships share the table: customer to addresses, and addresses to orders through the order's shipping reference.
  • Order lines are their own entity, not a list inside the order, because each line carries its own facts: which product, how many, at what price.
  • The unit price lives on the line, not on the product. The catalogue price and the price charged are different facts; one changes with the market, the other must never change after the sale. This single placement is what keeps old invoices honest.

One relationship was considered and rejected, which is worth recording too: an order could have pointed at a customer only, with the address copied into the order as columns. The reference wins here because the order should name which saved address the customer chose, but it brings a duty the price decision already taught: the address an order shipped to is a historical fact, exactly like the unit price charged.

If a customer could edit a saved address in place, every past order pointing at it would silently move with it, and packing slips, invoices and disputes would show an address the parcel never went to. So a saved address is treated as immutable once an order uses it: an edit inserts a new addresses row, and the old row stays, merely hidden from the customer's list (for example by an archived_at column). The foreign key, which uses the default ON DELETE NO ACTION, already refuses to delete an address an order still uses.

The other sound design snapshots the address columns onto the order at checkout; what is never sound is reading a historical fact from a shared row that can still be edited — the same mistake as reading the charged price from products. Write these small decisions down next to the diagram; six months later, the reasoning matters more than the shape.

03. Step 2: choose the keys

Apply the safe default from the keys lesson: a surrogate bigint GENERATED ALWAYS AS IDENTITY as primary key on customers, addresses, products and orders, with the business identifiers kept unique beside it — UNIQUE on email, on sku and on the order reference. Email addresses and SKU formats change; identity keys and their references do not.

order_lines is the one table that takes a composite primary key: (order_id, line_no) identifies a line, and an identity column would add nothing that the pair does not already guarantee. Quantities get a CHECK so a line with a zero or negative quantity is refused, and money is numeric(10,2) for the reason the first SQL lesson gave: floating-point types cannot hold exact cents.

One requirement needs a second composite key. The brief says an order ships to one of that customer's addresses. Two separate foreign keys, orders.customer_id to customers and orders.shipping_address_id to addresses, each check only that the row they name exists: an order for Ana could still name Liu's flat in Paris, and the database would accept it. To make "the customer's own address" a rule the database enforces, the order must point at the pair (address, owner). A foreign key may only reference columns that form a primary key or carry a UNIQUE constraint, so addresses gets UNIQUE (id, customer_id). That looks redundant, since id alone is already unique, but it is what lets orders declare FOREIGN KEY (shipping_address_id, customer_id) REFERENCES addresses (id, customer_id). The order's own customer_id is now part of the address reference, so the two columns cannot disagree.

04. Step 3: write the DDL

Start the rdm-lab container from the keys lesson if it is not running, connect with docker exec -it rdm-lab psql -U postgres -d store, and give the example its own database so it cannot collide with earlier work:

SQL · store=#
CREATE DATABASE ordersdb;
\c ordersdb
Expected output
CREATE DATABASE
You are now connected to database "ordersdb" as user "postgres".
SQL · ordersdb=#
CREATE TABLE customers (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email     text NOT NULL UNIQUE,
  full_name text NOT NULL,
  phone     text
);

CREATE TABLE addresses (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id   bigint NOT NULL REFERENCES customers(id),
  line1         text NOT NULL,
  city          text NOT NULL,
  country_code  char(2) NOT NULL,
  postcode      text NOT NULL,
  UNIQUE (id, customer_id)  -- target of the composite FK on orders
);

CREATE TABLE products (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku   text NOT NULL UNIQUE,
  name  text NOT NULL,
  price numeric(10,2) NOT NULL CHECK (price > 0)
);

CREATE TABLE orders (
  id                  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_number        text NOT NULL UNIQUE,
  customer_id         bigint NOT NULL REFERENCES customers(id),
  shipping_address_id bigint NOT NULL,
  placed_at           timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT orders_address_owner_fk
    FOREIGN KEY (shipping_address_id, customer_id)
    REFERENCES addresses (id, customer_id)
);

CREATE TABLE order_lines (
  order_id   bigint NOT NULL REFERENCES orders(id),
  line_no    integer NOT NULL,
  product_id bigint NOT NULL REFERENCES products(id),
  quantity   integer NOT NULL CHECK (quantity > 0),
  unit_price numeric(10,2) NOT NULL,
  PRIMARY KEY (order_id, line_no)
);
Expected output
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
SQL · ordersdb=# (\d order_lines)
\d order_lines

                 Table "public.order_lines"
   Column   |     Type      | Collation | Nullable | Default 
------------+---------------+-----------+----------+---------
 order_id   | bigint        |           | not null | 
 line_no    | integer       |           | not null | 
 product_id | bigint        |           | not null | 
 quantity   | integer       |           | not null | 
 unit_price | numeric(10,2) |           | not null | 
Indexes:
    "order_lines_pkey" PRIMARY KEY, btree (order_id, line_no)
Check constraints:
    "order_lines_quantity_check" CHECK (quantity > 0)
Foreign-key constraints:
    "order_lines_order_id_fkey" FOREIGN KEY (order_id) REFERENCES orders(id)
    "order_lines_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id)

The block above shows the \d order_lines command followed by its output. That output is the model made visible: the composite primary key, the check on quantity, and one foreign key per relationship the diagram drew. Notice where each reference lives — customer_id on orders, shipping_address_id on orders, order_id on order_lines — always on the many side. On orders the address relationship is the composite orders_address_owner_fk, named explicitly so that its error message tells a support engineer which rule was broken.

05. Step 4: load data and read it back

Two customers, three addresses (two saved by Ana), three products, two orders, four lines. Liu's order pays 8.90 for a cable listed at 9.90 — a discount captured at purchase time:

SQL · ordersdb=#
INSERT INTO customers (email, full_name, phone) VALUES
  ('[email protected]', 'Ana Petrova', '+44 20 7000 1234'),
  ('[email protected]', 'Liu Chen', NULL);

INSERT INTO addresses (customer_id, line1, city, country_code, postcode) VALUES
  (1, '14 Market Street', 'Bristol', 'GB', 'BS1 1QA'),
  (1, '7 Harbour Road',   'Bristol', 'GB', 'BS1 4TD'),
  (2, '3 Rue de Rivoli',  'Paris',   'FR', '75001');

INSERT INTO products (sku, name, price) VALUES
  ('CBL-USBC-1M', 'USB-C cable 1m', 9.90),
  ('CBL-HDMI-2M', 'HDMI cable 2m', 12.50),
  ('PAD-STD',     'Desk mat',      18.00);

INSERT INTO orders (order_number, customer_id, shipping_address_id) VALUES
  ('ORD-2026-0142', 1, 2),
  ('ORD-2026-0143', 2, 3);

INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price) VALUES
  (1, 1, 1, 2,  9.90),
  (1, 2, 3, 1, 18.00),
  (2, 1, 2, 3, 11.25),
  (2, 2, 1, 1,  8.90);
Expected output
INSERT 0 2
INSERT 0 3
INSERT 0 3
INSERT 0 2
INSERT 0 4
SQL · ordersdb=#
SELECT o.order_number, c.email,
       count(l.line_no)                              AS lines,
       sum(l.quantity * l.unit_price)::numeric(10,2) AS total
  FROM orders o
  JOIN customers c   ON c.id = o.customer_id
  JOIN order_lines l ON l.order_id = o.id
 GROUP BY o.order_number, c.email
 ORDER BY o.order_number;
Expected output
 order_number  |      email      | lines | total 
---------------+-----------------+-------+-------
 ORD-2026-0142 | [email protected] |     2 | 37.80
 ORD-2026-0143 | [email protected] |     2 | 42.65
(2 rows)

The join technique is the one you practised in the joins lesson; what is new is why it works. Because lines reference orders and orders reference customers through enforced foreign keys, every row in that result is guaranteed to be about a real order, a real customer, real products. The schema, not discipline, makes the join safe.

Liu's line also shows the model earning its keep: his line records the 8.90 he paid in order_lines.unit_price, and a join to products can still show the 9.90 catalogue price — two facts, two columns, no conflict. A schema that stored only the catalogue price would have repriced his order the moment the price changed.

Now test the rule from Step 2 the way a bug would break it. Address 3 is Liu's; try to place an order for Ana (customer 1) that ships there, then the same order with her own first address:

SQL · ordersdb=#
-- Ana (customer 1) names Liu's address (3)
INSERT INTO orders (order_number, customer_id, shipping_address_id)
VALUES ('ORD-2026-0144', 1, 3);

-- the same order, shipping to one of Ana's own addresses (1)
INSERT INTO orders (order_number, customer_id, shipping_address_id)
VALUES ('ORD-2026-0144', 1, 1);

DELETE FROM orders WHERE order_number = 'ORD-2026-0144';
Expected output (long lines wrapped)
ERROR:  insert or update on table "orders" violates foreign key constraint
        "orders_address_owner_fk"
DETAIL:  Key (shipping_address_id, customer_id)=(3, 1) is not present in
         table "addresses".
INSERT 0 1
DELETE 1

psql prints each message on one line; it is wrapped here to fit. The DETAIL line reads like the rule itself: there is no address 3 owned by customer 1. With the original design, two single-column foreign keys, the same first INSERT returns INSERT 0 1 because address 3 and customer 1 both exist; the wrong parcel would only be noticed by a courier. The DELETE removes the test order, so the stretch tasks below start from the two orders above.

06. Mistakes to catch before they ship

07. Check your understanding

Practice check · 3 questions

Decisions in the order schema

Defend three choices the worked example made.

Q1. Two months from now the cable's catalogue price rises to 12.90. What keeps yesterday's invoice showing 8.90?
Q2. The example keys order_lines on (order_id, line_no). What would adding UNIQUE (order_id, product_id) change?
Q3. A draft of orders had customer_id REFERENCES customers(id) and shipping_address_id REFERENCES addresses(id), each on its own. Which change stops an order shipping to another customer's address?
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend the schema in your ordersdb database:

  1. Add collections and the junction table with its position attribute, using the DDL you ran in the keys lesson.
  2. Put two products in one collection and one of them in a second, then prove with a query that a pairing cannot repeat.
  3. Add a note column to order_lines that may be NULL for most lines — then think again: is a note a fact about a line, or could a customer attach several? If several, model it as its own table instead.

This is the same shape of work as the clinic practice: map the diagram, choose keys, write DDL, prove it with data.

09. Review prompt

Without looking back: why are addresses their own table rather than columns on customers? Which table in the example uses a composite primary key, and what are its columns? Where does the charged unit price live and what would go wrong otherwise? Why does addresses carry a UNIQUE (id, customer_id) that looks redundant, and which bad order does it let the database refuse? And on which side of a one-to-many does the reference column always sit?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check