Video in progress
What is TOAST, and how do big text or jsonb columns affect query speed?
A Postgres page is 8 KB, so values larger than about 2 KB are compressed and moved in chunks into a separate TOAST table. That keeps the main table compact, but if SELECT * also pulls the big column, every row costs an extra read and decompression.
📖 Answer
TOAST (The Oversized-Attribute Storage Technique) creates a hidden pg_toast.pg_toast_<oid> table for each table. Only a pointer stays in the main row.
Practical consequences:
-
SELECT *is expensive. A list page needsid, title, but a JPA entity also loads the 50 KBbodyjsonb. For every row there's a read from TOAST and detoasting. A DTO projection or a separate entity solves it. -
A small change in jsonb is rewritten in full. Even if you change one field in a 100 KB document with
jsonb_set, the whole value is written as a new version. It's better to move a frequently updated field into a regular column. -
Bloat is hidden. The main table looks small, while TOAST is ten times bigger:
SELECT pg_size_pretty(pg_relation_size('document')) AS main,
pg_size_pretty(pg_total_relation_size('document')) AS total_with_toast_and_indexes;
- Since PG14 you can choose the compression algorithm:
ALTER TABLE document ALTER COLUMN body SET COMPRESSION lz4;, which is faster than the defaultpglz.
If a column already stores compressed data (an image, a zip), you can turn off the pointless compression attempt with SET STORAGE EXTERNAL.
Sign up to mark studied questions and save your progress.