Chapter Five · How a Row Is Stored
How a Row Is Stored
Three facts about Cartwheel that the schema cannot explain: inventory holds 12,000 rows in 900 MB, products.attributes averages 3 KB and lives outside the table it belongs to, and SELECT id, price FROM products reads far more disk than two columns account for. Five topics open the file and show what is physically on the page.
The first four chapters treated Postgres as something you send statements to. The schema was designed, the constraints were made real, the migrations shipped without an outage, and the SQL got sharp enough to replace three round trips with one. From here the book turns the machine around and works from the inside out, and this chapter is the first look at a page of actual bytes. Everything in the next four chapters — snapshots, vacuum, indexes, the planner's cost model — is measured in the units defined here.
Nadia has three measurements and no explanation for any of them. inventory has 12,000 rows of three narrow columns and occupies 900 MB, which is roughly 1,700 times what those rows need. products reports 18 MB in the obvious size query while its data directory shows hundreds. And a query naming two columns of products reads disk as though it had named all of them. Nothing in the DDL predicts any of this, because none of it is about the schema — it is about how the engine physically arranges a row and what it does to that arrangement when the row is written to twice.
The five topics build up in order: the 8 KB page and its three regions, then the tuple header whose four fields are the entire basis of multiversion concurrency, then TOAST for the values too big to sit in a row, then the two small side files that make inserts and index-only scans cheap, and finally the data directory itself. Two questions are deliberately left open at the end. Which of two versions of a row a given transaction may see is Chapter 6's subject, and how inventory came to be that size is Chapter 7's. Neither answer can be given honestly without this chapter's vocabulary.