02 / 19 · Models and Integrity
From a domain to a data model
Turn an order and its catalog items into entities and relationships. Use cardinality and identity rules to decide what the database must reject.
On this page 4
A checkout asks for two units of tea at 350 cents each. The catalog now has a 50 g pack and a 100 g pack. Both display the name “Tea”. A receipt showing two units of tea for 700 cents tells us how much was paid. It leaves the warehouse with two possible items to pick.
Decide what has an identity#
In the first SQL example, one row represents one position of one order. Its product label works for reading the example. To use the same data for fulfilment, we need to distinguish the items that can be sold. In this shop, a catalog item represents one sellable pack type. The 50 g and 100 g packs are two items. Two individual 50 g packs on a shelf are two units of the same item. A shop that tracks individual units would need another identity at that level. The decision follows what the system has to distinguish. For trade items identified by a GTIN, GS1 makes a related distinction: a change to legally required net content declared on the pack requires a new GTIN. GS1, §2.3
An entity is a distinguishable object we want to represent. Order 101 and the 50 g pack type are instances of two entity types, Order and Catalog item. An attribute records a property, such as the display name of an item. A relationship associates entities, such as an order containing a line. A conceptual model records the objects, attributes and relationships relevant to the domain before we choose their representation in tables. Chen, 1976, §§2.1–2.2
A line records the chosen item, the quantity and the unit price agreed for that line. The price belongs to the line because another sale of the same item can have a different price. If the shop uses the catalog’s current price to reconstruct old orders, a price change from 350 to 400 cents turns the amount for those two units from 700 into 800 cents. We keep the agreed price with the position that it describes.
Count links in both directions#
Each line belongs to exactly one order and specifies exactly one catalog item. An order can contain several lines. A draft can contain zero. A catalog item can appear in many lines or have no sales yet. Cardinality constrains how many entities can be linked to an entity at the other end. Here we record both the minimum and the maximum. The label 0..* permits zero and puts no finite upper bound on the count. Chen, 1976, §3.1
Cardinality at both ends of each relationship
The association between orders and catalog items is many-to-many. The line records a particular occurrence of the association. Order 106 may contain one 50 g pack at 350 cents and another at 300 cents as two separate positions. Both positions link the same order and the same item. A record keyed only by the order and product pair would accept at most one of them. A separate line lets each occurrence keep its own quantity and price.
The minimum can depend on the state. The shop allows a draft with zero lines and requires at least one line at checkout. The diagram describes the links across all orders, including drafts. The extra rule concerns a state transition, and the two foreign keys in the example below express which parents a line can reference. Adding an order without lines leaves both foreign-key constraints satisfied.
Choose keys and keep the other rules#
A candidate key is a set of attributes with two properties. Its values are present and identify one record in every allowed state. Removing any attribute loses that guarantee. Here a line number is assigned within an order. Lines 101/1 and 106/1 share the line number, while lines 101/1 and 101/2 share the order number. The pair (order_id, line_no) is a candidate key because the shop forbids giving two lines the same number in one order. Four distinct pairs in a sample illustrate the rule. They cannot establish it. The primary key is the candidate key selected as the main identifier. Chen, 1976, §2.3.1 PostgreSQL 18, §5.5.4
For items, assume the shop issues a catalog code and requires all current codes to be distinct. The code is a natural key for this database because it already identifies the item in the shop’s catalog workflow. The display name cannot serve that role. Catalog staff can also correct a mistyped code. If all lines refer to that code, the correction must preserve their references, for example by cascading the update to the referencing rows. A surrogate key is introduced for the database’s own use. Here we assign product_id = 7 to the 50 g pack and leave that value fixed as catalog staff correct TEA50 to TEA-50. Chen, 1976, §2.3.1 PostgreSQL 18, §5.5.5
Correcting the code preserves the item references
A primary key on product_id still permits two records with different IDs and the same catalog code. The model forbids that combination, so we keep a separate uniqueness constraint on the code. This rule checks the current catalog. If an importer must resolve old codes after corrections, it needs another record of those assignments. A fixed internal identifier helps existing references. It gives the importer no way to infer which item an absent old code meant.
Put the rules into a schema#
Use a fresh PostgreSQL session for this example. Keep an order header, the catalog and a table of positions. The line’s primary key gives each position its identity. REFERENCES requires a matching parent row. The target primary key makes that match unique, and a required reference also needs a non-null value. A column included in the primary key already has that property, as order_id does in order_lines. PostgreSQL 18, §§5.5.2–5.5.5
CREATE TEMP TABLE orders (
order_id integer PRIMARY KEY
);
CREATE TEMP TABLE catalog_items (
product_id integer PRIMARY KEY,
catalog_code text NOT NULL UNIQUE,
display_name text NOT NULL
);
CREATE TEMP TABLE order_lines (
order_id integer REFERENCES orders (order_id),
line_no integer CHECK (line_no > 0),
product_id integer NOT NULL REFERENCES catalog_items (product_id),
quantity integer NOT NULL CHECK (quantity > 0),
unit_price_cents integer NOT NULL CHECK (unit_price_cents >= 0),
PRIMARY KEY (order_id, line_no)
);
INSERT INTO orders VALUES (101), (105), (106);
INSERT INTO catalog_items VALUES
(7, 'TEA50', 'Tea'),
(8, 'TEA-100', 'Tea'),
(9, 'COFFEE', 'Coffee');
INSERT INTO order_lines VALUES
(101, 1, 7, 2, 350),
(101, 2, 9, 1, 600),
(106, 1, 7, 1, 350),
(106, 2, 7, 1, 300);
The two rows named Tea coexist because their catalog codes differ. Order 105 has no lines, which is valid for a draft. The two positions of order 106 reference the same item with different line numbers. The model accepts all three cases. A foreign key points from one child to its parent. It permits a parent without children and it permits multiple children to point to that parent.
Correct the code and join the positions of order 106 to the catalog. The JOIN pairs each position with the catalog row whose product_id equals the position’s reference.
UPDATE catalog_items SET catalog_code = 'TEA-50' WHERE product_id = 7;
SELECT l.line_no, c.catalog_code,
l.quantity * l.unit_price_cents AS amount_cents
FROM order_lines AS l
JOIN catalog_items AS c ON c.product_id = l.product_id
WHERE l.order_id = 106
ORDER BY l.line_no;
| line_no | catalog_code | amount_cents |
|---|---|---|
| 1 | TEA-50 | 350 |
| 2 | TEA-50 | 300 |
The code comes from the current catalog row. The amounts still come from the prices recorded on the two lines. The same join would be insufficient to reconstruct the label printed on an old receipt after a catalog rename. If the original label matters, the data model must represent that historical value.
To see what the database rejects, submit each statement separately after the setup. Each insertion violates a different constraint.
INSERT INTO order_lines VALUES (106, 1, 7, 1, 350);
INSERT INTO order_lines VALUES (106, 3, 99, 1, 350);
INSERT INTO catalog_items VALUES (10, 'TEA-50', 'Tea');
The first tries to reuse the pair (106, 1), which identifies an existing position. The second has a free line number but refers to catalog item 99, which is absent. The third supplies a fresh ID and a code already in use. The database rejects each insertion at the corresponding constraint. It would accept (106, 3, 8, 1, 350) even if a checkout meant to select the 50 g pack. The foreign key can confirm that item 8 exists. It cannot establish which pack the customer chose.
Next#
The design gives us three tables with precise row meanings and declared constraints. The next step is to describe their contents as relations and use relational operations to recover the facts spread across them. The relational model and algebra develops those operations.
References#
- Peter P. Chen. The Entity-Relationship Model—Toward a Unified View of Data. ACM Transactions on Database Systems, 1(1), 9–36, 1976. §§2.1–2.3 define entities, relationships, attributes and identifiers. §3.1 develops entity–relationship diagrams and relationship mappings. Paper
- PostgreSQL Global Development Group. PostgreSQL 18 documentation. §§5.5.1–5.5.5 specify check, not-null, unique, primary-key and foreign-key constraints and describe updates to referenced keys. Constraints
- GS1. GTIN Management Standard. Release 1.1, 2023. §2.3 specifies when a change in declared net content requires a new GTIN. Standard