Sub topic 13
Storage strategies and compression methods
This chapter covers the per-column settings that control how TOAST treats large values: the storage strategy and the compression method. It assumes you know the TOAST basics from the earlier chapters (large values are compressed or moved to a side table when a row gets too big). It also assumes you can run SQL in psql. The examples need PostgreSQL 14 or later, and lz4 needs a server built with lz4 support.
Two settings per column
Every column has two separate settings in pg_attribute:
attstorageis the storage strategy. It decides whether the column's values may be compressed and whether they may be moved out of line.attcompressionis the compression method. It decides which algorithm is used when a value is compressed. An empty value means "use the default at the time the value is stored".
The strategy says what is allowed. The method says how compression is done. Changing the method has no effect on a column whose strategy forbids compression.
The four strategies
| Strategy | `attstorage` | Compress? | Move out of line? | Typical use |
|---|---|---|---|---|
| PLAIN | `p` | No | No | Fixed-width types such as `int` and `bigint` |
| EXTENDED | `x` | Yes | Yes | Default for `text`, `bytea`, `jsonb`, and other variable-length types |
| EXTERNAL | `e` | No | Yes | Large values that are already compressed, or that you slice with `substr` |
| MAIN | `m` | Yes | Only as a last resort | Values you want to stay in the main table page |
Only variable-length types (those with a length header, called varlena types) can be TOASTed at all. A fixed-width type must stay PLAIN, and PostgreSQL rejects SET STORAGE for strategies the type does not support.
When the strategy is consulted
TOAST work starts only when a row is larger than about 2 kB. That is one quarter of the page size, controlled by the toast_tuple_target storage parameter. A row below the threshold is stored as written, whatever the column strategies say. A table of many 1 kB text values never touches TOAST.
Once the row exceeds the threshold, PostgreSQL works on the largest values first and repeats until the row fits. In simplified form:
- EXTENDED values are compressed. EXTERNAL values are moved out of line, uncompressed.
- If the row is still too large, EXTENDED values that remain inline are moved out of line.
- MAIN values are compressed in place. Only if the row still does not fit are they moved out of line.
A compression attempt can also fail on its own. Very small values are not worth compressing, and pglz abandons the attempt if it does not save enough space. A value that fails to compress is stored as it was and may still go out of line.
Looking at the current settings
The query below uses the docs table from earlier in the tutorial:
SELECT attname, attstorage, attcompression
FROM pg_attribute
WHERE attrelid = 'docs'::regclass AND attname = 'body';A default text column shows x for attstorage and an empty attcompression. You can also see the strategy in psql with \d+ docs, in the Storage column.
Changing the strategy
ALTER TABLE docs ALTER COLUMN body SET STORAGE EXTERNAL;This command changes only the catalog entry. It does not rewrite the table and does not touch values already stored. Existing rows keep their current form until they are written again.
Use each strategy for a specific reason:
- EXTERNAL suits data that is already compressed (JPEG, PNG, zip files stored in
bytea). Trying to compress it wastes CPU and saves almost nothing. It also speeds upsubstron large text orbyteavalues. An uncompressed out-of-line value can be read by fetching only the chunks that contain the requested range. A compressed value must be decompressed from the start first. - MAIN suits medium-sized values that you read on nearly every query. Keeping them inline avoids an extra lookup in the TOAST table. They are still moved out if the row cannot fit otherwise.
- PLAIN on a varlena column prevents TOAST for that column. This is rarely a good idea, because a row that cannot fit in a page then fails with an error.
You can also set the default strategy for a data type with ALTER TYPE ... SET (STORAGE = ...). New columns of that type use it.
Compression methods
PostgreSQL offers two methods:
| Method | Available | Character |
|---|---|---|
| `pglz` | All versions, always built in | Built-in algorithm. Slower, often compresses a little better on some data. |
| `lz4` | PostgreSQL 14 and later, needs lz4 support at build time | Faster compression and much faster decompression. Usually the better choice for read-heavy tables. |
The results depend on your data, so measure with your own values rather than trusting a general rule. Highly repetitive data compresses well with either method. Random or already compressed data compresses with neither.
You choose the method at two levels:
- The server-wide default is the
default_toast_compressionsetting, which ispglzunless you change it. You can set it inpostgresql.confor per session. - A column can override the default with
SET COMPRESSION.
SET default_toast_compression = 'lz4';
ALTER TABLE docs ALTER COLUMN body SET COMPRESSION lz4;If the server was built without lz4, naming lz4 fails with an error that tells you so.
The method belongs to each stored value
This is the point that most often confuses people. PostgreSQL records the compression method inside each compressed value, in the value's own header. The column setting is only used when a new value is compressed.
As a result:
SET COMPRESSIONdoes not recompress anything. Existing values stay in their old method.- A table can hold a mix of
pglzandlz4values in one column. Reads work either way, because each value says how to decompress itself. - Copying a value unchanged keeps its compression.
INSERT ... SELECTof a compressed value,VACUUM FULL, andCLUSTERall carry the stored bytes over without recompressing.
Checking which method a value uses
The function pg_column_compression reports the method of the stored value. It returns NULL for a value that is not compressed.
CREATE TABLE notes (id int PRIMARY KEY, body text);
ALTER TABLE notes ALTER COLUMN body SET COMPRESSION pglz;
INSERT INTO notes VALUES (1, repeat('abc', 100000));
ALTER TABLE notes ALTER COLUMN body SET COMPRESSION lz4;
INSERT INTO notes VALUES (2, repeat('abc', 100000));
SELECT id,
pg_column_compression(body) AS method,
pg_column_size(body) AS stored_bytes,
octet_length(body) AS raw_bytes
FROM notes
ORDER BY id;Row 1 reports pglz and row 2 reports lz4, even though both inserts used identical text and the column setting is now lz4. The stored_bytes column also shows how much each method saved on this input.
Rewriting old values with the new method
To move existing values to a new method, write them again as new values. Building the value in an expression forces a new datum, which is then compressed using the column's current method:
UPDATE notes SET body = body || '';
SELECT id, pg_column_compression(body) AS method
FROM notes
ORDER BY id;After this, both rows report lz4. Remember what the earlier chapters showed about UPDATE: every updated row creates a new row version, and the old TOAST data stays until VACUUM removes it. Rewriting a large table this way produces a lot of dead data. On a big table, do it in batches and let autovacuum or manual VACUUM keep up.
Tuning the threshold
The toast_tuple_target storage parameter sets the row size at which TOAST starts working, and also the size it tries to reach:
ALTER TABLE notes SET (toast_tuple_target = 4096);Lowering it makes PostgreSQL compress and move values out of line sooner. This keeps the main table narrow, which helps scans that read only small columns. Raising it keeps more data inline, which helps queries that read the large values, at the price of fewer rows per page. Like the other settings here, a change applies only to rows written afterwards.
Common errors
- Expecting
SET STORAGEorSET COMPRESSIONto shrink the table. Neither command rewrites data. Checkpg_column_compressionand sizes before and after. - Setting EXTERNAL and then wondering why the table grew. EXTERNAL turns off compression. Compressible text will take more space in the TOAST table.
- Using
lz4without checking the build. A server without lz4 support rejects the setting. A replica or restored dump on a differently built server can also fail. - Judging by
pg_relation_size('docs')alone. That function counts only the main heap. Usepg_table_sizeto include the TOAST table, andpg_total_relation_sizeto include indexes as well. - Forgetting that small rows never reach TOAST. If every row is under about 2 kB, none of the settings above change anything.
Choosing settings
- Leave text,
jsonb, and similar columns on EXTENDED unless you have a measured reason to change them. - Switch to
lz4for columns that are read often and hold compressible data. Confirm the saving withpg_column_sizeon a sample. - Use EXTERNAL for already compressed binary data and for large values you often slice.
- Use MAIN sparingly, for values of moderate size that nearly every query needs.
- Apply changes before loading data, or rewrite the affected rows afterwards.
Exercise
A table files(id int, content bytea) stores ZIP archives of 1 MB each. The column has the default strategy. You run ALTER TABLE files ALTER COLUMN content SET STORAGE EXTERNAL;. Which rows are affected, and why is EXTERNAL a sensible choice here?
Show answer
No existing rows change, because SET STORAGE only updates the catalog and does not rewrite data. Rows stored from now on are moved out of line without a compression attempt. EXTERNAL fits because ZIP data is already compressed, so trying to compress it again costs CPU and saves almost nothing. It also lets partial reads with substr fetch only the needed chunks.
Exercise
A column was set to SET COMPRESSION lz4 last week. Some old rows still show pglz in pg_column_compression. Why, and how can you convert them?
Show answer
The compression method is stored inside each compressed value, and changing the column setting affects only values compressed afterwards. Old values keep pglz. To convert them, write them again as new values, for example UPDATE t SET col = col || '', in batches, and run VACUUM afterwards to clean up the dead row versions and old TOAST data. VACUUM FULL alone would copy the old compressed bytes unchanged.