Kit (Phuc) Nguyen

How Databases Actually Work, Part 1: Finding Your Data

Nov 28, 2026 · databases

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:

  1. Storage: data lives in fixed-size pages, on disk or cached in RAM.
  2. Access paths: indexes let it jump straight to the right page instead of scanning the whole table.
  3. Query optimisation: the same query can run many different ways, so a planner estimates the cost of each and picks the cheapest.
  4. 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:

Log-scale chart of access times: CPU cache read 1 ns, RAM read 100 ns, SSD random read 100 µs, data-centre network round trip 500 µs, spinning disk seek 10 ms 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 one heap file of three pages, each holding a few rows in numbered slots. Kit is in page 1, slot 3, and a new player lands in free space on page 2. 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:

An 8 KB page laid out as a header, a slot list growing from the front, free space in the middle, and rows growing from the back. Slot 2 points to row 2. Postgres slotted heap page · simplified, not to scale

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.

A query checks the Postgres buffer cache first, then on a miss the OS page cache, then on another miss the disk. The page with the lowest usage count in the buffer cache is evicted next. 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:

A B-tree on players.name. The root points to the inner page for names G to M, which points to the leaf page Kai to Kyle, which gives the row address of Kit’s full row in the heap. B-tree on players.name · 3 levels plus the heap (simplified)

Animated B-tree lookup: root, inner page, leaf, then heap page 1 slot 3, with a page-read counter ticking from 1 to 4
Watch the page-read counter: four reads to find one row among 10 million.

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:

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 full leaf page holding IDs 10, 20, 30 and 40 receives ID 25. It splits into leaf page 1 with 10 and 20, and a new leaf page 2 with 25, 30 and 40. The parent gets a new entry pointing IDs from 25 up to leaf page 2. 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:

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:

An Index Scan is one of a few kinds of step you’ll see in plans. The most common:

“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:

  1. 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.
  2. The statistics are out of date. After loading a million rows at once, the planner may still think the table is tiny. Running ANALYZE fixes it.
  3. Your query hides the column. The name index 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:

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:

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.

Read Part 2: Keeping Your Data Safe →

Back to all writing