Sub topic 5
Enum storage size and label limits
This chapter covers what an enum value costs on disk, how PostgreSQL turns it back into a label, and the limits on label text. It assumes you can create and use an enum type and have seen ALTER TYPE ... ADD VALUE. You should also know basic psql usage and that PostgreSQL has system catalogs such as pg_type.
What an enum value is on disk
A column of an enum type does not store the label text. It stores a 4-byte number, and PostgreSQL looks up the label through a system catalog when it needs to print the value.
The catalog is pg_enum. It holds one row per label, and each row has its own object identifier (OID). An OID is a 4-byte unsigned integer that PostgreSQL uses to identify catalog rows. The OID of the pg_enum row is the value stored in your table.
The columns of pg_enum that matter here:
| Column | Meaning |
|---|---|
| `oid` | The identifier stored in table rows and indexes |
| `enumtypid` | The OID of the enum type this label belongs to |
| `enumsortorder` | A `real` number that defines the label's position in the ordering |
| `enumlabel` | The label text |
You can see all of this for a small type:
CREATE TYPE ticket_state AS ENUM ('open', 'in_progress', 'resolved', 'closed');
SELECT oid, enumsortorder, enumlabel
FROM pg_enum
WHERE enumtypid = 'ticket_state'::regtype
ORDER BY enumsortorder;The oid values are arbitrary numbers assigned when the type was created. They differ between databases and between runs, so never write application code that depends on them.
The type's own entry in pg_type confirms the fixed width:
SELECT typname, typlen, typalign, typstorage
FROM pg_type
WHERE typname = 'ticket_state';The result is typlen = 4, typalign = i, and typstorage = p. In order:
typlen = 4means every value takes exactly 4 bytes. It is fixed-width, with no length header.typalign = imeans the value is aligned to a 4-byte boundary, asintegeris.typstorage = pmeans the value is never compressed or moved out of line (TOAST), because it is too small to need either.
Comparing the size with other representations
The 4 bytes are the same whether your label is 'open' or a 40-character name. A text column pays for every character, plus a length header. Use pg_column_size to see the size of a single value:
SELECT
pg_column_size('open'::ticket_state) AS enum_open,
pg_column_size('in_progress'::ticket_state) AS enum_in_progress,
pg_column_size('open'::text) AS text_open,
pg_column_size('in_progress'::text) AS text_in_progress,
pg_column_size(1::smallint) AS smallint_value,
pg_column_size(1::integer) AS integer_value;Typically you see 4 and 4 for the enum, 5 and 12 for the text values (the characters plus a 1-byte header for short strings), 2 for smallint, and 4 for integer. The enum is the same size as integer, larger than smallint, and smaller than most text labels.
This is a per-value measurement. What you pay in a real table also depends on row layout, so measure a table. The next script builds two tables of 500,000 rows with the same data, one using text and one using the enum, and compares the heap and the index sizes.
CREATE TABLE tickets_text (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
state text NOT NULL
);
INSERT INTO tickets_text (state)
SELECT (ARRAY['open', 'in_progress', 'resolved', 'closed'])[1 + g % 4]
FROM generate_series(1, 500000) AS g;
CREATE TABLE tickets_enum (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
state ticket_state NOT NULL
);
INSERT INTO tickets_enum (state)
SELECT state::ticket_state
FROM tickets_text
ORDER BY id;
CREATE INDEX tickets_text_state_idx ON tickets_text (state);
CREATE INDEX tickets_enum_state_idx ON tickets_enum (state);
VACUUM ANALYZE tickets_text;
VACUUM ANALYZE tickets_enum;
SELECT
'text' AS variant,
pg_size_pretty(pg_relation_size('tickets_text')) AS heap,
pg_size_pretty(pg_relation_size('tickets_text_state_idx')) AS state_index
UNION ALL
SELECT
'enum',
pg_size_pretty(pg_relation_size('tickets_enum')),
pg_size_pretty(pg_relation_size('tickets_enum_state_idx'));Expect the enum table to be smaller, but not dramatically. Each row carries a header of about 24 bytes, and PostgreSQL pads rows to 8-byte boundaries, so part of the saving disappears into padding. The index difference is usually a bit larger in relative terms, because an index entry is small and the label bytes are a big share of it. A btree index on a low-cardinality column, one with only a few distinct values like state, also compresses duplicate keys in recent PostgreSQL versions, which narrows the gap further.
What this means in practice
- Do not choose an enum only to save space. For most tables the saving is a few bytes per row.
- The saving matters most in wide, very large tables, such as event logs with billions of rows, where a status column repeats in both the heap and several indexes.
- If you want a 2-byte or 4-byte code and want to keep the labels in your own table, a lookup table with a
smallintkey gives similar sizes. The final chapter compares these options in full.
Enum values and ordering internals
The label is separate from the stored number, and so is the order. The stored OID says which label a value is. The enumsortorder column says where that label sits in the type's ordering.
When you create a type, PostgreSQL assigns sort positions 1, 2, 3, ... in declaration order. When you insert a label with ADD VALUE ... BEFORE or AFTER, it needs a position between two existing ones, so it picks a fractional number. Nothing in existing rows changes. Only a new pg_enum row appears.
ALTER TYPE ticket_state ADD VALUE 'on_hold' AFTER 'in_progress';
SELECT oid, enumsortorder, enumlabel
FROM pg_enum
WHERE enumtypid = 'ticket_state'::regtype
ORDER BY enumsortorder;The new label on_hold gets a sort order of 2.5. Its OID is larger than the OIDs of the labels that come after it in order. When the OIDs of a type's labels no longer increase with the sort order, a comparison cannot just compare the two stored numbers. PostgreSQL then consults a cached copy of the sort order for the type. This is handled for you and is cheap, but it explains why ORDER BY on an enum is a comparison of sort positions, not a comparison of the stored OIDs and not alphabetical text.
This is also why renaming a label is free: RENAME VALUE changes enumlabel in one pg_enum row, and no table row is touched.
Two consequences worth remembering:
- Enum values are never physically removed from
pg_enumbyALTER TYPE. There is noDROP VALUE. A stored number must always resolve to a row, which is why the chapter on removing values uses a type replacement instead. - Every label permanently uses one OID from the cluster-wide OID counter. That is not a concern for normal enums with tens of labels. It is a reason not to model thousands of values, or labels that change constantly, as enum labels.
Label limits
A label is an identifier-like string stored in a name-sized slot. The limit is the same as for identifiers such as table names:
- A label can be at most 63 bytes long (the compile-time constant
NAMEDATALENminus 1, whereNAMEDATALENis 64 in standard builds). - The limit is in bytes, not characters. A label with multibyte characters reaches it sooner.
- A longer label is rejected, both in
CREATE TYPEand inALTER TYPE ... ADD VALUE.
Try it. The DO block builds the statement dynamically so that you can generate a label of an exact length:
DO $$
BEGIN
EXECUTE format('CREATE TYPE label_ok AS ENUM (%L)', repeat('x', 63));
RAISE NOTICE 'a 63-byte label was accepted';
END
$$;
DO $$
BEGIN
EXECUTE format('CREATE TYPE label_too_long AS ENUM (%L)', repeat('x', 64));
END
$$;The first block succeeds. The second fails with an error like this:
ERROR: invalid enum label "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
DETAIL: Labels must be 63 bytes or less.Because the limit counts bytes, check a multibyte label with octet_length:
SELECT
length('é') AS characters,
octet_length('é') AS bytes_in_utf8;In a UTF-8 database, é is one character and two bytes. A label of 32 of these is 64 bytes and fails, while 31 fit. If your labels are machine codes such as in_progress, the limit never matters. It matters when labels are human-readable sentences in languages that use multibyte characters.
Label matching rules
The limit is not the only rule to know. These behaviors cause everyday errors:
- Labels are case-sensitive.
'Paid'and'paid'are different labels, and casting a string that matches no label exactly fails. - Whitespace is part of the label.
'paid 'with a trailing space is a different label from'paid'. - Duplicate labels in one type are rejected.
- Input is checked against the labels at the time of the cast.
SELECT 'open'::ticket_state; -- works
SELECT 'Open'::ticket_state; -- fails
SELECT 'open '::ticket_state; -- failsThe failing statements raise invalid input value for enum ticket_state: "Open". Treat this error as an input validation problem. If your application sends user-supplied text, validate it, or catch the error, instead of letting it surface as a server error.
Looking up size and label facts from the catalog
You can build a quick report of any enum type from the catalogs. This is useful when you review a schema and want to know how close any label is to the limit, or how many labels a type has:
SELECT
t.typname AS enum_type,
count(*) AS label_count,
max(octet_length(e.enumlabel)) AS longest_label_bytes,
t.typlen AS stored_bytes_per_value
FROM pg_type AS t
JOIN pg_enum AS e ON e.enumtypid = t.oid
WHERE t.typtype = 'e'
GROUP BY t.typname, t.typlen
ORDER BY t.typname;The filter typtype = 'e' selects enum types. The stored_bytes_per_value column is always 4.
To find which columns in the current database use a given enum, join through pg_attribute:
SELECT
c.relname AS table_name,
a.attname AS column_name
FROM pg_attribute AS a
JOIN pg_class AS c ON c.oid = a.attrelid
WHERE a.atttypid = 'ticket_state'::regtype
AND a.attnum > 0
AND NOT a.attisdropped
AND c.relkind = 'r';Run this before you plan a type replacement, because every column it lists must be converted.
Limits that do not exist, and ones that do
It helps to separate real limits from assumptions:
| Question | Answer |
|---|---|
| How many bytes does a value take? | 4, always |
| How long can a label be? | 63 bytes |
| Is there a small fixed maximum number of labels? | No fixed small cap is documented. Practical limits come from OID use and from how you manage the type |
| Can you remove a label with `ALTER TYPE`? | No |
| Can you change a label's sort position? | Not directly. You can add a new label at the position you want, or replace the type |
| Is a label case-insensitive? | No |
| Do enum comparisons cross types? | No. Two different enum types cannot be compared without casting through `text` |
The last point is an easy trap. Two enum types that happen to have the same labels are different types. To compare or join across them, cast to text, which also gives up the enum ordering:
CREATE TYPE priority_a AS ENUM ('low', 'high');
CREATE TYPE priority_b AS ENUM ('low', 'high');
SELECT 'low'::priority_a::text = 'low'::priority_b::text AS same_label;Common mistakes
- Using the OID as a key. The OID is internal and differs per database. Use the label.
- Expecting a large space saving. Measure your own table. Alignment padding often absorbs much of the difference.
- Using long descriptive sentences as labels. Labels are codes. Keep descriptions elsewhere, for example in a lookup table or in application translations.
- Counting characters instead of bytes for non-ASCII labels.
- Ignoring case and spaces when loading data from CSV files or user input.
- Expecting
ADD VALUEto reorder old rows. It only inserts a new label at a position. Existing rows keep their stored numbers.
Cleaning up
Remove the demo objects when you are done:
DROP TABLE IF EXISTS tickets_text, tickets_enum;
DROP TYPE IF EXISTS ticket_state, label_ok, priority_a, priority_b;Exercises
Exercise
A table has 200 million rows and a status column of an enum type with the labels 'queued', 'running', 'failed', and 'done'. How many bytes does each stored status value take, and does the answer change if you rename 'running' to 'inprogresswithamuchlongername'?
Show answer
Each value takes 4 bytes, because the column stores the OID of the matching pg_enum row and not the label text. Renaming the label changes only the enumlabel in one pg_enum row, so the stored size is still 4 bytes and no table rows are rewritten. The new label is 36 bytes, which is below the 63-byte limit, so the rename is accepted.
Exercise
You run ALTER TYPE ticket_state ADD VALUE 'waiting_for_the_customer_to_reply_with_the_requested_information' and PostgreSQL rejects it. What is the cause, how can you confirm it, and what would you do?
Show answer
The label is longer than 63 bytes, so PostgreSQL raises invalid enum label with the detail Labels must be 63 bytes or less. Confirm with SELECT octet_length('waiting_for_the_customer_to_reply_with_the_requested_information');, which returns 66. Choose a shorter code such as waiting_on_customer and keep the long description in application text or a lookup table.
Exercise
Write a query that lists every enum type in the current database with its number of labels and its longest label in bytes.
Show answer
SELECT t.typname, count(*) AS labelcount, max(octetlength(e.enumlabel)) AS longestlabelbytes FROM pgtype AS t JOIN pgenum AS e ON e.enumtypid = t.oid WHERE t.typtype = 'e' GROUP BY t.typname ORDER BY t.typname;