AlgoViz

SQL databases

easy 25 min

A SQL (relational) database keeps data in tables with declared columns, joins those tables by key when you ask a question, and enforces rules such as unique emails and valid references.

Video lesson · Chapter 1 of 5

Give an order a stable identity

0:00 / 3:56

Theory

Read or listen first. About 2 min.

What it is

A relational database stores facts in tables. A table has named columns, each with a type, and each row is one fact: one customer, one order. You ask questions in SQL, the Structured Query Language, by describing the answer you want instead of the steps to find it.

The database also guards the data. You declare rules once, such as "every email is unique" or "every order belongs to a real customer", and no program can break them by accident. Changes that belong together are grouped into a transaction.

Why it exists

Before relational systems, programs had to know how records were linked on disk. A new question often meant a new program. With tables and SQL, a question nobody planned for is one new query, and the database chooses how to run it.

The second reason is trust. Money, stock and bookings must stay correct when two people act at once and when the power fails. Rules and transactions put that work in one well-tested place instead of in every service.

A short history

  1. 1970

    Edgar F. Codd at IBM publishes "A Relational Model of Data for Large Shared Data Banks". Data is described by its values, not by how it is stored.

  2. 1973

    IBM starts System R, a full-strength relational system. Its team includes Chamberlin and Boyce, who design the query language, and Patricia Selinger, who develops a cost-based optimizer.

  3. 1986

    SQL becomes an ANSI standard, and an ISO standard the year after. In the same year, work begins on POSTGRES at Berkeley.

  4. 1995

    The first version of MySQL appears.

  5. 1996

    Berkeley's project, by then with SQL, takes its present name: PostgreSQL.

Words to know

Table, row, column
A named set of facts, one fact, and one named property with a type.
Schema
The declared shape of the data: tables, columns, types and rules.
Primary key (PK)
The column or columns that identify one row. Never empty, never repeated.
Foreign key (FK)
A column that must hold a key that exists in another table.
Join
Combining rows of two tables where a value matches.
Transaction
A group of changes that takes effect as one, or not at all.
Index
A sorted or hashed structure kept beside a table so that rows are found without reading all of it.
Normalisation
Arranging tables so that each fact is stored in one place.

How it works

Step through the idea, or press Play.

Step 1 of 4

Declare. Tables, columns, types, keys and rules come first

Understand it

Start here

The school register

A school keeps its records on paper. The first version is one big sheet, and the same teacher's name is written again for every pupil in the class. Two linked lists fix that, and a simple rule keeps nonsense out.

From one sheet to linked lists
EVERYTHING ON ONE SHEETNo.PupilClassTeacher1Ana5ARay2Bo5ARay3Cy5BLin4Di5ARay

Same facts, less repetition, and a rule that cannot be forgotten.

Another everyday picture is a very tidy filing cabinet with spreadsheets inside. You ask "show me all customers from New York" and the right rows come out. The cabinet is good, but not magic: it can still lose data if you turn durability off or never take a backup, and it is slow when nothing tells it where to look.

The idea

Tables, rows and keys

A users table

id (PK)nameemailcreated
1Alicealice@ex.com2024-01-15
2Bobbob@ex.com2024-01-16
3Carolcarol@ex.com2024-01-17
Each row is one user. The primary key id identifies it, even if the name or the email changes.
  • Schema first

    You define the structure before you insert data. A wrong type or a missing value is refused at the door.

  • Relationships

    Tables are linked by foreign keys and combined by joins, so one fact serves many questions.

  • ACID transactions

    Related changes commit together or not at all, and a commit survives a crash.

  • Declarative queries

    You say what you want. The planner chooses the order, the indexes and the join method.

Rules the database keeps for you

ConstraintWhat it refuses
Primary keyA missing or repeated identity
Not nullA row without a required value
UniqueA second account with the same email
Foreign keyAn order for a customer that does not exist
CheckA balance below zero, a quantity of minus three
Application checks are still useful for friendly messages, but two requests can pass the same check at the same moment. The constraint cannot be raced.

Modelling

Relationships between tables

A small shop

One customer has many orders. Orders and products are many to many, so a third table, the order line, holds one row per pair.

From a story to tables

  1. 1

    Underline the nouns

    "A customer places an order for products." Customer, order and product become tables.

  2. 2

    Give each a key

    A number or a UUID that never changes. Emails and phone numbers do change.

  3. 3

    One to many

    Put the foreign key on the many side: each order stores its customer's id.

  4. 4

    Many to many

    Add a table for the pair. It is also the home of facts about the pair, such as the quantity and the price paid.

  5. 5

    Write the rules

    Not null, unique, check and foreign keys, decided together with the tables.

Modelling

Normalisation: one fact, one place

Normalising is like organising a closet. Each kind of thing gets one specific place, and labels, the foreign keys, tell you where to find it. The rules come in steps called normal forms.

FormRuleBreaks itFix
1NFAtomic values, no repeating groupsphones holds two numbers in one textA phone numbers table, one row each
2NFNo column depends on part of a composite keyStudent name stored in the student and course tableKeep the name only in students
3NFNo column depends on another non-key columnDepartment name in the employee tableKeep it only in departments
BCNFEvery determinant is a keyA teacher fixes the room, but is not a keySplit out teacher and room
A saying that covers the first three: every column depends on the key, the whole key, and nothing but the key.

What repetition costs

5,000,000 orders×200 B=1 GB500,000 customers×200 B=100 MB5{,}000{,}000 \text{ orders} \times 200\,\text{B} = 1\,\text{GB} \qquad 500{,}000 \text{ customers} \times 200\,\text{B} = 100\,\text{MB}
Assume a 200-byte address. Repeating it in every order takes ten times the space. The larger cost is the update: a customer with ten orders has ten copies to change.

Asking

Writing a query

SQL
-- big orders, newest firstSELECT u.name, o.total, o.created_atFROM users uJOIN orders o ON u.id = o.user_idWHERE o.total > 100ORDER BY o.created_at DESCLIMIT 10;-- customers with more than five ordersSELECT user_id, COUNT(*) AS order_count, SUM(total) AS spentFROM ordersGROUP BY user_idHAVING COUNT(*) > 5;
WHERE filters rows before grouping. HAVING filters the groups.

The logical order of a SELECT

You write SELECT first, but it is worked out late. That is why, in standard SQL, WHERE cannot use a name invented in the SELECT list. The database may run the work in another order if the answer is the same.

Kinds of join

JoinKeeps
InnerOnly pairs that match
LeftEvery left row, with empty values when nothing matches
FullEvery row of both sides
CrossEvery combination; rarely what you meant
To keep customers without orders you need a left join. A filter on the right table in WHERE would remove them again, so put that filter in the ON clause.

Speed

Indexes

Without an index, finding a row means reading the whole table, like reading a book from the first page. An index is the index at the back of the book: sorted words with page numbers. How the tree works inside is in B-tree.

IndexGood forExample condition
B-treeThe usual default: equality, ranges, sortingage > 25
HashEquality onlyid = 123
CompositeSeveral columns, led by the first onescity and state
UniqueSpeed plus a ruleemail must be unique
In PostgreSQL, CREATE INDEX builds a B-tree unless you ask for another type, and a hash index answers equality only.
SQL
-- single columnCREATE INDEX idx_users_email ON users(email);-- composite: the order mattersCREATE INDEX idx_orders_user_date  ON orders(user_id, created_at);-- uniqueCREATE UNIQUE INDEX idx_users_username  ON users(username);

Will the planner use my index?

A simplified rule of thumb. The real planner compares estimated costs; EXPLAIN shows the choice it made.

How deep is the tree?

levels=⌈log⁡500100,000,000⌉=⌈82.70⌉=3\text{levels} = \left\lceil \log_{500} 100{,}000{,}000 \right\rceil = \left\lceil \tfrac{8}{2.70} \right\rceil = 3
Assume 500 keys fit in one page. One hundred million rows are three pages away from the top, instead of a scan of every page.

Safety

Transactions and ACID

ACID is a contract: whatever happens, a power cut, a crash or an error, committed data stays safe and the rules still hold. The contract covers what you declared and enabled. It cannot know a rule you never wrote.

LetterMeansExample
AtomicityAll of the transaction, or none of itA transfer debits and credits, or does neither
ConsistencyFrom one valid state to anotherbalance >= 0 is always enforced
IsolationTransactions running together do not disturb each other, up to the chosen levelTwo people book the last seat: one succeeds
DurabilityA commit survives a crashPower fails after the commit; the data is there
SQL
BEGIN;-- debit account AUPDATE accounts SET balance = balance - 100 WHERE id = 'A';-- credit account BUPDATE accounts SET balance = balance + 100 WHERE id = 'B';COMMIT;      -- if both succeed-- ROLLBACK; -- if anything fails

A transfer that fails halfway

No half transfer remains. Atomicity does not care why the transaction did not commit.

Isolation has levels, and the default is usually not the strictest: PostgreSQL's default is Read Committed. Details live in ACID and isolation levels.

Inside

What happens to one query

The path of a query

A service sends SQL to one relational database. Inside it, a parser and planner pass a plan to an executor. The executor reads pages through a page cache, which fetches missing pages from the tables and indexes. At commit the executor writes to the write-ahead log, whose changes reach the tables later.
Reads are fast when the page is in memory. A commit waits for the log, not for the table itself.
  1. 1

    Parse and plan

    Check the text and the names, list the possible ways, estimate their cost and choose one.

  2. 2

    Execute

    Walk indexes, read pages, join, group and sort.

  3. 3

    Use the page cache

    Hot pages stay in memory, so a working set that fits in memory rarely touches the disk.

  4. 4

    Log before commit

    The change is written to the write-ahead log first. After a crash the log is replayed.

Row storage like this suits many small reads and writes, called OLTP. Large scans over a few columns are the business of OLAP systems, which store columns together. Some engines use an LSM tree instead of a B-tree.

Numbers

Does it fit on one database?

Ten million orders a day

10,000,000100,000=100/s100×3=300/s at peak300×4=1,200 row writes/s\frac{10{,}000{,}000}{100{,}000} = 100/\text{s} \qquad 100 \times 3 = 300/\text{s at peak} \qquad 300 \times 4 = 1{,}200 \text{ row writes/s}
Assume three lines per order, so four rows. The exact day has 86,400 seconds, about 116 orders a second; dividing by 100,000 is the quick version.

At an assumed 1 KB per order with its rows and indexes, that is 10 GB a day and 3.65 TB a year. The write rate is modest. The growth is what asks for a decision: keep a year in the primary tables and move older orders to cheaper storage, or split by time.

Growth

Scaling a relational database

One primary, a standby and a read replica

Users send requests to an app. The app sends all writes to one primary database. The primary copies each change to a standby and waits for it, and copies to a read replica without waiting.
The standby is for failure. The replica is for reads that may be slightly old. All writes still go to one machine.
  1. 1

    Fix the queries

    Read the slow query list, add the missing index, stop fetching rows you do not use.

  2. 2

    Use a connection pool

    Connections cost memory. A small shared pool serves many requests.

  3. 3

    Scale up

    More memory keeps more pages cached. See vertical scaling.

  4. 4

    Add replicas

    Reads that tolerate lag move away. Read your own write from the primary. See data replication.

  5. 5

    Partition or shard

    Split by time inside one database, or by customer over many. See sharding.

Products

Popular SQL databases

DatabaseCharacterSeen in
PostgreSQLOpen source, wide feature set, jsonb documents, many index typesWeb back ends, analytics beside transactions
MySQLWidely used open source serverFacebook describes running it for its most important workloads
SQL ServerMicrosoft's server, on Windows and LinuxStack Overflow described it at the centre of its 2016 design
SQLiteA library, not a server: one file inside your programAndroid and iOS devices, Firefox and Chrome

"Why PostgreSQL over MySQL?" is a common question. A good answer names a feature you need: jsonb with rich indexing, custom types or extensions. Do not say that MySQL lacks common table expressions or window functions: current versions have both. And "faster for reads" is a claim to test with your own queries.

Decide

When a relational database fits

Good signs

  • Facts refer to each other, and questions cross them
  • Money, stock or bookings: wrong is worse than slow
  • You cannot list all future questions
  • The data fits on one strong machine for years
  • Reports and constraints matter

Look elsewhere

Summary

The whole topic in one minute.

A relational database keeps each fact once, in tables linked by keys. You describe the result in SQL and the planner finds a way to compute it, using indexes when they help.

Constraints and transactions keep the data correct under failure and concurrency. Start with one such database, index for your real queries, add a standby and read replicas, and split the data only when a number forces you to.

  • Tables hold typed rows; keys link them; joins combine them.
  • Constraints refuse bad data even when two requests race.
  • Normalise to keep each fact once; copy only on purpose.
  • An index turns a scan into a few page reads, and every index slows writes.
  • A transaction commits as a whole; isolation has levels.
  • Grow in order: queries, pool, bigger machine, replicas, then splitting.

Sources