How Databases Actually Work, Part 1: Finding Your Data
What happens when you hit Enter?
You type this, hit Enter, and a couple of milliseconds later your row is back:
SELECT * FROM players WHERE name = 'Kit';
That table has 10 million rows. The database didn’t read them all. It went almost straight to the right one. How does it pull that off? And how does it do it while thousands of other people are writing to the same table, without losing a thing when the server crashes?
It’s easy to think of a database as a massive Excel sheet: you jump to the row you want and read across the columns. Under the hood, it’s quite different: lookups that fast don’t come for free, and they depend on structures the database builds and maintains behind the scenes.
That’s what this post is about: what actually happens inside a database.
Our running example is the backend of a Minecraft server: a players table with 10 million rows, an inventory table showing what each player is carrying, and a trades table where players swap items. To answer even simple queries, the database has four jobs:
- Storage: data lives in fixed-size pages, on disk or cached in RAM.
- Access paths: indexes let it jump straight to the right page instead of scanning the whole table.
- Query optimisation: the same query can run many different ways, so a planner estimates the cost of each and picks the cheapest.
- Durability and concurrency control: a committed change must survive a crash, and when many users read and write at once, nobody should see someone else’s change until it’s committed.
This part covers the first three: how data is stored, found, and how the database decides the fastest way to get it. Part 2 covers the fourth.
Where data lives: pages, disk and RAM
First surprise: a database never reads a single row. It reads a page, a fixed-size chunk that holds lots of rows. In Postgres a page is 8 KB, which fits dozens of players rows. Why bother? Because of this:
Approximate orders of magnitude from widely cited latency figures
RAM is fast, disk (even an SSD) is slow, and the gap is huge. Almost every trick in this post boils down to one goal: read as few pages as possible, and read them from RAM instead of disk whenever you can.
Why pages? Storage devices read and write in fixed-size blocks, and every I/O request carries a fixed overhead, so fetching 8 bytes costs about the same as fetching 8 KB. Databases amortise that overhead by always reading whole pages and packing each one as densely as they can.
The heap: where rows actually live
Postgres stores each table as a file on disk, split into those 8 KB pages. That file is called the heap: an unordered pile of rows. A new row goes wherever there’s free space, often the end of the file or a gap left by a deleted row. Your 10 million players aren’t stored alphabetically or by ID. Kit just sits next to whoever happened to land on the same page.
Instead of reading every page to find a particular row, every row gets an address: its page and its slot on that page. Kit’s is page 1, slot 3. An index maps each key to its row’s address: “Kit” → page 1, slot 3. Look up the key, and you go straight to the row.
The players table as a heap file · illustrative
What’s inside a page
Zoom into one 8 KB page and you’ll find a neat layout called a slotted page. It fills up from both ends at once:
Postgres slotted heap page · simplified, not to scale
- The header at the very start holds a few facts about the page itself, like how much free space is left.
- Next comes the slot list, which records the location of each row within the page. Without it, you couldn’t jump straight to a specific row, because rows vary in size: a long name or a big JSON value makes one row longer than the next.
- The rows themselves are stored from the back of the page, working forwards. When the slot list and the rows meet in the middle, the page is full.
Which pages stay in RAM
When you set up Postgres, whether on a laptop or a managed service like Azure, a fixed slice of the server’s RAM is set aside just for holding pages. That’s the buffer cache. If the page a query needs is already there (a cache hit), Postgres skips the disk entirely. If not (a miss), it reads the page from disk and has to evict some other page to make room. The eviction policy approximates least-recently-used: every page carries a usage count that goes up each time it’s accessed and decays over time. So pages that queries keep coming back to, like the ones holding your most-looked-up players, stay in RAM. Pages read once, say by a one-off scan of the whole table, are the first to be evicted.
Underneath sits a second cache. Postgres doesn’t read the disk itself: it asks the operating system to read its data files through system calls, and the OS keeps recently read file data in its own page cache. A page evicted from the buffer cache is often still sitting there, so the read costs a system call rather than a trip to disk.
Both caches live in the same physical RAM, and they don’t coordinate, so a hot page is often cached twice: once by Postgres, once by the OS. That double caching is why the buffer cache is deliberately kept to a fraction of the machine’s RAM, typically around a quarter, leaving the rest for the OS. Run Postgres in Docker on your laptop and the default buffer cache is just 128 MB, so the OS cache does much of the work. On a managed service like Azure, the buffer cache is sized for you based on the server you pick. Either way, there’s an operating system underneath doing this caching: Docker containers share the host’s OS, and Azure runs Postgres on a Linux server you never see.
Reading a page in Postgres · two caches, then the disk (simplified)
Finding things: why indexes exist
Reading every page has a name: a sequential scan, and for 10 million players it means tens of thousands of pages. An index avoids that by mapping “Kit” to an address, but with 10 million names the index itself spans thousands of pages. You don’t want a sequential scan of the index either. So how is it laid out so that finding Kit takes only a handful of reads?
CREATE INDEX players_name_idx ON players (name);
The B-tree: a sorted tree that stays short
The most common kind of index, and the default in Postgres, MySQL and most relational databases, is the B-tree. When you create an index on name, each player’s name becomes a key: the value you search by. The index is stored separately from the heap, and its job is to translate a key into the row’s address: “Kit” → page 1, slot 3.
But with 10 million players, the index itself has 10 million entries. If finding “Kit” in the index meant reading through all of them, you’d just be doing a sequential scan of the index instead of the heap. So the index needs a layout built for fast lookup. A B-tree solves this by storing the keys in sorted order and arranging their pages as a tree; for 10 million names, that’s three layers:
- Leaf pages at the bottom hold every name in alphabetical order, and next to each name, the address of its row: ‘Kit’ → page 1, slot 3. The name is what you search by; the address is where it sends you.
- Inner pages hold no rows or addresses, just directions: each entry is a range of names plus the page below that covers it, like “A to F → this page, G to M → that page”.
- The root is the single page at the top where every search starts.
B-tree on players.name · 3 levels plus the heap (simplified)
What keeps a B-tree shallow is its fan-out: the number of child pages a single page can point to. Unlike a binary search tree, where each node has at most two children, a B-tree page can point to hundreds of child pages.
Suppose every page above the leaves (the root and the inner pages) can point to 200 child pages. The root points to 200 pages, and each of those points to another 200, giving 40,000 leaf pages. Since each leaf page also stores hundreds of index entries, a tree with just three levels can index millions of rows. That’s why finding Kit among 10 million players takes four page reads, three down the index and one into the heap, instead of tens of thousands. Add a fourth level and the same tree covers billions.
Sorted leaves pay off a second time with ranges. Each leaf page links to the next one, so to find every name from Kai to Kim (WHERE name BETWEEN 'Kai' AND 'Kim'), Postgres walks down the tree once to reach Kai, then reads the leaves left to right until it passes Kim. The same goes for returning results in alphabetical order (ORDER BY name): the leaves are already sorted, so there’s no sorting to do.
Why not just a hash map?
If you’ve used hash maps, you might wonder why the database doesn’t just hash “Kit” and jump straight to the entry in O(1). It can: Postgres has hash indexes. But the B-tree is the default for good reasons:
- Hashing throws away order, so no ranges. A hash scatters “Kai”, “Kim” and “Kit” to unrelated spots, so it can find
name = 'Kit'but can’t do the range lookup from above (every name from Kai to Kim), or return names in alphabetical order. In a B-tree, those names sit side by side in the leaves, which is exactly what makes ranges cheap. - O(1) vs O(log n) barely matters here. What actually costs time is reading a page from disk when it isn’t already in RAM. A B-tree lookup touches only three or four pages, and its top levels are used so often they almost always stay cached. A hash lookup still reads an index page and then the row from the heap, so it saves a page or two at most, usually ones that were already in RAM.
Page splits, and why random IDs hurt
So far, we’ve been looking at a B-tree index on the name column. Now consider an index on the player’s id column instead. In Postgres, a B-tree index is created automatically when you define a primary key.
Each leaf page has a limited amount of space. When a new player is added, their id value has to be inserted into the right leaf page. If that page is already full, Postgres allocates a new page and redistributes the entries between the two pages, preserving their sorted order. It then updates the parent page to include a pointer to the newly created page. This process is known as a page split.
A B-tree leaf page split · simplified, real pages hold hundreds of entries
Page splits are a normal part of how a B-tree grows. However, the order in which new IDs are generated can have a significant impact on index performance. Consider two approaches to generating player IDs:
- Sequential IDs: Suppose we assign players IDs of 1, 2, 3, and so on. Since each new ID is larger than the previous one, new index entries are always inserted into the rightmost leaf page. When that page fills up, Postgres notices the insert is at the very end of the index and splits unevenly: instead of moving half the entries, it leaves the old page almost full and starts a fresh page for the new ID. Subsequent inserts continue on that new rightmost page. This keeps older pages densely packed and the page receiving new entries in the buffer cache.
- Random IDs: If IDs are generated randomly, a new ID could belong anywhere in the B-tree. Instead of repeatedly accessing the same leaf page, Postgres may need to access a different page for each insertion. If that page isn’t already cached in RAM, it may require a disk read. Page splits also occur throughout the index, and each one is a half-and-half split like the one in the diagram, leaving unused space across leaf pages and potentially increasing the overall size of the index.
This matters when you choose the type of a table’s primary key, like the id of players. Sequential IDs come from a single counter inside the database, so a new player only gets an ID once their row reaches it. That’s fine for one server, but awkward when records are created in many places at once, like several game servers or an app that works offline. Sequential IDs are also easy to guess: if you’re player 1042, player 1041 probably exists. UUIDs (Universally Unique Identifiers) avoid both problems. They’re 128-bit random values, a range so large that anyone can generate one on the spot with practically no chance of a clash. Fully random UUIDs fall into the second case above. Time-ordered UUIDs (UUIDv7) start with a timestamp, so each new one sorts after the previous ones and behaves like a sequential ID: you get both benefits.
A table can have more than one index, each its own separate B-tree. Say players has one on name, whose leaves list every player alphabetically, and one on mode, whose leaves list every player grouped by game mode. Then SELECT * FROM players WHERE name = 'Kit' AND mode = 'survival' could be answered by scanning the whole table, using the name index, or using the mode index. Same answer, very different costs. So how does the database pick?
The query planner: the database’s decision-maker
When you write SQL, you say what you want, not how to get it. For SELECT * FROM players WHERE name = 'Kit', Postgres could read the whole table, or walk the index on name. Choosing between options like these is the job of the planner. It estimates the cost of each one, mostly how many pages it would have to read, and picks the cheapest. Usually it’s right. When a query is mysteriously slow, it’s often because the planner was working from a bad estimate.
To see the plan it chose, put EXPLAIN in front of a query. EXPLAIN ANALYZE goes further: it runs the query too, and reports what actually happened next to what the planner expected.
EXPLAIN ANALYZE SELECT * FROM players WHERE name = 'Kit';
Postgres replies with something like this (the exact format varies a little between versions):
Index Scan using players_name_idx on players (cost=0.43..8.45 rows=1 width=52) (actual time=0.030..0.031 rows=1 loops=1)
Index Cond: (name = 'Kit'::text)
Buffers: shared hit=4
Planning Time: 0.112 ms
Execution Time: 0.049 ms
Here’s what each part means:
Index Scan using players_name_idx: Postgres walked the index onnameinstead of reading the whole table.cost=0.43..8.45 rows=1is the planner’s estimate before running. The..separates two numbers: 0.43 is the estimated cost of finding where Kit’s row is (walking down the B-tree), and 8.45 is the total, including reading the row from the heap and returning it. The units are made up, roughly “the price of reading one page”, so they’re only useful for comparing one plan with another.rows=1is how many rows it expects to find.actual ... rows=1is what really happened. Comparing those tworowsnumbers is the most useful check in any plan. Here they match, so the planner guessed well; a big gap means it guessed wrong and probably picked a bad plan.Buffers: shared hit=4: it touched 4 pages, all already in the buffer cache. Three down the B-tree, one in the heap: the four page reads from earlier.
An Index Scan is one of a few kinds of step you’ll see in plans. The most common:
- Seq Scan: a sequential scan, reading every page of the table.
- Index Scan: the one above. Walk the B-tree to find the matching addresses, then fetch each row from the heap.
- Index Only Scan: everything the query asks for is already in the index, so it can usually skip the heap. For example,
SELECT name FROM players WHERE name = 'Kit'only needs the name, which thenameindex already has.
“But I have an index! Why isn’t it using it?”
A classic surprise: you create an index, run EXPLAIN, and the plan still says Seq Scan. Postgres had the index available and chose to read the whole table anyway. That’s not a bug. The planner decided the index would be slower, based on its estimates.
The planner’s estimates come from statistics Postgres keeps about each table: roughly how many rows it has, the most common values in each column, and how the rest are spread out. They’re refreshed automatically in the background, or by hand with ANALYZE. When it ignores your index, it’s usually one of these:
- Your filter matches too many rows. If 40% of players are in survival mode,
WHERE mode = 'survival'matches 4 million rows, and since the heap isn’t sorted, they’re scattered across nearly every page. Through the index, Postgres would fetch them one at a time: 4 million separate trips into the heap, hitting the same pages over and over in random order. Reading the table straight through visits each of its tens of thousands of pages just once, in order, which is far less work. - The statistics are out of date. After loading a million rows at once, the planner may still think the table is tiny. Running
ANALYZEfixes it. - Your query hides the column. The
nameindex stores names exactly as they were written ('Kit') and is sorted in that form.WHERE lower(name) = 'kit'asks about a lowercased version that isn’t in the index, so Postgres would have to lowercase every name to check, which means reading them all. You can index the lowercase version instead:CREATE INDEX ON players (lower(name))stores'kit', sorted, and this query can use it.
Joining tables
Most real queries combine tables. The trades table doesn’t store names, only the IDs of the two players involved: a row might say player 1 gave 3 diamonds to player 2. To show “Kit gave 3 diamonds to Alex”, each trade has to be matched with the players table to turn those IDs into names. That matching is called a join, and choosing how to do it is usually the planner’s biggest decision. Postgres has three ways:
- Nested loop: a loop inside a loop. The outer loop goes through the trades one by one, and for each trade, the inner step looks up the matching player using the index on player IDs from earlier. A thousand trades means a thousand quick index lookups. Great when there aren’t many trades; with millions, those lookups add up.
- Hash join: build a hash map first, then use it. Postgres reads
playersonce and puts every player into a hash map in RAM, keyed by ID (1 → Kit, 2 → Alex, …). Then it readstradesonce from start to finish, and for each trade looks up both IDs in that hash map, which takes no index and no extra page reads. Great when both tables are big, because each one is read just once. - Merge join: sort both tables by player ID, then walk through them together like the merge step in merge sort, pairing up rows whose IDs match. Each table is read just once. Great when both are already sorted, for example when read through a B-tree index; otherwise sorting them first costs extra.
When a query joins three or more tables, Postgres joins two of them, then joins that result with the next table, so it also has to pick the join order. Say you want a list of all the players who traded today, along with their inventory. That needs all three tables: trades for today’s trades (1,000 of them), players for the names, and inventory for the items. Postgres could start from either end:
- Trades first: take today’s 1,000 trades, join them with
players(still 1,000 rows, now with names), then withinventory. Every step handles about 1,000 rows. - Players first: join all 10 million players with their inventories (10 million combined rows), and only then with today’s trades to get the 1,000 you actually wanted. Same answer, thousands of times more work.
Every one of these choices depends on how many rows the planner expects each step to produce. Say it estimates only 10 trades were made today, so it picks a nested loop: 10 quick index lookups into players. If 4 million trades actually come back, that’s 4 million lookups, and the query crawls when a hash join would have been far faster. That’s why, when EXPLAIN ANALYZE shows expected rows far from actual rows, refreshing the statistics with ANALYZE is the first thing to try.
Coming up in Part 2
So far we’ve only read data. Part 2 is about changing it safely: how a database records a change so it survives a crash halfway through, how thousands of players can read and write the same rows at once without seeing each other’s half-finished work, and how other databases like Redis, Cassandra and MongoDB make different trade-offs.