Skip to content
Draft — this lesson has not been reviewed yet. Its facts are sourced, but read it with a critical eye.

Relational databases

The salon platform from lesson 1.4 now takes payments, one row each. The owner’s dashboard shows today’s takings, kept as one number on one row so the screen need not add up every payment. It works.

Then the salon gets busy, and three things go wrong.

The first is slow. “Tolu’s day” lists one stylist’s appointments for a date. At a few hundred rows it is instant. At two million it hangs: to find Tolu’s twelve, the database reads every row.

The second is half-written. Ada pays a ₦5,000 deposit. The server inserts the payment row, then the process crashes before it marks the appointment paid and adds ₦5,000 to the takings. The money arrived. The appointment says unpaid. The takings are ₦5,000 short of the payments. Which one is the truth?

The third needs two people. At 10:00 the takings stand at ₦20,000. Ada pays ₦5,000 and Kemi pays ₦8,000 in the same second. Each request reads the takings, ₦20,000, adds its own payment, and writes the result back. Ada’s request writes ₦25,000. Kemi’s writes ₦28,000. The dashboard says ₦28,000. The salon took ₦33,000.

None of these is a bug in one line of code. A relational database answers each: find rows without reading them all, make writes happen together or not at all, and control what concurrent work sees of each other.

Terms used in this lesson:

  • A full table scan reads every row of a table to find the ones a query wants. An index is a separate structure, kept in step with the table, that finds rows by a column’s value instead.
  • A transaction is a group of reads and writes the database treats as one unit: it commits (all of it takes effect) or rolls back (none of it does).
  • Transactions are concurrent when they run at the same time on the same data. The isolation level says how much of each other’s work they may see.

A database makes two promises: find it fast, and keep it true. The index keeps the first. The transaction keeps the second: a group of writes happens all or nothing, survives a crash once committed, and runs as if it were alone, to the degree its isolation level says.

The third failure, step by step, and the one-line fix. Amounts are in naira for reading.

Kemi's paymentTakings rowAda's paymentKemi's paymentTakings rowAda's paymentRead, then write (lost update)28,000. Ada's 5,000 is lostOne statement: total = total + amountwaits for Ada to commitread total: 20,000read total: 20,000write 25,000, commitwrite 28,000, commitadd 5,000 (row now held by Ada)add 8,000commit: 25,000re-reads the new row, writes 33,000

Indexes: finding twelve rows in two million

Section titled “Indexes: finding twelve rows in two million”

Why read every row? Because nothing tells the database where Tolu’s rows are. The PostgreSQL manual: without an index, “the system would have to scan the entire test1 table, row by row, to find all matching entries.” With one, “it might only have to walk a few levels deep into a search tree.”

That tree is a B-tree, the index CREATE INDEX builds by default in PostgreSQL, because B-trees “fit the most common situations”. They “can handle equality and range queries on data that can be sorted” (=, <, <=, >=, >), and can return rows already in order. A primary key gets one for free: adding it “will automatically create a unique B-tree index”.

“Tolu’s day” filters on two columns: stylist_id = 7, and starts_at within one date. Which index? One on both, in that order:

CREATE INDEX appointment_stylist_day ON appointment (stylist_id, starts_at);

Why that order? A multicolumn B-tree is sorted by the first column, then by the second within it, like a phone book sorted by surname, then first name. The manual’s rule: equality on the leading columns, plus a range on the next column, limits the part of the index that is read. So (stylist_id, starts_at) goes straight to Tolu, then to that date. (starts_at, stylist_id) reads every stylist’s appointments that day and discards the others. Equality columns first, the range column last.

The costs, from the manual. Every write pays: the index must be kept “synchronized with the table. This adds overhead to data manipulation operations.” Building one blocks writes by default, “until the index build is finished”, unless you use CREATE INDEX CONCURRENTLY, which has caveats. And the planner uses an index only “when it thinks doing so would be more efficient than a sequential table scan”. EXPLAIN shows its choice.

Which do you build? The manual: “it is the task of the database programmer to foresee which indexes will be useful.” Index the queries you run; an unused index “should be removed”.

Back to Ada’s deposit. Three writes must agree: the payment, the appointment’s status and the takings. Make them one unit:

BEGIN;
INSERT INTO payment (appointment_id, amount_kobo) VALUES (42, 500000);
UPDATE appointment SET status = 'deposit_paid' WHERE id = 42;
UPDATE takings SET total_kobo = total_kobo + 500000 WHERE day = '2026-12-05';
COMMIT;

The PostgreSQL tutorial says what that buys: a transaction “bundles multiple steps into a single, all-or-nothing operation”, and “if an error occurs that prevents the transaction from completing, then none of the steps affect the database at all.” Crash after the insert, and the insert is gone too. ROLLBACK undoes every step so far.

One detail catches people. PostgreSQL “treats every SQL statement as being executed within a transaction”: without BEGIN, each statement commits on its own, so the three writes become three transactions.

These guarantees have a name. Härder and Reuter’s 1983 survey listed four properties a transaction must have, and called them ACID:

Property Härder and Reuter, 1983 What provides it
Atomicity “all-or-nothing”, and the user must “know which state he or she is in” discarding an unfinished transaction’s changes on abort or crash
Consistency “each successful transaction by definition commits only legal results” constraints you declare, plus your code
Isolation “Events within a transaction must be hidden from other transactions running concurrently” the isolation level (next section)
Durability committed results “survive any subsequent malfunctions” the write-ahead log

Consistency is partly yours. The database enforces only the rules you declare: keys, foreign keys, NOT NULL, and check constraints, which require a value to “satisfy a Boolean (truth-value) expression”, such as amount_kobo > 0. A rule that lives only in application code binds only the code paths that remember it.

Durability comes from a log. The write-ahead log (WAL) records each change before the data files do. PostgreSQL’s rule: changes to data files “must be written only after those changes have been logged, that is, after WAL records describing the changes have been flushed to permanent storage.” After a crash, the database replays the log. So “committed” means on disk: in Härder and Reuter’s words, “the things the system says have happened have actually happened.”

Transactions fix the crash. Do they fix Ada and Kemi? No: wrap each payment in BEGIN and COMMIT, and PostgreSQL’s default still loses ₦5,000. Why?

Perfect isolation is serializable: running transactions together has “the same effect as running them one at a time in some order.” That costs work, so the SQL standard defines weaker levels by the anomalies (wrong results from interleaving) each allows:

  • Dirty read: reading data “written by a concurrent uncommitted transaction”.
  • Nonrepeatable read: reading a row again and finding it “modified by another transaction” that committed in between.
  • Phantom read: re-running a query and finding the set of matching rows “has changed”.
  • Serialization anomaly: a result “inconsistent with all possible orderings of running those transactions one at a time.”
Level (PostgreSQL 19) Dirty read Nonrepeatable read Phantom read Serialization anomaly
Read uncommitted not in PostgreSQL possible possible possible
Read committed (default) no possible possible possible
Repeatable read no no not in PostgreSQL possible
Serializable no no no no

PostgreSQL gives more than the standard’s minimum because each statement reads a snapshot, the data “as it was some time ago”, so “reading never blocks writing and writing never blocks reading.”

Ada and Kemi’s failure is not in the table. Berenson and colleagues named it in 1995: the lost update. One transaction reads, another updates, then the first “(based on its earlier read value) updates the data item and commits.” Their history is ours with other numbers: both read 100, one writes 120, the other 130, and “the final value of x contains only the increment of 30”. It “is possible at the READ COMMITTED isolation level”.

There are three ways out, each with a cost.

One statement. UPDATE takings SET total_kobo = total_kobo + 500000. In Read Committed, a second updater of the same row waits for the first to commit, then applies its change “using the updated version of the row”, as in the diagram. The cost: the whole change must fit in one statement.

Repeatable Read. Each transaction reads one snapshot, taken at its first statement. When Kemi’s transaction updates a row Ada’s changed since then, PostgreSQL rolls Kemi back: “could not serialize access due to concurrent update”. Nothing is lost, but “applications using this level must be prepared to retry”. The cost is the retry loop.

Explicit locks. SELECT ... FOR UPDATE makes the other transaction wait. Lesson 2.7 covers locking strategies and when each wins.

Is Repeatable Read enough, then? Not always. Berenson’s paper names a second anomaly, write skew: two transactions read the same rows, each writes a different one, and “if there were a constraint between x and y, it might be violated.” Their example: a bank lets either of two linked accounts go negative while the sum stays non-negative. Two withdrawals each check the sum, see enough, and debit their own account. Neither touches the other’s row, so both commit. Under a snapshot, “a transaction’s Reads come at one instant and the Writes at another.”

Serializable catches it. PostgreSQL runs it like Repeatable Read, but also watches for dependencies that no one-at-a-time order could produce, and rolls one transaction back with “could not serialize access due to read/write dependencies among transactions” (SQLSTATE 40001). The watching “does not introduce any blocking beyond that present in repeatable read”. The cost is some overhead and more retries, so every transaction needs a retry path.

One question sits under every payment: what type holds ₦5,000.50?

Not a float. real and double precision “are inexact”: they are IEEE 754 binary floating point, and “storing and retrieving a value might show slight discrepancies.” The Python tutorial shows why: “since 0.1 is not exactly 1/10, summing three values of 0.1 may not yield exactly 0.3”. 0.1 + 0.2 prints 0.30000000000000004. For money, “paid equals owed” becomes a question about rounding.

Two exact choices remain. PostgreSQL’s numeric is “especially recommended for storing monetary amounts”, but “very slow compared to the integer types”. Or store minor units, the currency’s smallest unit, as an integer. ISO 4217 lists each currency’s minor unit: two decimal places for the naira (100 kobo) and the US dollar, none for the yen, three for the Bahraini dinar. So ₦5,000.50 is 500050. Integer sums and comparisons are exact; put the unit in the column name.

Size the integer on purpose. A 4-byte integer stops at 2,147,483,647, which in kobo is ₦21,474,836.47, a figure a running total can pass. An 8-byte bigint reaches about 9.2 × 10¹⁸.

Roost, a booking platform for businesses that sell their time, collects deposits and payments in naira.

The problem. An amount passes through many hands. An owner types a price. A payment provider reports what arrived, sometimes as a decimal string. Then the system asks a question that must have an exact answer: does what was paid equal what was owed? If any step holds the amount as a binary float, the answer depends on rounding.

The design. Every amount inside the system is a whole number of kobo in an exact type, never a float, and it travels with its currency. Conversion happens only at the edges: an incoming decimal is parsed as text, and more than two decimal places is refused, not rounded, because rounding would quietly change what someone owes. A percentage cut is worked out in basis points (hundredths of a percent) with integer arithmetic, rounded down, and the other party gets the exact remainder, so the parts always add up to the whole. The rules money must obey, such as no negative amount and no deposit above the total, are check constraints in the database, where every write path meets them. Writes that must agree run in one transaction.

The trade-off. Every boundary needs a converter and tests, and every screen needs formatting. And 500000 means nothing without its unit, so the unit is named wherever an amount crosses a boundary.

Honest about scale. Roost is early-stage and handles one currency. With many currencies the minor unit differs per currency, so an amount cannot be read or shown without its currency code. At much larger volume the question moves from how one amount is stored to how every movement of money is recorded and reconciled: a ledger, lesson 2.8.

Index or no index. An index makes one read fast and every write slower. This course’s suggestion: index the queries you run, starting with the foreign keys you filter on, and check EXPLAIN rather than guess.

Which isolation level. Read Committed is fast and never makes you retry, but read-then-write code can lose updates. Serializable lets you reason about each transaction alone, at the cost of overhead and a retry path everywhere. Repeatable Read stops lost updates, not write skew. This course’s suggestion: Read Committed with single-statement updates for counters; Serializable where a rule spans several rows; locks when retries would be frequent (lesson 2.7).

A stored total or a sum. The takings row is lesson 1.4’s denormalised copy: fast to read, and every payment must update it in the same transaction. SUM(amount_kobo) over indexed payments has nothing to keep in step, at the cost of work on every read.

“A salon dashboard shows today’s takings. Two payments arrive in the same second, and the total ends up one payment short. What happened, and how do you fix it?”

Model answer

The anomaly. A lost update. Each request read the total, added its amount in application code, and wrote the result, so the second write overwrote the first. PostgreSQL’s default, Read Committed, allows it, and wrapping each request in a transaction does not stop it.

Fix 1: one statement. UPDATE takings SET total_kobo = total_kobo + :amount. The second updater waits for the first to commit, then adds to the new value. Cheapest, but the change must fit in one statement.

Fix 2: Repeatable Read or Serializable. The second transaction fails with a serialization error and retries on fresh data. Right for longer read-then-write logic; costs a retry loop.

Fix 3: no stored total. SUM(amount_kobo) over payments, indexed by day. Nothing to keep in step; costs work on every read.

Rubric
  • Names the lost update and the read-then-write cause — 3
  • Says the default level allows it, and a transaction alone does not fix it — 2
  • Gives the single-statement fix and its limit — 2
  • Gives an isolation-level fix and names the retry cost — 2
  • Mentions computing the sum instead, with its cost — 1

Total 10. 8 or more is a pass.

The interviewer follows up: “At least one stylist must be on shift every afternoon. Tolu and Bisi are on for Friday, and both ask for it off at the same moment. Each request counts stylists on shift, sees two, and marks its own stylist off. Both succeed; nobody is on shift. Your Drill 1 fix does not help. Why, and what does?”

Model answer

The anomaly. Write skew. Both transactions read the same rows, each writes a different row, and together they break a rule that spans both. Neither update touches the row the other wrote, so a single-statement update has nothing to wait on.

Why Repeatable Read fails. Each transaction’s snapshot shows two stylists on shift, and the writes never meet on one row, so both commit.

Fix. Run both at Serializable. No one-at-a-time order gives this result, so PostgreSQL rolls one back with SQLSTATE 40001; the retry sees one stylist on shift and refuses. The cost is overhead and a retry path. The alternative, locking the rows the rule reads, is lesson 2.7.

Rubric
  • Names write skew and explains that the writes hit different rows — 3
  • Explains why Repeatable Read allows it — 2
  • Chooses Serializable and handles the retry — 3
  • Names a locking alternative and its cost — 2

Total 10. 8 or more is a pass.

Break and fix all three failures in PostgreSQL, with two psql sessions side by side.

  1. Create appointment (id bigint primary key, stylist_id int, starts_at timestamptz) with two million rows from generate_series. Predict the plan for “Tolu’s day”, then run EXPLAIN ANALYZE. Add this lesson’s index, run it again, then reverse the columns.
  2. Create takings (day date primary key, total_kobo bigint). In session A, BEGIN, insert a payment and update takings, then close the session without committing. Predict what session B sees.
  3. In both sessions, BEGIN, read the total, then write a new total you computed by hand. Commit both and count the money. Repeat with SET total_kobo = total_kobo + ..., then with BEGIN ISOLATION LEVEL REPEATABLE READ and the hand-computed total. Note each error.
  4. Build Drill 2’s shift rule. Make it fail at Repeatable Read, then catch it at Serializable.
  5. In any language, add 0.1 ten times and compare with 1.0. Then do the sum in integer kobo.

Write one sentence per step on what surprised you.

Answer without notes.

  1. Why is a query on an unindexed column slow on a large table? For stylist_id = ? AND starts_at BETWEEN ? AND ?, which index do you build, and what does it cost?
  2. Say what each ACID letter means in one sentence, and which mechanism provides durability.
  3. A server crashes between two writes inside one transaction. What does the database hold after restart, and why? What changes if the writes were not in a transaction?
  4. Name PostgreSQL’s default isolation level. Define the lost update and write skew, and say which level stops each.
  5. Why should money never be a float? How would you store ₦5,000.50, and why does the integer’s size matter?