Relational databases
Relational data modelling
A relational data model says what the database records and how those facts fit together. An order belongs to a customer. An order line records a quantity of one product at an agreed price. A payment contributes towards an order. Choosing the tables, keys and relationships gives each of those claims a place where it can be recorded, found and changed.
A design can store today’s rows and still be wrong. It may allow two current names for the same customer, require an order before a new product can exist, or mistake two lines containing the same product for a duplicate. The useful test is what happens when the shop changes its data: which fact changes, how many copies must change with it, and which associations survive.
The examples follow the small tea shop from the relational introduction. Mina Shah, customer 1, places order 103. It has one blue mug, P7, at 20.00 and two packets of green tea, P3, at 4.50 each: 29.00 in all. Each worked scenario starts independently from these invented shop facts, rather than continuing the previous change. Together they develop one design and test the choices that would change its meaning.
What one row represents
Start a table by completing the sentence “One row records…”. For orders, one row records an order placed by one customer at one time. For order_items, one row records a numbered line of that order. For payments, one row records one payment towards an order. In prose we call an order_items row an order line.
The distinction matters as soon as an order has several lines and several payments. Order 101 has green tea and a teapot, worth 39.50 together. Payment 501 pays 30.00 by card; payment 502 pays the remaining 9.50 by gift card. Pairing each line with each payment repeats both facts.
Figure as text
Order 101 has two lines and two payments. Joining both one-to-many relationships by order produces four pairings. Each payment is repeated, so summing the joined payment amounts would report £79 rather than £39.50.
The four combinations are valid answers to “Which lines and payments belong to order 101?” They are a poor home for the underlying facts. Every payment is repeated for every line, and summing those repeated amounts doubles what was paid. More lines would produce more copies. Storing only two combinations instead would imply an allocation the shop never made.
Keep the order, its lines and its payments at their own levels. Both child tables refer to the order. If the shop later allocates part of a payment to a particular line, that allocation is another fact, with an amount and references to both. It should be recorded explicitly. Sharing an order does not establish that relationship.
Keys and identity
A key identifies a row across every state the shop permits, including rows it has not seen yet. Mina’s name is unique in the sample. That does not make it a customer key: two customers can have the same name, and one customer can change their name. Customer 1 remains the same customer through either event.
Candidate keys and surrogate keys
A superkey is a set of columns that identifies a row uniquely. A candidate key is a minimal superkey: remove any column and it no longer has that guarantee. Minimal means that none of its columns is unnecessary; it does not mean the shortest key among all the candidates. Choose one candidate as the primary key.
A natural key has meaning outside the database, such as a catalogue code that the shop promises to keep unique. Check the promise, its scope and what happens when that value changes. A surrogate key is an identifier introduced to name the row, such as a generated customer number. It lets references keep pointing to the customer when editable attributes change.
Adding a surrogate does not remove other uniqueness rules. If the shop gives each order line a separate line_id, it must still prevent two lines with the same (order_id, line_no). Otherwise two different IDs can both claim to be line 1 of order 103. A primary key on the ID alone cannot catch that disagreement. Keep the pair unique as well.
Composite keys
Line number 1 identifies a line only within an order. Orders 101, 102 and 103 can all have a line 1. The composite key (order_id, line_no) supplies the missing scope: line 1 of order 103 is one particular line.
Using (order_id, product_id) instead makes a different promise. It allows each product only once per order. Suppose the shop permits a second mug line, perhaps with a separately agreed price. Lines 1 and 3 of order 103 can both name P7 under the numbered-line key. A unique order–product pair would reject the second occurrence, regardless of its line number.
| order_id | line_no | product_id |
|---|---|---|
| 103 | 1 | P7 |
| 103 | 3 | P7 |
(order_id, line_no)
- 103 / 1
- distinct
- 103 / 3
- distinct
(order_id, product_id)
- 103 / P7
- same pair
- 103 / P7
- duplicate pair
An extra line_id can name each row. It cannot choose the duplicate-product rule for the shop.
Line number 1 can appear on another order. Product P7 can appear on another line. Together, order_id and line_no identify this occurrence.
Both numbered lines can contain P7. The composite line key distinguishes the occurrences. A key on the order and product pair would forbid the second line.
Both rules can suit a shop. A cart that always merges identical products might want the unique order–product pair. A system that preserves distinct line occurrences needs a line key. Make that decision before choosing the key. Another identifier makes rows easier to reference; it does not decide which occurrences the business considers duplicates.
Relationships and cardinality
A relationship says which facts refer to which others. Its cardinality gives the allowed number on each side. Ask for both the minimum and the maximum. “A customer has many orders” leaves open whether a new customer may have none. “An order has one customer” leaves open whether that customer is required.
One-to-many and one-to-one relationships
For this shop, each order has exactly one customer, and each customer may have zero or many orders. Mina has two; Edda Berg, customer 3, has none. The reference therefore belongs in orders.customer_id. Repeating customer 1 on two orders records two different order–customer associations.
Customer 1 has orders 101 and 103; Edda has none. Order 103 has two lines and no payment. A foreign key cannot require a parent to have a child.
Each arrow points from a required foreign key to its target key. Every child names exactly one parent; a parent may have zero or many children.
The required foreign key on each order makes its customer mandatory and requires that customer to exist. It does not require every customer to have an order. The same distinction applies to order lines: each line has an order, but the line’s foreign key cannot require every order to have a line. If the shop allows empty drafts but requires at least one line before submission, that is a further rule about the order’s lifecycle.
To turn a reference into a one-to-one relationship, make the reference unique as well. For example, a product-detail table whose product_id is both its primary key and a foreign key permits at most one detail row per product. A product can still have no detail row. Requiring one on both sides needs an additional enforcement decision. Constraints develops how to make these rules hold when applications write concurrently.
Many-to-many relationships
An order can contain many products, and a product can appear in many orders. order_items represents that many-to-many relationship. Its rows do more than link IDs: each has a quantity, an agreed unit price and a line identity.
Quantity belongs to the line because neither the order alone nor the product alone tells you how many were bought. The agreed price belongs there for the same reason: P7 can be sold on different lines at different prices. A list of product IDs inside orders would leave those facts without a clear address. It would also make an individual product reference harder to check.
A linking table is not automatically keyed by its two foreign keys. A unique pair records membership, such as a product belonging to a tag. A line records an occurrence, which can repeat the same order–product pair. The shape of a many-to-many diagram does not settle that choice.
Relationships involving three things
Some facts need three references together. Suppose a supplier offers a product to a particular shop location. Knowing that the supplier sells the product, serves the location, and that the location stocks the product is not enough. The offer has to name all three.
The shop has recorded three offers: (S1, P7, North), (S1, P3, South) and (S2, P7, South). Replacing these with separate supplier–product, supplier–location and product–location pairs loses which three things were offered together.
Figure as text
S1–P7, S1–South and P7–South each occur in the original three offers, but S1 / P7 / South was never offered. Splitting an actual offer into three pair lists loses this distinction.
Joining those pairs invents (S1, P7, South). S1–P7 came from the North offer, S1–South from the P3 offer, and P7–South from S2’s offer. Every pair is real, but their combination was never offered. Keep offers(supplier_id, product_id, location_id) together, with any price or delivery terms that belong to that complete offer. Here one current offer per triple makes the triple its key. If offers can repeat over time, they need a further identity or time distinction; three columns alone would no longer identify one occurrence.
Functional dependencies
Keys tell us what identifies a whole row. A functional dependency says which columns determine another fact. Write customer_id → name and read it as “customer ID determines the customer’s current name”. Whenever two rows have the same customer ID, they must agree on that name.
This is a rule about every permitted state. It is not a pattern inferred from a few rows. The sample’s product names happen to be distinct, but that is no reason to declare name → product_id. The shop must be able to promise the distinction.
Consider a deliberately flattened table containing order, customer, product and line facts. Both lines of order 103 store customer 1’s current name, Mina Shah. Correcting it to Mina Patel on the mug line alone leaves Mina Shah on the tea line. Two rows now disagree about the current name of the same customer.
Figure as text
Two flattened order lines repeat customer 1’s name. Correcting only one to Mina Patel leaves inconsistent current names. A single customer record gives the current name one home, referenced by both lines.
| These columns determine… | …these facts |
|---|---|
order_id | The order’s customer_id, placed_at and status |
customer_id | The customer’s current name |
product_id | The product’s current name and catalogue price |
(order_id, line_no) | The line’s product, quantity and agreed unit price |
The first rule applies to all the lines of an order; the second applies across that customer’s orders too. The last requires the complete line key. Neither order_id nor product_id alone determines a line’s quantity.
Update, insertion and deletion anomalies
The name disagreement is an update anomaly: correcting one fact requires finding and changing several copies. Updating every copy in one transaction can make that particular correction consistent, but every writer must keep doing so.
The same design has an insertion anomaly. P9, the teapot, exists before anyone buys it. A table whose rows require an order and line number cannot record that product on its own. A fabricated order or an incomplete line is a symptom that the product needs an independent home.
There is also a deletion anomaly. In the starting data P9 appears only on order 101’s second line. If the flattened table is the only home for product facts, removing that last line also removes the only record of P9’s name and price. A product table lets the shop remove an association without accidentally removing the product.
Repeated values alone are not the problem. Customer 1 must appear on both orders to say who placed each. The anomaly is repeating the customer’s current name as though each order could decide it independently. Keep references where they express separate relationships; move the shared fact to the row its determinant identifies.
Normalisation
Normalisation uses dependencies to find and repair these kinds of redundancy. The normal forms name increasingly strong conditions on a table. They help explain why a repair works; they do not tell you which business facts to collect or require a separate table for every column.
The repair follows what determines each fact. Line facts stay with the complete line key, order facts with the order, and current customer facts with the customer. The normal forms distinguish the dependencies that make each separation useful.
| Problem | Fact to separate | Its home |
|---|---|---|
| Repeating slots | product_1, product_2, … | One order_items row per line |
| Partial dependency | order_id → placed_at | orders · key: order_id |
| Transitive dependency | order_id → customer_id → name | customers · key: customer_id |
The line key keeps quantity and agreed price together. The order key determines the order time; the customer key determines the current name.
Each repair gives a fact a home identified by its determinant. A line’s agreed price remains a line fact.
Repeating groups and first normal form
Columns named product_1 and product_2 give an order an arbitrary capacity of two lines. A third line needs a schema change, and finding every order containing P7 requires looking in every slot. An encoded field such as "P7,P3" removes the column limit by making the application interpret a list inside the value.
The conventional first normal form, or 1NF, uses a single value from the column’s domain at each row–column position, without repeating groups of fields. For the shop’s lines, separate rows give every occurrence its own key, quantity and product reference. The application can then change one line or ask for all lines containing P7 using the same structure.
This does not mean every structured value must be broken into the smallest imaginable pieces. Whether a product description is one document or several facts depends on what must be addressed, checked and changed independently. The values article develops that boundary. Order lines already have independent identities and relationships, so hiding them in one value works against their meaning.
Partial dependencies and second normal form
After making line rows, suppose every row still stores placed_at. The key is (order_id, line_no), but the timestamp needs only order_id. This is a partial dependency: an order fact is repeated on every line even though the line number contributes nothing to it.
Second normal form, or 2NF, excludes partial dependencies of non-key attributes on a candidate key. Here those are the attributes that appear in no candidate key. Move placed_at, customer_id and status into orders; leave each line’s quantity and agreed price in order_items.
Adding a line_id does not repair the original dependency. If (order_id, line_no) still identifies lines, it remains a candidate key, and the order timestamp still depends on just part of it. Even if a design drops that uniqueness rule, the repeated fact remains: a normal-form label based on the new key would not make the copies safe.
Transitive dependencies and third normal form
The order now has its own table, but putting the customer’s current name there repeats it across orders. Follow the chain: order_id → customer_id → name. The order determines which customer placed it; that customer determines the current name. This is a transitive dependency.
For these shop tables, the third normal form, or 3NF, repair is to separate that non-key fact: store the current name in customers and retain only customer_id on the order. The same reasoning puts the product’s current name and catalogue price in products. It does not move the line’s agreed price there, because that is a different fact.
Boyce–Codd normal form, or BCNF, asks a stronger question: for every non-trivial functional dependency, is its determinant a superkey? “Non-trivial” excludes dependencies that merely repeat columns already on the left, such as (order_id, line_no) → order_id. A current customer name in the orders table fails: customer_id determines the name but does not identify one order.
3NF has a more permissive definition for attributes that participate in candidate keys, so it and BCNF differ in some designs with overlapping keys. Formal key derivation, those cases and decomposition procedures belong in Normalisation and decomposition. For this design, the practical question is already visible: does a fact depend on something that identifies several rows, forcing every one of those rows to carry the same answer?
Decomposing tables safely
Splitting a table is a decomposition. A useful split has to preserve the original information. Reconnecting its parts must recover the original associations without losing any or inventing others. A split that has that guarantee is lossless.
Keeping every column somewhere is not enough. Mina’s order 101 was placed on 12 October 2026 at 09:30 UTC; order 103 on 20 October at 10:15 UTC. Both name customer 1. Suppose we split these facts into (order_id, customer_id) and (customer_id, placed_at). The second table retains both timestamps, but no longer says which order belongs to each.
Figure as text
Orders 101 and 103 share customer 1 but have different dates. Joining projections through the customer pairs each order with both dates, inventing two rows. Keeping order_id on each side restores exactly the original associations.
Rejoining on customer 1 pairs each order with both timestamps: four rows instead of the original two. Two associations have been invented. A safe split keeps order_id on both sides, using (order_id, placed_at) for the timestamps. Each order then matches only its own timestamp, reconstructing exactly the original rows. There is usually no reason to split these particular one-to-one order facts; they make a small example of the reconstruction test.
Separating customer names from orders passes the same test. An order holds one customer_id, and that key selects exactly one row in customers. Reconnecting them recovers the order and its customer’s current name without inventing a second customer for the order.
Preserving information is different from preserving dependencies. Suppose instead that we store (order_id, customer_id) in one table and (order_id, customer_name) in another. Both use the order key, so the split reconstructs order facts safely. Yet neither table by itself can check that every order for customer 1 uses the same current name. That check needs information from both.
A dependency-preserving decomposition lets the dependencies be enforced by rules on the individual resulting tables, without joining them to check the original rules. The customer table gives customer_id → name one clear home. Losslessness and dependency preservation answer different questions; a split may satisfy one and fail the other. Normalisation and decomposition develops formal tests and the cases where the stronger normal form trades against local enforcement.
Independent multivalued facts
Functional dependencies do not find every kind of repetition. Suppose P7 has the tags gift and ceramic, and can be bought from suppliers S1 and S2. These are independent lists: the tag does not say anything about which supplier supplies the mug.
If a table tries to record both lists together, it needs all four combinations. Leave one out and the absence appears to say something about that tag–supplier pair, even though the shop has no such rule.
| product | tag | supplier |
|---|---|---|
| P7 | gift | S1 |
| P7 | gift | S2 |
| P7 | ceramic | S1 |
| P7 | ceramic | S2 |
| product | tag |
|---|---|
| P7 | gift |
| P7 | ceramic |
| product | supplier |
|---|---|
| P7 | S1 |
| P7 | S2 |
Adding one supplier to the combined table requires a row for every tag. Separating the independent lists records the supplier once. Unlike an offer, no particular tag–supplier pairing is being asserted.
P7 has two tags and two suppliers. In this scenario every supplier is independent of every tag. The four combinations contain only four membership facts: two tags and two suppliers.
No single tag or supplier is determined by P7, so the functional dependency product_id → tag would be false. The problem is that the whole set of tags is independent of the whole set of suppliers for that product. Adding a third supplier to the combined table requires two new rows, one per tag. A new tag would require one row per supplier.
Give each membership its own table: product_tags(product_id, tag) and product_suppliers(product_id, supplier_id). Each pair is unique. Now adding a supplier changes one membership, regardless of how many tags the product has. This is the kind of redundancy that multivalued dependencies and fourth normal form, or 4NF, describe; a table can pass BCNF and still have it.
The independence is essential. The earlier supplier–product–location offers asserted particular three-way combinations. Splitting them invented an offer. Here every tag–supplier combination is deliberately permitted, so the two independent sets preserve the intended information. Similar-looking three-column tables can need opposite decisions because they record different facts.
Historical facts and derived data
Two equal values may express different facts. Two different values may be conflicting copies of one fact. Before removing a value as redundant, ask exactly what it means and when it is supposed to change.
Current price and agreed price
products.price is the shop’s current catalogue price. order_items.unit_price is the price agreed for one line. Raising P7’s catalogue price from 20.00 to 22.00 leaves the mug line at its agreed 20.00 and order 103’s total at 29.00. Repricing that line from the catalogue would incorrectly raise the old total to 31.00.
Figure as text
The catalogue mug price rises from £20 to £22. The existing order line retains its agreed £20 price, and order 103 still totals £29.
The agreed price depends on the line key, not on P7 alone. It may differ by purchase date, negotiation or discount. Replacing it with a lookup of the current product price would silently reprice old orders. The agreement deserves its own stored value even when it was initially copied from the catalogue.
A current customer name is different. In the earlier examples it explicitly meant the name the shop currently holds, so its copies must agree. An order-time recipient name or delivery address would be another historical fact, defined to preserve what was agreed for that order. Name it accordingly. Choosing effective dates, retaining versions and correcting historical records are developed in Data lifecycle.
Totals, caches and denormalisation
Order 103’s line values are 1 × 20.00 = 20.00 and 2 × 4.50 = 9.00. Under this article’s rule, their sum determines its total: 29.00. There are no taxes, shipping charges or other adjustments in this example.
A stored orders.total calculated from those same lines is a second representation of the same fact. Change a quantity without refreshing the total and the two answers disagree. Deliberately storing such a copy to reduce read work is denormalisation. The saving must be worth the extra write work and the risk of disagreement.
| Decision | For a copy of order 103’s line sum |
|---|---|
| Authority | The quantities and agreed prices in order_items define the answer. |
| Refresh rule | Every line insert, price or quantity change, and deletion must refresh the copy. |
| Acceptable staleness | A checkout amount may need to agree immediately. A reporting cache may tolerate a stated delay. |
| Rebuild route | Recalculate from the authoritative lines and detect any disagreement. |
| Useful saving | Measure the read work saved on the real workload against maintenance cost. |
Now suppose the shop gives Mina a 3.00 discount on the whole order, leaving the line prices unchanged. The lines still add up to 29.00, but Mina owes 26.00. The line rows cannot tell us that the shop granted a discount. Record the discount against the order, along with its reason. The amount due can then be calculated as the line sum minus the discount. The discount is a new fact to store; the calculated 26.00 is still a value we can work out from other records.
For the original order, start by calculating the total from its lines when it is needed. Before storing a copy, measure how much time that calculation takes in the queries the shop actually runs. A stored total may make those reads faster, but every change to a line must also update the total. If two requests edit the same order at once, both changes must be reflected in it.
Indexes explains how an index can help a query find the relevant rows. Transactions explains how to make related writes succeed or fail together and what can go wrong when requests overlap.
Modelling variations in the data
The same questions apply when facts do not fit a uniform list of attributes. What does one row mean? Which identity do several kinds of fact share? Which relationships must remain visible and checkable?
Shared attributes and subtypes
Tea has an origin; teaware has a capacity. One products table could hold both columns, with a product type and unused fields for the attributes that do not apply. That is often manageable for a few stable variations. It needs rules distinguishing an inapplicable value from an unknown applicable one.
Another design keeps common product facts together and puts specialised facts in subtype tables. Here P3’s invented origin is Japan and P7’s capacity is 300 ml.
| product_id | name |
|---|---|
| P3 | Green tea, 50 g |
| P7 | Blue mug |
| product_id | origin |
|---|---|
| P3 | Japan |
| product_id | capacity_ml |
|---|---|
| P7 | 300 |
P3 and P7 keep their common product identity. P3 has tea details, P7 teaware details. The shop must separately decide whether one product may have both, or neither.
Optional subtype rows keep tea-only and teaware-only attributes with the products they describe. These references alone do not decide whether the subtypes overlap or cover every product.
Each subtype’s primary key is also a reference to products, so a tea detail row describes the same product that order lines reference. Adding the subtype does not create a second product identity.
Decide whether the subtypes are disjoint or overlapping: may a product have both kinds of detail? Decide whether they are total or partial: must every product have one, or can some have neither? Two foreign keys do not answer those questions. Choose between one table and several from the applicability and rules of the attributes, then arrange their enforcement. A separate table is useful when it expresses a coherent specialised fact, rather than merely moving a few empty cells elsewhere.
Recursive relationships
A product category can refer to another category. A nullable parent_id referencing categories.category_id gives each category at most one parent; a root has none. The reference is recursive because both ends name rows of the same table.
One parent · parent_id
Several parents · edge table
A parent_id column holds at most one parent per category. An edge table can hold both Mugs → Teaware and Mugs → Gifts.
Arrows point to parents. Mugs has one parent in the tree and two in the graph. Both designs need a separate rule to forbid cycles.
One parent per category can represent a tree, provided the shop also forbids cycles and decides how roots work. A foreign key accepts a parent that exists; it does not stop Mugs pointing to Blue mugs while Blue mugs points back to Mugs. Even excluding a category from being its own parent catches only the shortest cycle.
If Mugs can belong under both Teaware and Gifts, a single parent column is too restrictive. Use separate edges such as category_edges(child_id, parent_id), with the pair unique. The result permits shared ancestry and still needs a no-cycle rule if the categories must form a directed acyclic graph. Choosing traversal and reparenting methods, and comparing paths, closure tables and other representations, belongs in Modelling hierarchies.
Tables, JSON and entity-attribute-value models
A product’s presentation may include a small, variable description: tasting notes for tea, care instructions for a mug, or a display arrangement that changes with the catalogue. A JSON document can keep that material together when it is read and edited as one coherent document. Relational columns and documents can coexist.
The trade changes when the hidden fields carry established business rules. Putting an order’s products and quantities inside JSON makes the product references and line identity less directly available to ordinary foreign keys and uniqueness constraints. Putting capacity inside JSON may be reasonable for optional descriptive content, but less attractive once the shop must require a positive capacity for every teaware product and compare it consistently across the catalogue. JSON can be queried and validated; choosing it changes where those checks must be expressed.
An entity-attribute-value model, or EAV, goes further by storing rows such as (P7, 'capacity_ml', '300') in a generic attribute table. New attribute names need no new column. But the value column now mixes meanings: 300 ml and a country name do not have the same type or rules. Preventing two capacities, distinguishing unknown from inapplicable, checking units and connecting values to other entities all require additional design.
Use that flexibility when the attributes themselves are data the application must manage, such as a user-defined catalogue, and accept the need for attribute definitions, types and validation. For stable shared facts, named columns or coherent subtype tables usually make the rules easier to see. For independent relationships such as order lines and suppliers, retain explicit keys and references.
Assessing a schema
A schema review needs examples that exercise its distinctions. The starting rows are useful, but so are facts that have no associated rows yet, repeated occurrences and changes that affect several uses. Walk the proposed shop model through the operations below.
| The shop needs to… | The model must allow… |
|---|---|
| Add Edda before she orders | One customers row, with no fabricated order. |
| List a product before it sells | One products row, with no fabricated line. |
| Put P7 on two separate lines | Two line numbers within the order, if the shop permits that; no accidental unique order–product restriction. |
| Take a card and gift-card payment | Two payments rows referencing the same order, without duplicating its lines. |
| Correct customer 1’s current name | One change in customers; existing orders still identify customer 1. |
| Raise P7’s catalogue price | One change in products.price; the agreed 20.00 on order 103 stays put. |
| Remove a line from an editable order | The association disappears; its product and customer remain independently represented. |
Then read the relationships back as sentences. Every order identifies exactly one customer. Each line identifies exactly one order and product. An order may have several payments. Ask which rules are merely intended and which are actually declared. Positive quantities, existing references and unique line numbers can be explicit constraints. At least one line on submission, no category cycles and complete subtype coverage need further enforcement. A diagram that says “one” does not implement the promise.
Finally, ask the questions the application must answer. Can it find Mina’s orders, distinguish repeated mug lines, show what was agreed before a price change, and find unpaid orders such as 103? To calculate what remains due, it must total lines and payments at the order level before combining them. Joining their raw rows first pairs every line with every payment, repeating the amounts. Detailed SQL belongs in Query results, but the relationships required for the answer must already exist.
A useful design lets a new fact arrive without inventing another one, lets a correction reach the fact’s authority, and lets an association disappear without taking unrelated facts with it. Keys and dependencies explain those properties. The change walkthrough tests whether the model has actually preserved them.