Vineet Ganti
How Data Sits on Disk: Pages, Heaps and Clustered Tables
All posts

Data Engineering/Database Engineering · Part 2 of 14

·23 min read

How Data Sits on Disk: Pages, Heaps and Clustered Tables

What a table really is on disk: fixed-size pages in a file, what's inside one byte by byte, why a read is never one row, how Postgres's heap differs from InnoDB's clustered tree, and why column stores win at analytics.

DatabasesPostgreSQLMySQLStorage

A table looks like a spreadsheet: rows and columns, in a nice grid. On disk nothing looks like that. A table is a file, the file is a sequence of fixed-size pages, and every read and write the database does happens one page at a time.

Almost every performance question in this series comes back to this picture. An index is a way to read fewer pages. A cache is a way to avoid reading them twice. A bad primary key is one that spreads rows over too many pages. So this post opens up a real page and reads it byte by byte.

#From rows to pages

Start with the vocabulary, because every later post uses it.

  • Table: what you query. Rows and columns, with no physical meaning.
  • Row id: an internal identifier for each row. In InnoDB it's the primary key. In Postgres it's a physical address called the ctid.
  • Page: a fixed-size block of bytes holding many rows. It's the smallest unit the database reads or writes.
  • I/O: one read request to the disk. The aim of most tuning is to do fewer of them.
  • Heap: the collection of pages holding the table's actual data.
  • Index: a separate structure, also stored in pages, that says which heap page holds what you want.

Here are the real page sizes on the two engines:

✅ ran here · PostgreSQL 18.6
SHOW block_size;
 block_size 
------------
 8192
(1 row)
✅ ran here · MySQL 8.4.13
SELECT @@innodb_page_size;
+--------------------+
| @@innodb_page_size |
+--------------------+
|              16384 |
+--------------------+
1 row in set (0.00 sec)

Every row in Postgres shows its address if you ask for the hidden ctid column. Try the presets:

Every row has an addressruns in your browser
ctid is (page, line pointer). Watch a row's address change when you update it, and see which rows share a page.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

The last preset is the one to watch: an UPDATE changes a row's address, because it writes a new copy. Post 1 explained why, and we're about to see the bytes.

#Why a read is never one row

If an index tells the database exactly where a row is, why fetch a whole page? A student asked this in the course's Q&A, and the answer has three layers.

Disks aren't byte addressable. RAM lets you ask for one byte. A disk only serves whole blocks, so even a request for 4 bytes moves at least a block.

The database often doesn't know the exact byte. Rows vary in size, so the only thing it can compute is which page a row is in. The position inside the page is stored in the page itself, and the page has to be in memory to read that.

Fetching neighbours is usually a good bet. Rows that are read together tend to sit together, and a page brings them all for the same cost. This is why a query reading a range of an index is fast, and why packing related rows together pays off.

The terms overlap, so here's how I keep them apart: a page is the database's unit, a block is the file system's or disk's unit, and one page usually spans several blocks.

You can count pages directly. EXPLAIN (ANALYZE, BUFFERS) reports every page a query touched. This table holds 100,000 employees:

✅ ran here · PostgreSQL 18.6
SELECT relpages, reltuples::int FROM pg_class WHERE relname = 'employees';
 relpages | reltuples 
----------+-----------
      934 |    100000
(1 row)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT salary FROM employees WHERE id = 5000;
                               QUERY PLAN                                
-------------------------------------------------------------------------
 Index Scan using employees_pkey on employees (actual rows=1.00 loops=1)
   Index Cond: (id = 5000)
   Index Searches: 1
   Buffers: shared hit=3
 Planning:
   Buffers: shared hit=35
(6 rows)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT sum(salary) FROM employees;
                         QUERY PLAN                          
-------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=934
   ->  Seq Scan on employees (actual rows=100000.00 loops=1)
         Buffers: shared hit=934
 Planning:
   Buffers: shared hit=3
(6 rows)

The whole table is 934 pages. Finding one employee by primary key touched 3 pages: index pages down to the row, then the heap page. Summing every salary touched all 934. That ratio is the reason indexes exist, and post 3 takes it from there. (hit means the page was already in memory. Pages that came from outside the buffer pool are counted as read.)

#How a page lives in a file

A table is a file, and the file is an array of pages. To read page X, the database needs three things: the file, the offset X × page size, and the length of a page. No lookup is needed, because every page is the same size.

To read pages 2 through 9 of a table with 8 KB pages:

text
offset = 2 × 8192 = 16,384 bytes
length = 8 × 8192 = 65,536 bytes

Here's that exact read against a real table's file. I ran dd inside the container, reading the file the way the database does:

✅ ran here · PostgreSQL 18.6 · reading a table's file directly
SELECT pg_relation_filepath('test');
base/<db>/<table>

$ stat -c '%s bytes' <that file>
229376 bytes, which is 28 pages of 8192 bytes

# pages 2 through 9: skip 2 pages, read 8
$ dd if=<that file> bs=8192 skip=2 count=8 | wc -c
65536

SELECT min(ctid::text) FROM test WHERE page = 2;
(2,1)   (the first row those bytes hold)

#Inside a Postgres page

Here is the layout, read from a real page with the pageinspect extension after each step. Click the steps, then click a line pointer or a row:

A new table has no pages at all, so the first INSERT creates page 0. The page starts with a 24-byte header. The row lands at the very end of the page, and a 4-byte line pointer at the front says where it is. lower marks where the pointers stop and upper where the rows start, and free space is the gap between them.
Page 0 of table t: 8192 byteslower 28 · upper 8160header24 B14 Bfree space8132 byteslive32 Bline pointers grow this way →← rows grow this way
Click a line pointer or a row to read it.
heap_page_items()
lplp_offlp_lent_xmint_xmaxt_ctid
181603211710(0,1)
SELECT ctid, * FROM t
ctididname
(0,1)1Ana
✅ read from a real page on PostgreSQL 18.6

The page layout docs describe five parts:

PartSizeWhat it holds
Page header24 bytesFree-space pointers (lower, upper), the checksum and more
Line pointers4 bytes eachThe offset and length of each row in this page
Free spaceThe restThe gap between pointers and rows
RowsVariableThe data, added from the end of the page backwards
Special spaceVariableEmpty for tables, used by index pages

Three things in that replay are worth stopping on.

The line pointer is a level of indirection. Indexes point at (page, line pointer), not at a byte offset. So a row can move inside its page, and only the pointer changes. After VACUUM repacked the rows, row 3 sat at a different offset and its ctid didn't change. Line pointer 2 even became a redirect to pointer 4, so an index entry for the old version still leads to the current row. That's the Heap Only Tuple trick, which post 14 covers.

Nothing is overwritten. An UPDATE adds a version and a DELETE adds a mark. The space only comes back when VACUUM runs, which is what makes MVCC possible, and also what makes tables bloat.

Index pages use the special space. A table page has none, so special equals the page size. A B-tree page keeps links to its neighbours there:

✅ ran here · PostgreSQL 18.6
CREATE EXTENSION pageinspect;

CREATE TABLE t (id int PRIMARY KEY);

INSERT INTO t SELECT generate_series(1, 1000);

SELECT lower, upper, special FROM page_header(get_raw_page('t', 0));
 lower | upper | special 
-------+-------+---------
   928 |   960 |    8192
(1 row)

SELECT lower, upper, special FROM page_header(get_raw_page('t_pkey', 1));
 lower | upper | special 
-------+-------+---------
  1492 |  2304 |    8176
(1 row)

Now the box version, on the same table shape. This is real pageinspect in your browser:

Open a real pageruns in your browser
pageinspect reads the raw bytes of a page. Try the presets, then delete or update a row and look again.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#How wide can a row be?

The width of your rows decides how many fit in a page, and therefore how much each read brings back:

At 2k bytes of data in each row: 4 ✅ measured on PostgreSQL 18.6

This is why SELECT of a wide table is slower to scan than a narrow one with the same row count, and why the course keeps warning against wide rows.

A row also can't be bigger than a page: the Postgres docs say tuples can't span pages. So what happens to a 1.7 MB text value? It's compressed, and moved out of line to a side table. That's TOAST, triggered once a row passes about 2 KB:

✅ ran here · PostgreSQL 18.6
CREATE TABLE doc (id int, body text);

INSERT INTO doc VALUES (1, repeat('database ', 200000));

SELECT pg_size_pretty(pg_column_size(body)::bigint) AS stored, pg_size_pretty(octet_length(body)::bigint) AS original FROM doc;
 stored | original 
--------+----------
 20 kB  | 1758 kB
(1 row)

SELECT pg_size_pretty(pg_relation_size('doc')) AS main_table, pg_size_pretty(pg_relation_size(reltoastrelid)) AS toast_table FROM pg_class WHERE relname = 'doc';
 main_table | toast_table 
------------+-------------
 8192 bytes | 24 kB
(1 row)

The main table stayed at a single page, and repeated text compressed from 1,758 kB to 20 kB. InnoDB does something similar with overflow pages.

#Reading and writing through memory

Pages don't go straight between disk and query. When the database needs a page it looks in its own buffer pool first, then asks the operating system, which checks its file cache before touching the disk:

Request or acknowledgment

So not every I/O reaches the disk. Hitting the OS cache is why a query can be slow the first time and fast the second, even after the database restarts.

Writes work the other way round. The page is changed in memory, a small log record is forced to disk at commit, and the page itself goes back later, possibly after many more changes. That's the write-ahead log from post 1, seen from the page's side:

DataMetadata

#Heap tables and clustered tables

There are two big ways to organise a table's pages. The difference shapes everything from insert speed to index size.

#Postgres: a heap, and every index on the side

In Postgres rows go wherever there's room, so the heap has no order. Insert ids 3, 1, 2 and that's how they stay:

✅ ran here · PostgreSQL 18.6
CREATE TABLE people (id int PRIMARY KEY, name text);

INSERT INTO people VALUES (3, 'Cara'), (1, 'Ana'), (2, 'Ben');

SELECT ctid, id, name FROM people;
 ctid  | id | name 
-------+----+------
 (0,1) |  3 | Cara
 (0,2) |  1 | Ana
 (0,3) |  2 | Ben
(3 rows)

The primary key is an ordinary index. All indexes are secondary, and each entry stores a physical address.

#InnoDB: the table is the primary key's tree

InnoDB builds the table as a B+Tree on the primary key, and the leaf pages hold whole rows. This is called a clustered index. The MySQL docs say each InnoDB table has one, and if you don't define a primary key it creates a hidden one. Same inserts, different result:

✅ ran here · MySQL 8.4.13
CREATE TABLE people (id int PRIMARY KEY, name text);
Query OK, 0 rows affected (0.04 sec)

INSERT INTO people VALUES (3, 'Cara'), (1, 'Ana'), (2, 'Ben');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

SELECT id, name FROM people;
+----+------+
| id | name |
+----+------+
|  1 | Ana  |
|  2 | Ben  |
|  3 | Cara |
+----+------+
3 rows in set (0.00 sec)

The rows came back in key order without any ORDER BY, because that's how they're stored. Don't rely on that, though: only ORDER BY guarantees an order.

Oracle calls this an index-organized table, and in SQL Server it's a clustered index. Postgres has a CLUSTER command, but the docs are clear it's a one-time reordering: later writes aren't kept in order.

#Two ways to reach a row

You can prove what a secondary index holds. Run the same query on both engines: an index on email only, asking for id.

✅ ran here · PostgreSQL 18.6
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE email = 'user42@example.com';
                     QUERY PLAN                     
----------------------------------------------------
 Index Scan using users_email_idx on users
   Index Cond: (email = 'user42@example.com'::text)
(2 rows)
✅ ran here · MySQL 8.4.13
EXPLAIN SELECT id FROM users WHERE email = 'user42@example.com';
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key       | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | users | NULL       | ref  | idx_email     | idx_email | 403     | const |    1 |   100.00 | Using index |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

Postgres has to visit the heap to get id. MySQL says Using index, meaning it never touched the table, even though id isn't in the index definition. The primary key is in every secondary index entry.

Postgres heapInnoDB clustered
Row orderNonePrimary key order
Lookup by primary keyIndex, then heapOne tree walk, the row is in the leaf
Lookup by secondary keyIndex, then heapSecondary tree, then primary tree
Range scan on primary keyRows may be scatteredRows are adjacent
When a row movesIndexes may need new entriesOnly the primary key tree changes
Cost of a wide primary keyOnly that indexEvery secondary index carries it

This table is the seed of post 14's story about why Uber left Postgres. It also explains why random keys hurt a clustered table: inserts land all over the tree instead of at the end. Post 4 measures that.

#Row stores and column stores

Everything so far stored each row's columns together. There's another option: store each column's values together. The same table, and the same three queries from the course, with the pages counted for real:

SELECT sum(salary) FROM emp
Row store6 pages read
page 1
1AnaRoss1114019802BenShaw222751983
page 2
3CaraTran3335019864DevUeda444851989
page 3
5EliVega5556019926FayWong666951995
page 4
7GusXu7777019988HanaYang888451981
page 5
9IvyZhao99980198410JonAmes1110551987
page 6
11KimBoyd122190199012LeoCole1332651993
Fetched 72 values, used 12.
Column store1 page read
id
123456789101112
first
AnaBenCaraDevEliFayGusHanaIvyJonKimLeo
last
RossShawTranUedaVegaWongXuYangZhaoAmesBoydCole
ssn
111222333444555666777888999111012211332
salary
407550856095704580559065
dob
198019831986198919921995199819811984198719901993
Fetched 12 values, used 12.
This is the column store's home ground: one page holds every salary. The row store reads the whole table and uses one value in six.

The pattern is simple. A row store reads whole rows, so it's ideal when you want whole rows. A column store reads whole columns, so it's ideal when you want a few columns of many rows.

I can show the effect on real Postgres by comparing a wide table with a table of just the one column a query needs, which is what a column store's file for that column amounts to:

✅ ran here · PostgreSQL 18.6 · a column store's advantage, approximated
SELECT relname, relpages FROM pg_class WHERE relname IN ('emp_rows', 'emp_salary_column') ORDER BY relpages DESC;
      relname      | relpages 
-------------------+----------
 emp_rows          |     3456
 emp_salary_column |      885
(2 rows)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT sum(salary) FROM emp_rows;
                                   QUERY PLAN                                   
--------------------------------------------------------------------------------
 Finalize Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=3456
   ->  Gather (actual rows=3.00 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         Buffers: shared hit=3456
         ->  Partial Aggregate (actual rows=1.00 loops=3)
               Buffers: shared hit=3456
               ->  Parallel Seq Scan on emp_rows (actual rows=66666.67 loops=3)
                     Buffers: shared hit=3456
 Planning:
   Buffers: shared hit=11
(12 rows)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT sum(salary) FROM emp_salary_column;
                             QUERY PLAN                              
---------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=885
   ->  Seq Scan on emp_salary_column (actual rows=200000.00 loops=1)
         Buffers: shared hit=885
 Planning:
   Buffers: shared hit=5
(6 rows)

885 pages against 3,456, for the same sum. A real column store does far better, because Postgres still pays about 28 bytes of overhead per row in that narrow table. A real one packs bare values and compresses them. A column of salaries has few distinct values and long runs, and that compresses dramatically.

Row storeColumn store
Best atReads and writes of whole rowsReads of few columns over many rows
WorkloadOLTP: many small transactionsOLAP: few large analytical queries
WritesFast: one row, one placeSlow: one row touches every column's file
CompressionModest, values are mixedExcellent, similar values sit together
AggregatesMust read everythingReads only what it needs
Queries on many columnsEfficientMust reassemble rows
ExamplesPostgres, MySQL, SQL ServerClickHouse, Snowflake, BigQuery, DuckDB

Rows and columns aren't the only choices. The aim is always to pack a page so that one read is as useful as possible for the workload. Document databases store a compressed document the way a row store stores a row, as post 12 shows, and graph databases persist connections so that one page read helps a traversal.

#Page size is a trade-off

Small pagesLarge pages
Reading one rowLess data movedMore data moved
Fit with the deviceCloser to its block sizeSpans many blocks
Metadata overheadHigher, more headers and pointersLower
Page splitsMore frequentLess frequent
A cold read or writeFasterSlower

Postgres fixed its page at 8 KB and InnoDB at 16 KB, though both can be changed when the server is built or initialised.

#What's under the page

The course's video on storage covers the two kinds of disk, and they explain why the industry cares so much about write patterns.

🎓 On a hard disk, rewriting a block in place is fine, and the expensive thing is moving the head. On an SSD random reads are cheap, but a page can't be overwritten. A rewrite goes to a fresh page, and the old block is erased later. Each cell survives a limited number of erase cycles.

This is the argument the course makes against B-trees on SSDs: an index insert can rewrite a page that was only slightly changed, while an append-only structure writes to new space. That thinking led to LSM trees, which post 11 builds.

#Things that can trip you up

  • ctid isn't a stable id. It changes on UPDATE and on VACUUM FULL. Never store one.
  • A DELETE doesn't shrink the file. Space is reused by later rows in the table, and plain VACUUM rarely returns it to the operating system.
  • SELECT * reads big columns you don't need. Out-of-line TOAST values are only fetched if requested, so naming your columns can be much cheaper.
  • Row order without ORDER BY is an accident. Postgres gives insertion order until an update moves a row. InnoDB gives key order until the planner picks another index.
  • A large InnoDB primary key taxes every index. A 36-character UUID string is copied into each secondary index entry.
  • CLUSTER is a one-off. It also takes an exclusive lock while it rewrites the table.
  • "Hit" doesn't mean cheap for every query. shared hit=934 is still 934 pages of work, just without a disk read.

#Reproduce this yourself

Commands assume the pgacid container from post 1.

  1. ✅ Read a real page. Enable the extension and look at any table:
    sql
    CREATE EXTENSION pageinspect;
    SELECT lower, upper, special FROM page_header(get_raw_page('employees', 0));
    SELECT lp, lp_off, lp_len, t_xmin, t_xmax, t_ctid
    FROM heap_page_items(get_raw_page('employees', 0)) LIMIT 5;
    
  2. ✅ Find a table's file with SELECT pg_relation_filepath('employees'); and run dd on it inside the container, as in the offset demo.
  3. ✅ Count pages with EXPLAIN (ANALYZE, BUFFERS) <your query>.
  4. ✅ For the InnoDB tests, start mysql:8.4 as in post 1 and run the people and users examples.
  5. 📘 To change Postgres's page size you must build it yourself with --with-blocksize. InnoDB's is set with innodb_page_size before the data directory is created.

#Glossary

TermMeaning
PageThe fixed-size unit of every read and write
BlockThe file system's or disk's unit, often smaller than a page
HeapTable pages with no particular row order
ctidA row's physical address in Postgres: (page, line pointer)
Line pointer (ItemId)A 4-byte entry at the front of a page, giving a row's offset and length
Buffer poolThe database's own cache of pages in memory
Dirty pageA page changed in memory that isn't yet on disk
TOASTPostgres's way of compressing large values and moving them out of line
Clustered indexA table stored inside the tree of one index, usually the primary key
Secondary indexAny index that isn't the clustered one
OLTP, OLAPWorkloads of many small transactions, or few big analytical queries
Write amplificationPhysical writes exceeding the logical change that caused them

#Summary

A table is a file of fixed-size pages, and the page is the unit of all I/O. Its address is arithmetic, so a read is a file, an offset and a length. Inside a Postgres page, pointers at the front give each row an address that survives moves within the page, while updates add versions rather than overwrite. Postgres keeps rows in an unordered heap, and its indexes hold physical addresses. InnoDB stores rows in the primary key's tree, and its secondary indexes hold the key. Row stores and column stores make different bets about which values are read together.

#Concepts at a glance

ConceptIn one lineWhy it matters
PageSmallest unit of I/OQuery cost is mostly pages touched
Offset arithmeticPage × size gives the position in the fileNo lookup needed to find a page
Line pointerRow's offset within its pageRows can move without changing their address
lower, upperThe two ends of the free spaceShow how full a page is
Row versionsUpdates add, deletes markWhy VACUUM exists
TOASTBig values leave the pageRows can't span pages
Buffer poolPages cached in database memoryWhy a second run is faster
Heap tableRows in no order, indexes on the sidePostgres's model
Clustered tableRows live in the key's treeInnoDB's model, fast key lookups and ranges
Secondary index contentsAn address or a primary keyDecides what a row move costs
Row vs column storeWhat sits next to what in a pageDecides which queries read less

#Test yourself

A table has 100,000 rows in 934 pages. Why did finding one row by primary key touch only 3 pages, and why did a sum touch all 934?

The index let the database walk down a couple of index pages to the row's address, then read one heap page. A sum needs every row, so it must read every page. Query cost tracks pages touched, not rows returned.

What does the ctid (2,5) tell you, and why isn't it a byte offset?

Page 2, line pointer 5. The page gives the file offset: 2 × 8192. The line pointer is an entry at the front of the page holding the row's offset and length. That indirection lets the row move inside the page without changing its address.

You run UPDATE on one row in Postgres, and then look at the page. What has changed?

A new row version was added with a new line pointer. The old version is still there, with xmax set to the updating transaction and its t_ctid pointing at the new version. The free space shrank. Nothing was overwritten, and only VACUUM reclaims the old version.

In InnoDB, an index on email answers SELECT id FROM users WHERE email = ? without touching the table. Why can't Postgres do the same with the same index?

InnoDB's secondary index entries contain the primary key, so id is already in the index. Postgres index entries contain the indexed column and a physical address, so id must be read from the heap. Adding id to the index, for example with INCLUDE, would allow an index-only scan.

Why are column stores bad at updating one row?

Each column lives in its own pages, so changing or inserting one row touches a page per column, and the data is usually compressed in blocks that must be rewritten. A row store writes the row in one place.

#Open questions and gaps

  • The column store demo is an approximation on Postgres, not a real column store. I didn't benchmark one, since the course only discusses the idea.
  • 🎓 The hard disk and SSD descriptions come from the course, except where the box corrects them. I couldn't verify the course's figures for block sizes and endurance, and I ran nothing at that layer.
  • I read InnoDB's layout from the docs and from behaviour. I didn't open an .ibd file byte by byte the way I did for Postgres.

#Sources