Sub topic 4
Adding and renaming enum values
An enum type is a fixed list of labels, but real systems change. A shop adds a refunded order status, and a team decides cancelled should be spelled canceled. This chapter covers the two ALTER TYPE commands that handle these changes without rewriting your tables: ADD VALUE and RENAME VALUE. It also covers the transaction restriction on new values, which is the usual cause of failed migrations.
It assumes you can write CREATE TYPE ... AS ENUM, you know that enum values sort by declaration order, and you know what a transaction block is (BEGIN ... COMMIT). The examples use the order_status type and orders table from the first chapter on enums. Run this setup if you are starting fresh:
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped', 'delivered', 'cancelled');
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);
INSERT INTO orders (status) VALUES ('paid'), ('shipped');Why these two operations are cheap
PostgreSQL does not store the label text in each row. A row stores a small internal identifier for the label, and the labels live in the system catalog pg_enum. Two consequences follow:
- Adding a label inserts one row into
pg_enum. No table is scanned or rewritten. - Renaming a label updates one row in
pg_enum. The stored rows still point to the same identifier, so they display the new label automatically.
This makes both operations fast on tables of any size. It also explains the one awkward rule in this chapter. A newly added label is a catalog row that other transactions may not be able to see yet, so PostgreSQL restricts how it can be used until the change commits.
Adding a value
The basic form appends a label at the end of the ordering:
ALTER TYPE order_status ADD VALUE 'refunded';To place the label somewhere else, name a neighbor with BEFORE or AFTER. This example also uses IF NOT EXISTS, which makes the command safe to run twice:
ALTER TYPE order_status ADD VALUE IF NOT EXISTS 'refunded' AFTER 'delivered';If you already ran the first form, the second command only emits a notice that the label exists and skips it. The existing label stays where it was, at the end, so IF NOT EXISTS never moves a label.
The position matters because enum values compare by declaration order. After the second form, status >= 'paid' AND status < 'refunded' includes delivered, and ORDER BY status puts refunded right after delivered. If you appended instead, refunded would sort after cancelled, which is probably not what a status lifecycle wants. Decide the position at the time you add the label, because you cannot move a label later. The only way to reorder is to replace the type, which the removal chapter covers.
Check the result with enum_range:
SELECT enum_range(NULL::order_status);{pending,paid,shipped,delivered,refunded,cancelled}Errors you will meet
| Command | Error message |
|---|---|
| `ADD VALUE 'paid'` when `paid` exists | `enum label "paid" already exists` |
| `ADD VALUE 'x' AFTER 'nope'` when `nope` does not exist | `"nope" is not an existing enum label` |
| `ADD VALUE` with a label longer than 63 bytes | `invalid enum label` (labels share the 63-byte identifier limit) |
IF NOT EXISTS suppresses only the first error. A missing neighbor label is always an error.
How the sort position is stored
Each pg_enum row has a enumsortorder column, a real (floating point) number. You can look at it directly:
SELECT enumlabel, enumsortorder
FROM pg_enum
WHERE enumtypid = 'order_status'::regtype
ORDER BY enumsortorder; enumlabel | enumsortorder
-----------+---------------
pending | 1
paid | 2
shipped | 3
delivered | 4
refunded | 4.5
cancelled | 5When you add a label between two others, PostgreSQL gives it a number halfway between its neighbors (4.5 here). Appending uses the highest number plus one. This is why insertion in the middle does not disturb existing rows.
The design has a cost, which the PostgreSQL documentation states. Comparisons involving a label added with BEFORE or AFTER can be slower than comparisons between original labels. The same can happen after an append if the system's object identifier counter has wrapped around since the type was created. Original labels have identifiers that already sort in label order, so PostgreSQL can compare them directly. For labels added out of order, the comparison has to look up enumsortorder in the catalog. The slowdown is small, and most applications never notice it. It shows up only in comparison-heavy queries over very large tables, such as sorting millions of rows by an enum column that has had many mid-list insertions. If you expect that workload, consider planning the label order carefully up front.
The transaction restriction
Most migration tools wrap each migration file in a transaction. This is where ADD VALUE surprises people. The rules depend on your PostgreSQL version:
- Before PostgreSQL 12,
ALTER TYPE ... ADD VALUEcould not run inside a transaction block at all. It failed immediately withALTER TYPE ... ADD cannot run inside a transaction block. - From PostgreSQL 12, it can run inside a transaction block, but the new value cannot be used until that transaction commits.
"Used" is broad. It covers inserting the value, comparing against it, casting a literal to the enum type, or using it in an index predicate or default expression. Here is what the failure looks like:
BEGIN;
ALTER TYPE order_status ADD VALUE IF NOT EXISTS 'refunded' AFTER 'delivered';
INSERT INTO orders (status) VALUES ('refunded');ERROR: unsafe use of new value "refunded" of enum type order_status
HINT: New enum values must be committed before they can be used.ROLLBACK;The restriction exists because other sessions cannot see an uncommitted label. If the new value could be stored in a row or an index before commit, and the transaction then rolled back, the data would reference a label that no longer exists. PostgreSQL avoids that by refusing the use.
There is one exception. If the enum type itself was created earlier in the same transaction, its new values are safe to use immediately, because no other session can see the type either. A migration that creates a type and extends it in one step works as a single unit.
Structuring migrations around the rule
Keep the ADD VALUE and anything that uses the new value in separate transactions. Two common patterns:
- Put
ALTER TYPE ... ADD VALUEalone in its own migration file. The migration commits before the next one starts. Use the next migration to backfill rows, add a default, or create a partial index that mentions the new label. - Run the statement outside a transaction. In
psql, autocommit does this for you when you do not typeBEGIN.
A rolled-back transaction also rolls back the added value. After a failed migration you do not need to clean up a half-added label. Running the migration again with IF NOT EXISTS is still a good habit, because it makes reruns and manual fixes safe.
Renaming a value
RENAME VALUE changes a label in place. It needs PostgreSQL 10 or later:
ALTER TYPE order_status RENAME VALUE 'cancelled' TO 'canceled';The label's position in the ordering does not change, and neither do any stored rows. A row that held cancelled now reads as canceled. You can confirm it:
SELECT enum_range(NULL::order_status);{pending,paid,shipped,delivered,refunded,canceled}Unlike ADD VALUE, a rename has no restriction on use within the same transaction. It can run in a transaction block, and you can use the new label right afterward. Other sessions see the old name until you commit.
The two errors are the mirror of those for ADD VALUE. Renaming a label that does not exist fails with "x" is not an existing enum label. Renaming to a label that already exists fails with enum label "x" already exists. There is no IF EXISTS form, so a rename migration is not safe to rerun. If you need that, check pg_enum first in a DO block.
What a rename does not update
PostgreSQL updates anything that refers to the label through the catalog. That covers stored rows, and also parsed expressions such as column defaults, CHECK constraints, and partial index predicates. For these, the old label was stored as a reference to the same pg_enum entry, so they display the new spelling after the rename.
Anything that holds the old label as plain text is not updated:
- Function bodies written as strings, such as PL/pgSQL and SQL functions defined with
$$ ... $$. A body that saysWHERE status = 'cancelled'still contains that literal. It will fail withinvalid input value for enum order_status: "cancelled"the next time it runs. - Application code, ORM models, API documentation, and reporting queries.
- Rows in other tables that store the label as
text, such as an audit log or an events table. - Views are safe, because PostgreSQL stores a view's query in parsed form. A view that compared against the old label displays the new one.
Search function definitions before renaming. This query finds candidates in user-defined functions:
SELECT n.nspname, p.proname
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE p.prosrc LIKE '%cancelled%'
AND n.nspname NOT IN ('pg_catalog', 'information_schema');Run it before the rename, with the old spelling. After the rename, those functions are already broken.
Renaming is also a deployment problem. Between the moment the migration commits and the moment the new application version starts, old code sends cancelled and fails. For a zero-downtime change, a safer sequence is:
- Add the new label (
ALTER TYPE ... ADD VALUE 'canceled') and commit. - Deploy application code that writes the new label and reads both.
- Update existing rows with
UPDATE orders SET status = 'canceled' WHERE status = 'cancelled'. - Stop reading the old label, then leave it in place. You cannot remove it without replacing the type.
If a short window of errors is acceptable, a plain RENAME VALUE is simpler and keeps the type clean.
Renaming the type itself
ALTER TYPE order_status RENAME TO order_state renames the type. Columns follow automatically, because they reference the type by identifier. As with values, function bodies written as text that mention the type name, such as $$ SELECT 'paid'::order_status $$, will break, and so will application casts.
Comparing the operations
| Operation | Runs in a transaction block | New label usable in the same transaction | Rewrites table rows |
|---|---|---|---|
| `ADD VALUE` | Yes, on PostgreSQL 12 or later | No, unless the type was created in the same transaction | No |
| `RENAME VALUE` | Yes | Yes | No |
| `RENAME TO` (the type) | Yes | Not applicable | No |
What you cannot do
PostgreSQL has no DROP VALUE and no command to move a label to a different position. Both require the replacement procedure: create a new type with the labels you want in the order you want, convert the column through text, and swap the names. That procedure, and its traps with defaults and dependent objects, is the subject of the next chapter.
Because removal is hard, adding a value is a one-way door. Add labels deliberately. If a label may be experimental, consider whether a lookup table, covered in the last chapter, fits better than an enum.
Quick checklist
- Choose the position with
BEFOREorAFTERif the order matters for comparisons orORDER BY. - Use
IF NOT EXISTSonADD VALUEso the migration can be rerun. - Commit the
ADD VALUEbefore any statement that uses the new label. - Before a rename, search function bodies and application code for the old spelling.
- Verify with
enum_rangeor thepg_enumquery.
Exercise
You run this migration file, wrapped in a single transaction by your migration tool, on PostgreSQL 15: ALTER TYPE order_status ADD VALUE 'on_hold' AFTER 'paid'; followed by UPDATE orders SET status = 'on_hold' WHERE id = 1;. What happens, why, and how do you fix it?
Show answer
The UPDATE fails with unsafe use of new value "on_hold" of enum type order_status, and the whole transaction rolls back, so the label is not added either. PostgreSQL does not allow a new enum value to be used until the transaction that added it commits, because other sessions cannot see an uncommitted label. Fix it by moving the ALTER TYPE into its own migration (or a non-transactional step) so it commits first, and put the UPDATE in a later migration.
Exercise
After ALTER TYPE order_status RENAME VALUE 'cancelled' TO 'canceled';, a nightly report that calls a PL/pgSQL function containing WHERE status = 'cancelled' starts failing, while a view defined with WHERE status = 'cancelled' keeps working. Why do the two behave differently?
Show answer
A view stores its query in parsed form, where the literal is a reference to the enum label's catalog entry, so it follows the rename. The PL/pgSQL function body is stored as plain text and the literal 'cancelled' is only converted to the enum type when the function runs. After the rename that label no longer exists, so the cast raises invalid input value for enum order_status: "cancelled". Update the function body to use 'canceled'.
Exercise
You need a new label refunded placed between delivered and cancelled, and your deploy script may be rerun after a partial failure. Write the statement, and say what a second run does.
Show answer
ALTER TYPE order_status ADD VALUE IF NOT EXISTS 'refunded' AFTER 'delivered'; On the second run the label already exists, so PostgreSQL emits a notice and skips the command without an error. It does not move the label.