Sub topic 7
NULLs, alignment, and padding: why column order matters
This chapter assumes you know what a heap page is, how line pointers and ctid address a tuple, and what the tuple header holds. It also assumes pageinspect is available. Here you will see how the bytes after the fixed header are laid out. Two things decide the size of a row: how NULLs are recorded, and how the alignment rules insert padding between columns.
What follows the fixed header
The fixed tuple header is 23 bytes. Two optional or computed parts come after it, in this order:
- A NULL bitmap, present only if at least one column in that row is NULL.
- Padding up to the next multiple of 8 bytes.
The offset where column data begins is stored in the header field t_hoff. It is always a multiple of 8 (the platform's MAXALIGN). Every tuple also starts at an 8-byte boundary inside the page. This means alignment can be worked out relative to the start of the tuple, and the same rules hold on every page.
The NULL bitmap
The bitmap has one bit per column. A 1 means the column has a value and a 0 means it is NULL. A NULL column stores no data bytes at all. The bitmap costs ceil(columns / 8) bytes, and that cost is paid only by rows that contain a NULL. The header is always rounded up to a multiple of 8, so the cost of the bitmap is often hidden.
| Columns in the table | Header size, row has no NULL | Header size, row has a NULL |
|---|---|---|
| 1 to 8 | 24 bytes | 24 bytes |
| 9 to 72 | 24 bytes | 32 bytes |
| 73 to 136 | 24 bytes | 40 bytes |
Up to 8 columns, NULLs cost nothing extra in the header and save the data bytes. A wider table pays 8 more header bytes in every row that has any NULL. This can outweigh the savings when the NULL column was small.
You can see this with pageinspect:
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE nulls_demo (a int, b int, c int);
INSERT INTO nulls_demo VALUES (1, 2, 3);
INSERT INTO nulls_demo VALUES (1, NULL, 3);
INSERT INTO nulls_demo VALUES (NULL, NULL, NULL);
SELECT lp, lp_len, t_hoff, t_bits
FROM heap_page_items(get_raw_page('nulls_demo', 0))
ORDER BY lp;The expected result:
| lp | lp_len | t_hoff | t_bits |
|---|---|---|---|
| 1 | 36 | 24 | (null) |
| 2 | 32 | 24 | 101 |
| 3 | 24 | 24 | 000 |
Row 1 has no bitmap, so t_bits is empty. It stores 24 header bytes and 12 data bytes. Row 2 has a bitmap 101: column b is NULL and takes no data bytes. It stores 24 + 8 = 32 bytes. Row 3 is all header.
Alignment rules
Each data type declares an alignment requirement, which you can read from pg_type.typalign. A value must start at an offset that is a multiple of its alignment. If the next free byte is not a multiple, PostgreSQL inserts zero bytes of padding.
SELECT typname, typlen, typalign
FROM pg_type
WHERE typname IN ('bool', 'int2', 'int4', 'int8', 'float8',
'timestamptz', 'text', 'numeric')
ORDER BY typlen DESC, typname;The typalign codes mean:
| Code | Alignment | Example types |
|---|---|---|
| `c` | 1 byte (none) | `bool` |
| `s` | 2 bytes | `int2` |
| `i` | 4 bytes | `int4`, `text`, `numeric` |
| `d` | 8 bytes | `int8`, `float8`, `timestamptz` |
A variable-length type such as text has a typlen of -1. Its alignment depends on the form it is stored in. A short value (up to 126 bytes of data) uses a 1-byte length header and needs no alignment at all. A longer value uses a 4-byte header and is 4-byte aligned.
Padding in practice
Take the row (boolean, bigint, boolean, bigint). The data starts at offset 0 (relative to t_hoff):
atakes 1 byte at offset 0.bneeds offset 8, so 7 bytes of padding come first, then 8 bytes of data.ctakes 1 byte at offset 16.dneeds offset 24, so another 7 bytes of padding come first, then 8 bytes of data.
That makes 32 data bytes, of which 14 are padding. If the columns are reordered as (bigint, bigint, boolean, boolean), the data takes 8 + 8 + 1 + 1 = 18 bytes and has no padding between columns.
Measuring the difference
This script builds both tables with 100,000 rows each, then compares them:
DROP TABLE IF EXISTS padded, compact;
CREATE TABLE padded (a boolean, b bigint, c boolean, d bigint);
CREATE TABLE compact (b bigint, d bigint, a boolean, c boolean);
INSERT INTO padded SELECT true, g, true, g FROM generate_series(1, 100000) g;
INSERT INTO compact SELECT g, g, true, true FROM generate_series(1, 100000) g;
SELECT pg_relation_size('padded') AS padded_bytes,
pg_relation_size('compact') AS compact_bytes;
SELECT 'padded' AS tbl, lp_len, t_hoff
FROM heap_page_items(get_raw_page('padded', 0)) WHERE lp = 1
UNION ALL
SELECT 'compact', lp_len, t_hoff
FROM heap_page_items(get_raw_page('compact', 0)) WHERE lp = 1;lp_len reports 56 for padded and 42 for compact. Both have t_hoff of 24. The page stores each tuple rounded up to a multiple of 8, plus a 4-byte line pointer:
padded: 56 + 4 = 60 bytes per row. A page has 8168 usable bytes after the 24-byte page header, so 136 rows fit. That gives 736 pages, or 6,029,312 bytes.compact: 42 rounds up to 48, plus 4 = 52 bytes per row. 157 rows fit per page. That gives 637 pages, or 5,218,304 bytes.
Your numbers should match or come very close. The saving is about 13%, and it comes from reordering columns alone. The same saving applies to every index-free scan, every cache page and every backup of the table.
A rule of thumb for column order
For a new table, order columns like this:
- Fixed-width columns with 8-byte alignment (
bigint,timestamptz,float8). - Then 4-byte columns (
int,date). - Then 2-byte and 1-byte columns (
smallint,boolean). - Variable-length columns (
text,numeric,jsonb) last.
Putting variable-length columns last has a second benefit besides padding. PostgreSQL caches column offsets while reading a tuple. The cache works only up to the first NULL or variable-length column, so later columns need a walk through the preceding values to find. Keeping fixed-width, NOT NULL columns at the front makes the common columns cheap to reach.
Frequently NULL columns are best placed late, after the fixed columns that are always present.
Where the gain is small
Do not expect a large saving everywhere. The gain depends on:
- Row width. A table whose rows are mostly
texthas few alignment gaps, since short text values need no alignment. - Mixed small and large types. The biggest waste comes from a narrow type followed by an 8-byte type, as in the example above.
- Row count. On a table with thousands of rows, the saving is a few pages. On hundreds of millions of rows, it is a real storage and cache cost.
Summary
- A row's NULLs are tracked in a bitmap that exists only when a NULL is present. It costs
ceil(columns / 8)bytes, hidden inside the 8-byte rounding oft_hofffor tables up to 8 columns. - NULL columns store no data. Above 8 columns, the first NULL in a row can add 8 header bytes.
- Each type has an alignment (
c,s,i,d). Padding appears whenever a value does not start on a multiple of its alignment. - Ordering columns from widest alignment to narrowest, with variable-length columns last, removes padding between columns and speeds up column access.
Exercise
A table has columns (a smallint, b bigint, c smallint, d int), in that order, all NOT NULL. What is the tuple length (lp_len) of a row? What is it if the order is (b, d, a, c)?
Show answer
In the original order: a at offset 0 (2 bytes), b padded to offset 8 (8 bytes, ends at 16), c at offset 16 (2 bytes, ends at 18), d padded to offset 20 (4 bytes, ends at 24). Data is 24 bytes, so lplen is 24 + 24 = 48. In the order (b, d, a, c): 8 + 4 + 2 + 2 = 16 data bytes, so lplen is 24 + 16 = 40.
Exercise
A table has ten int columns. One row has no NULLs and another row has a single NULL. Compare their lp_len values and explain the result.
Show answer
The row with no NULLs has a 24-byte header (no bitmap) and 40 data bytes, so lplen is 64. The row with one NULL needs a 2-byte bitmap (ceil(10 / 8)), and 23 + 2 = 25 rounds up to a thoff of 32. It stores 36 data bytes, so lp_len is 32 + 36 = 68. The NULL row is larger, because the 8 extra header bytes outweigh the 4 data bytes saved.