1.3 When a Record Is Larger Than a Page
What happens when a single record is larger than a page? Values such as a long post body, a JSON document, or an image sometimes cannot be stored in one 8KB page.
In this case, the large value is kept in a separate storage area, and the original row holds only location information saying "this value is over there". The large value is split into pieces or compressed and stored separately, and the original row keeps only a pointer to its location. The name differs by database. PostgreSQL calls it TOAST, InnoDB calls it off-page storage, and Oracle and SQL Server call it a LOB storage structure.
Figure 1-3. Storage structure of PostgreSQL TOAST
flowchart TB
A["Row is too large for a page"] --> B["① Try to compress the large value"]
B -->|"Small enough after compression"| C["Stored as is in the main table's row"]
B -->|"Still large after compression"| D["② Split the large value into pieces of about 2KB"]
subgraph T ["TOAST table"]
T1["Chunk 1 (about 2KB)"]
T2["Chunk 2 (about 2KB)"]
T3["Chunk N"]
end
D --> T1
D --> T2
D --> T3
D --> E["③ Only a TOAST pointer<br/>remains in the main table's row"]
E -.->|"On lookup, follow the pointer to read the chunks"| T1
The figure shows, from top to bottom, the order in which PostgreSQL stores a row that is too large.
- When a row becomes too large for a page, PostgreSQL first tries to compress the large value (①). If compression alone makes it small enough, the value stays in the main table's row as is.
- If it is still large after compression, the large value is split into pieces of about 2KB (②). These chunks are stored separately in a dedicated TOAST table at the lower right (chunk 1, chunk 2, ..., chunk N).
- Only a pointer for finding those chunks remains in the main table's row (③).
- The dotted arrow is the path at lookup time. A query that needs the large value follows the row's pointer, reads the chunks in the TOAST table, and reassembles the original value.
One fact is worth remembering here. When a table has a column holding large values and you read all columns with SELECT *, the database must follow the pointers to the separate storage and read all the large values. If you name only the columns you need, that storage sometimes does not have to be touched at all. For example, if you need only the name and mobile number from a user table but use * and so also pull in the user's image column, unnecessary page reads occur. Minimizing the number of pages read from disk is important, because disk input/output (I/O) is very expensive compared with in-memory operations.