Relational Databases and SQL for Design

Know what relational databases guarantee (schemas, joins, ACID transactions, isolation levels) and why they are the default choice for most systems.

Beginner · about 4 hours · difficulty 2/5

Learn first: Back-of-the-Envelope Estimation

Relational databases such as PostgreSQL and MySQL store data in tables with a fixed schema and let you query it with SQL. For most products, a well-tuned relational database is the right starting point; Razorpay, Zerodha and countless startups run core money flows on them.

What you get

  • Schema and constraints: types, NOT NULL, UNIQUE, foreign keys. The database protects data quality for you.
  • Joins and flexible queries: you can answer questions you did not plan for.
  • ACID transactions: Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent transactions do not see each other's half work), Durability (committed data survives a crash, thanks to the write-ahead log).

Isolation levels

  • Read committed (Postgres default): no dirty reads, but a row can change between two reads in the same transaction.
  • Repeatable read / snapshot isolation: a consistent snapshot for the whole transaction.
  • Serializable: as if transactions ran one at a time; safest, with more aborts to retry.

Know the classic anomalies: dirty read, non-repeatable read, phantom read, lost update and write skew. Booking the last seat twice is a lost update problem.

Concurrency tools

  • Pessimistic locking: SELECT ... FOR UPDATE holds a row lock while you decide.
  • Optimistic locking: a version column; the update fails if someone else changed the row first.

Normalisation vs denormalisation

Normalise to avoid duplicate, inconsistent data. Denormalise selectively (store order_total, or a copy of the restaurant name on the order) when read speed matters more than write simplicity.

Pitfalls

  • Leaving everything at default isolation and assuming money transfers are safe.
  • Reaching for NoSQL "for scale" when a single Postgres with read replicas would serve years of growth.

You are ready to move on when you can explain ACID, name the isolation level that prevents double booking, and write a transaction that moves money between two accounts safely.

Key concepts

  • Tables, schemas and constraints
  • ACID transactions
  • Isolation levels and anomalies
  • Pessimistic vs optimistic locking
  • Normalisation and denormalisation
  • Write-ahead log
  • PostgreSQL vs MySQL

Mini project

Model a wallet with accounts and transfers in PostgreSQL. Write a transfer function, then run 100 concurrent transfers with a script and show that balances stay correct with proper locking and break without it.

Check yourself

Two users try to book the last seat at the same time. Describe one pessimistic and one optimistic way to make sure only one succeeds.

Free resources