Relational databases: collection tree

Relational databases

Relational databases

IntroductionAbout 14 minutes AI-generated

A relational database keeps an application's facts in tables and lets it ask questions across them. A shop can record customers, orders and products separately, then ask which orders Mina placed, what each contains and what she still owes. The same stored facts answer several questions.

The database also manages changes to those facts. Two customers may try to buy the last mug at once. A purchase may fail halfway through. A server may crash after accepting an order but before replying. Tables give those problems a place to be expressed; constraints and transactions provide tools for handling them. Choosing the rules and the work that belongs together remains part of designing the application.

Every example follows a small shop selling tea and tea things. Mina Shah buys one blue mug and two packets of green tea in order 103. We will first read the records after that purchase, then consider what must happen to accept it safely. The shop data is invented; it implies no measured timings or particular physical storage layout.

Tables and rows

A table is a named collection of rows. Each row records one fact of a particular kind, using named columns. In customers, a row records a customer and the columns give their identifier and name. In orders, a row records an order, including which customer placed it.

One purchase, four kinds of fact
Figure 1. The order, its lines, its customer and its products remain separate facts.
Figure as text

Order 103 names customer Mina. Its two lines name the blue mug and green tea. The references connect four kinds of record without copying the customer name into each order.

The value 1 in order 103's customer_id refers to Mina's customer row. It is a reference, not a copy of her name. Order 101 points to her too. If her name changes, both orders still identify the same customer.

A key identifies a row. The customer identifier is a key of customers; the order identifier is a key of orders. An order line needs two columns together: order_id and line_no. Line 1 of order 103 is different from line 1 of order 101. A key need not be a number, and its purpose is identity, not counting rows.

Row position is no substitute. The database can return rows in a different order, and a name can change or be shared by two people. When the order of a result matters, the question must ask for it explicitly.

The tables, their columns, value types and rules form the database's schema. A relation is the mathematical idea behind a table; “relational” does not merely mean that tables have links. SQL tables are its practical form, with features such as duplicate query rows and missing values that we will meet below.

Choosing what one row should mean is the first design decision. A product's current price and the price agreed on an earlier order line are different facts, even if both happen to say 20.00 today. Relational data modelling develops those choices through changes to this shop.

Values and missing data

The characters on a page can hide differences in meaning. A quantity of 2 counts packets; 4.50 is an amount per packet; P3 identifies a product. Order 103's placed_at records a moment, 20 October 2026 at 10:15 UTC. The schema gives each column a data type, defining the values it can hold and the operations available on them.

Zero is a value. A stock of zero means there are no units available. A missing value needs a different interpretation: a nullable dispatch time might mean “not dispatched yet”. SQL calls a missing value NULL. It does not behave like a zero or an empty string. The shop must decide which meanings are allowed before choosing a representation; Values, missing data and equality follows the consequences.

Order 103 has no payment row. That is an absence from another table, not a payment with a NULL amount. It remains pending, with 29.00 due. Keeping the distinction will matter when we ask for unpaid orders.

Constraints

A constraint is a rule the database enforces on the data it accepts. A primary key makes the chosen identity unique and non-missing. A foreign key requires a reference to name an existing row. A check constraint can require stock to stay at or above zero.

The rule follows the data, whichever caller changes it
Attempted changeResult
Change P7's price from 20.00 to 22.00Accepted: a non-negative price
Add another order with order_id = 103Refused: that identity already exists
Add an order for customer 99Refused: there is no customer 99
Set P7's stock to −1Refused: stock must not be negative

The price change is a separate experiment, not a change to our starting records. Notice what the constraints do not say: an order must have all its intended lines, and accepting it must allocate enough stock. Those rules involve several steps. Constraints and data integrity explains which rules a schema can enforce directly and which need a transaction protocol.

Asking questions of the same facts

SQL, pronounced “S-Q-L” or “sequel”, is the language used to define, read and change these tables. A SELECT asks for a result. This one asks for Mina's orders:

SELECT order_id, status
FROM orders
WHERE customer_id = 1
ORDER BY order_id;

FROM orders names the input. WHERE keeps rows whose customer identifier is 1. SELECT names the columns to return, and ORDER BY puts the answer in order of identifier. The result has two rows: 101, paid; and 103, pending. Reading does not remove or change either order.

A join pairs rows from tables according to a condition. For each line of order 103, the next query finds the product whose identifier matches the line's product_id. Its mug line matches P7, and its tea line matches P3, producing one result row for each line.

SELECT i.order_id, i.line_no, p.name,
       i.quantity, i.unit_price
FROM order_items AS i
JOIN products AS p ON p.product_id = i.product_id
WHERE i.order_id = 103
ORDER BY i.line_no;
Two matches, two result rows
Figure 2. The original rows stay in place. Matching creates result rows.
Figure as text

Line one matches product P7, the blue mug; line two matches P3, green tea. Each match adds one named order line to the result. Product names come from products; quantities and agreed prices come from the order lines.

The short names i and p identify the two input tables. i.unit_price comes from the order line; p.name comes from the product. The result has its own columns and its own row meaning: one line together with its product name.

Order 103 appears twice because it has two lines. There are still only three stored orders in the shop. Counting these result rows would count lines, not orders. Asking how much is still due also requires bringing in payments, which can themselves have several rows per order. Joins and the meaning of a result row builds that report without counting the same money twice.

The SQL describes the answer, not a prescribed physical search. Pairing by product identifier does not require the server to try every possible pair. How it finds the rows is a separate question, to which we will return.

Making a purchase

Go back to just before order 103. P7 has one mug in stock, P3 has twelve packets of tea, and order 103 does not yet exist. Mina wants the mug and two teas. Accepting her purchase must record the order and its two lines, and reduce both stock counts.

INSERT adds rows. UPDATE changes values in existing rows. DELETE removes rows. If each change takes effect separately, a failure can leave reduced stock without an order, or an order without its lines.

A transaction groups changes into one all-or-nothing operation. BEGIN starts it, COMMIT accepts its changes together, and ROLLBACK abandons them. This all-or-nothing property is called atomicity. If the purchase fails after subtracting the mug, rolling back restores its stock to 1 and removes any order or line rows added by that attempt. The tea stock remains 12.

The whole purchase, or none of it
Figure 3. The commit boundary belongs to the complete purchase, not each stock change.
Figure as text

The mug allocation, tea allocation and order are provisional together. Commit makes all three available to a new reader. Rollback after the mug allocation leaves the original stock and no order.

During the transaction, its own commands can use the changes it has made. Other ordinary PostgreSQL readers cannot see those uncommitted changes. A reader sees a committed state rather than an order halfway through being built; another writer may have to wait.

The successful purchase ends with P7 stock 0, P3 stock 10 and P9 stock 4. Order 103 has two lines worth 29.00 in total. Nothing in that transaction recorded a payment, so its status stays pending. A payment is a further business event.

Conditions on a change

Subtracting a mug is safe only if one is available. The condition belongs in the change itself:

UPDATE products
SET stock = stock - 1
WHERE product_id = 'P7' AND stock >= 1;

This command finds P7, requires its stock to be at least 1 and subtracts 1 from that row's current stock. The database reports how many rows changed. One means the mug was allocated by this operation. Zero means its precondition failed: no matching product with enough stock was changed.

Zero changed rows is not a database error. The caller must recognise it as a failed purchase and roll back the transaction, including any earlier changes. It must check the tea change too, with a required quantity of 2. Updates, upserts and bulk imports develops guarded writes and their results.

Two buyers and one mug

Now let Tariq try to buy the same last mug in purchase 104. Both requests read stock 1. Suppose each calculates the new stock in application code, then writes stock = 0. Putting each purchase inside a transaction does not repair that decision.

Two buyers, one mug
Figure 4. A selected PostgreSQL Read Committed schedule. Zero changed rows must make the caller abandon the purchase.
Figure as text

Mina and Tariq both read one mug. Mina updates first. Tariq waits. Writing the earlier calculated zero can accept both purchases; a guarded subtraction rechecks stock zero and changes no row, so Tariq rolls back.

The mistaken version can keep both purchases and leave stock at zero. Neither transaction was partial, and the non-negative stock constraint was never broken. The problem was deciding from an earlier read and later writing the calculated value.

With the guarded subtraction, Mina changes P7 while Tariq waits. At PostgreSQL's Read Committed isolation level, Tariq's update checks its condition again against Mina's committed row. Stock is zero, so it changes no row. Tariq's caller then rolls back purchase 104.

Isolation describes how transactions interact while they run together. This example assumes Mina updates first and uses PostgreSQL's Read Committed level. Another system or level may abort a competing transaction and require a retry. A rule involving several rows can need a different protocol altogether. BEGIN chooses a boundary, but does not by itself make every concurrent decision sound. Transactions and isolation starts from the rule that must survive.

SQL in an application

Mina's browser asks the shop application to place an order. The application uses a database connection, a conversation with the database server, to send the SQL and receive results. The server manages the shared tables; it does not know that a web page is waiting unless the application tells it.

Figure 5 · One request crosses the application boundary
Mina's browserPurchase request ↓Shop applicationOne connection: BEGIN → changes → COMMIT ↓Database serverRows changed, results and errors ↑

The application holds the purchase's database conversation together and decides what to tell Mina.

The commands of one transaction must use the same connection. A connection pool lends connections to requests, but taking a different one for each command would split the conversation. The application must supply values, inspect the result of each change and end the transaction after success or failure.

Values should travel separately from the SQL structure. In PostgreSQL a parameterised version of Mina's lookup can use WHERE customer_id = $1, with the value 1 supplied through the driver. The parameter is data; it is not pasted into the command as SQL. The driver is the library that manages this communication for the application.

An object-relational mapper, or ORM, lets application code work through objects and methods while it constructs SQL. It still sends commands, returns result rows and uses connections. Loading a customer's orders in a loop can still send one query per customer. SQL at the application boundary follows these responsibilities through drivers, pools and ORMs.

The transaction covers its database changes. If the application also charges an external payment provider or sends an email, ROLLBACK cannot uncharge the card or unsend the email. Those actions need their own failure and recovery design. Outboxes and database-backed jobs develops a way to record the intention in the transaction and carry it out afterwards.

The work behind a query

Mina's order lookup returns two rows. That says how big the answer is, not how much work produced it. Without a suitable shortcut, the database can read every order and test its customer identifier, discarding all the others. This is a table scan.

An index is a maintained structure that helps find rows by their values. An index on orders.customer_id can put Mina's entries together and lead to her orders, avoiding a test of every unrelated order.

The same answer by two routes
Figure 6. A real planner may prefer a scan for a table this small.
Figure as text

A table scan visits orders 101, 102 and 103, retaining Mina’s 101 and 103. A customer index directs the lookup to those two matches. This illustrates logical row access, not measured page reads.

On a large table, returning two orders by scanning millions of unrelated ones is expensive. The index can reduce that search, but each new order must also add an index entry, and relevant changes must maintain it. More indexes mean more stored data and more work on writes.

The database's planner chooses the work it expects will be cheapest. A query plan records that choice: which tables to scan, which indexes to use, and how to join or sort their rows. For the shop's three-order table, reading everything can be cheaper than using an index. Having an index does not compel the planner to use it.

When a query is slow, inspect the work as well as its answer. Query execution and performance follows rows through a plan; Indexes and access paths develops indexes for the questions an application actually asks.

Keeping a confirmed change

Atomicity prevents a partial purchase. Durability means an accepted commit survives a crash. The server cannot keep that promise if the only copy of the purchase is in memory, because a power cut empties memory.

PostgreSQL records changes in a recovery log on durable storage. With normal durable commit settings, it waits until the log includes a durable commit record before replying successfully. The table files can be written later: after a crash, the log can restore changes they are missing. The storage must keep what it reports as safely written.

The application receiving that reply is a later event. A crash before the commit becomes durable can leave no accepted purchase after recovery. A crash just after the durable commit can leave the complete purchase, even if the server never manages to send its reply.

Commit and reply are separate
Figure 7. Normal local durability and surviving reliable storage are assumed.
Figure as text

A purchase is prepared in memory. A crash before its durable commit leaves no accepted purchase. A crash after the durable commit preserves the whole purchase even when the caller did not receive the reply.

The application can see a dropped connection in either case. A missing reply cannot tell it whether the purchase exists. Retrying as a new order could make a second purchase. Retries and uncertain commit outcomes develops how to recover one logical request.

Crash recovery uses the files and log that survived. It cannot rescue a lost disk or decide that a successful deletion was a mistake. A replica supplies another live copy, but it also copies that deletion. A backup preserves a recoverable earlier copy; retained logs can help restore it to a later chosen point. Each protects against a different loss.

Storage and durability connects the rows to memory, files and the log. Replicas, lag and read routing and Backup, restore and reconciliation follow the copies and their limits.

Operating a changing database

Suppose Mina's next purchase takes several seconds. Its SQL might be fast once it runs. The delay can occur before the application gets a connection, while the transaction waits for another writer, or while a query does unnecessary work.

Follow the request to the place where it waits
Where the time goesWhat to investigate
Waiting for a connectionHow many requests are admitted and how long they keep connections
Waiting behind another transactionWho holds the row and why that transaction is still open
Running the queryThe plan, rows visited and data moved to produce the answer

Making the query faster will not fix an exhausted connection pool. Adding connections can make a busy server compete for the same resources. Diagnosing a database incident starts with evidence that separates these cases.

The schema changes too. Adding a required column while old application code is still writing is a deployment problem as well as a table definition. The application needs permission to do its job; an account that can read orders need not be allowed to erase them. Backups need a tested restore, and the server needs enough storage for its data and ongoing work. Live schema changes and backfills, Database access and least privilege and Connections, overload and capacity take those decisions further.

More than one machine

Relational tables and SQL do not require all the data to live on one server. There are two different reasons to add machines: keep another copy of the same facts, or divide the facts so different machines do different work.

A replica is a copy. A shard is a portion of the data. Two replicas can both hold P7 and P3. With sharding, one machine might hold the mug's stock and another the tea's. Purchase 103 then needs changes on both machines.

Copying data and dividing data
Figure 8. These are invented placements, not a replication or placement protocol.
Figure as text

Replication puts copies of the same records in two places. Sharding places different portions in each place. Each shard can itself be replicated.

Dividing the data can spread storage and work, but the purchase still needs its mug and tea changes to succeed together. When they live in different portions, that decision requires communication and coordination across machines. A machine or network failure can leave the participants unable to finish immediately.

A distributed SQL database carries these responsibilities behind a relational interface. A system assembled by an application may leave more of them to its callers. Either way, adding servers does not create another last mug: every purchase of P7 still competes over that fact. A rule covering the whole shop can still need coordination across the whole shop. Sharding and distributed SQL derives the costs from what each request must touch.

PostgreSQL and CockroachDB

The concepts so far apply to several database systems. PostgreSQL and CockroachDB provide two implementation routes through this collection. They accept familiar SQL, but that resemblance does not make every type, concurrent outcome or operating procedure identical.

Inside PostgreSQL

A PostgreSQL connection is handled by a server process, working with shared memory and the server's database files. Tables and indexes are managed there; replicas can copy the server's changes to other machines. The guarded-stock example used its Read Committed behaviour. If that is the system your application uses, Inside PostgreSQL follows a request into its processes, pages and maintenance work.

Inside CockroachDB

A CockroachDB connection reaches a node in a cluster. The system turns table and index operations into work on portions of ordered data called ranges, routes that work to their owners and keeps replicas of the ranges. Transactions can touch several ranges. If distribution, placement or transaction retries affect your application, Inside CockroachDB follows those boundaries.

The practical choice starts with the application and its required deployment: where requests and data need to be, which failures must be survived, and who will operate it. Familiar SQL can make a move easier, but the purchase and its failure handling still need checking on the chosen system.

Choosing a next question

A relational system is a useful fit when the application has related facts, several questions over the same records and rules that must hold across different writers. The shop benefits because customer identity, agreed order prices, available stock and payments stay meaningful as the questions change.

That comes with work: deciding the schema, evolving it while applications run, choosing safe transaction protocols and operating durable copies. SQL does not make a poor row definition accurate, or an unsound concurrent decision safe.

Choose the next article from the task in front of you. For a new schema, start with Relational data modelling. For a report that counts too much, follow Joins and the meaning of a result row. For a purchase that must survive competing callers, use Transactions and isolation. For a slow request, start at Diagnosing a database incident; for lost or unwanted data, at Backup, restore and reconciliation.

You can enter at the question you already have. The earlier explanations are there when that question needs them.

Sources and further reading

Checked against the primary documentation on 25 October 2026. The shop and the example schedules are illustrative. Displayed query results, rejected changes, rollback and sequential guarded updates were checked in PGlite 0.5.8, a WebAssembly build of PostgreSQL 18.3. The concurrent-stock example follows the documented PostgreSQL Read Committed contract; its waiting and interleaving are illustrative. No timings, crash drill or distributed execution are claimed.