Sub topic 6
Removing a value by replacing the type
PostgreSQL lets you add and rename enum labels, but it has no command to remove one. This chapter shows the supported way to remove a label: build a new enum type without it, move every dependent column to the new type, and retire the old type. It also covers what blocks that procedure and how to run it with the least risk.
This chapter assumes you can create and alter enum types (including ALTER TYPE ... ADD VALUE and RENAME VALUE), read basic transaction syntax (BEGIN, COMMIT), and know that ALTER TABLE ... ALTER COLUMN ... TYPE can rewrite a table.
Why there is no DROP VALUE
An enum label is stored as a row in the system catalog pg_enum. Every stored enum value in your tables is a small reference to that row. If PostgreSQL let you delete a label, any table row that still used it would point at nothing. Checking this would mean scanning every column of that type in every table, including tables the current user cannot see. PostgreSQL does not offer that check, so ALTER TYPE ... DROP VALUE does not exist.
You may find advice online to delete the row from pg_enum directly. Do not do this. It can leave rows that fail to print, compare, or dump. A dump taken in that state may not restore.
The supported route has four parts:
- Make sure no row uses the value you want to remove.
- Create a second enum type without the value.
- Convert each column that uses the old type to the new type.
- Drop the old type and give the new type the old name.
The starting point
The examples use the orders table from earlier in this tutorial. By now the type has gained a refunded label, and cancelled has been renamed to canceled. This script builds that state from scratch, with an index and a view added because real tables usually have them.
CREATE TYPE order_status AS ENUM (
'pending', 'paid', 'shipped', 'delivered', 'refunded', 'canceled'
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);
CREATE INDEX orders_status_idx ON orders (status);
CREATE VIEW open_orders AS
SELECT id, status FROM orders WHERE status IN ('pending', 'paid');
INSERT INTO orders (status) VALUES ('pending'), ('refunded'), ('shipped');The business decision is that refunded is a mistake: refunds will be tracked in a separate table, and an order that was refunded is simply canceled. So refunded must go.
The core steps
The spine's replacement recipe looks like this. It is the shape of the whole procedure, though as written it fails on our table for two reasons that the next sections explain.
CREATE TYPE order_status_new AS ENUM ('pending', 'paid', 'shipped', 'delivered', 'canceled');
ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;
ALTER TABLE orders
ALTER COLUMN status TYPE order_status_new
USING status::text::order_status_new;
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
DROP TYPE order_status;
ALTER TYPE order_status_new RENAME TO order_status;Each step has a reason:
- The new type lists only the labels you keep. The order you write them in becomes the new sort order. Keep the relative order of the survivors the same unless you mean to change it, because
ORDER BY statusand range comparisons follow declaration order. DROP DEFAULTcomes first. The column default'pending'is stored as an expression of the old enum type. PostgreSQL cannot convert it for you, and without this step you getdefault for column "status" cannot be cast automatically to type order_status_new.- The
USINGclause goes throughtext. There is no cast between two different enum types, even if their labels match. Casting totextand then to the new type uses each type's input and output functions, so the conversion is done by label. SET DEFAULTrestores the default. The literal'pending'is now resolved against the new type.DROP TYPEremoves the old type, and theRENAMEgives the new type the name the rest of your code expects.
What can go wrong
Rows that still use the value
The conversion applies status::text::order_status_new to every row. If any row holds refunded, the cast fails and the whole statement rolls back:
ERROR: invalid input value for enum order_status_new: "refunded"This is a safety net, not a nuisance. It guarantees you cannot lose data silently. Migrate the rows first, using the old type, which still knows the label:
UPDATE orders SET status = 'canceled' WHERE status = 'refunded';Check that the count of remaining rows is zero before you continue. If other tables or materialized views store the same type, check those too.
Dependent views
A view that mentions the column blocks the type change:
ERROR: cannot alter type of a column used by a view or ruleYou must drop the view and recreate it after the swap. Dropping a view also removes its grants, comments, and any other objects that depend on it, so script all of those back. Capture the definition before you drop it:
SELECT pg_get_viewdef('open_orders'::regclass, true);Functions and procedures that take or return order_status cause a different failure. DROP TYPE order_status stops with cannot drop type order_status because other objects depend on it. Drop and recreate those functions too. Avoid DROP TYPE ... CASCADE here. It removes the dependent objects without telling you which ones.
Other columns, arrays, and composite types
The old type has to be unused everywhere before you can drop it. That includes:
- columns of the same type in other tables and schemas
- array columns such as
order_status[] - columns inside composite types
- table-level
CHECKconstraints or generated columns that mention the type
Array columns need a matching conversion, for example USING status_history::text[]::order_status_new[]. The next section shows a query that finds all of them.
Locks and table rewrite
Changing a column to an unrelated type rewrites the whole table and rebuilds its indexes. The statement holds an ACCESS EXCLUSIVE lock for the entire rewrite, so reads and writes on that table wait. On a small table this takes milliseconds. On a table with hundreds of millions of rows it can take long enough to count as an outage.
Find the dependents first
Before you write the migration, list everything that uses the type. This query finds table, view, and materialized view columns:
SELECT n.nspname AS schema_name,
c.relname AS relation,
c.relkind,
a.attname AS column_name
FROM pg_attribute AS a
JOIN pg_class AS c ON c.oid = a.attrelid
JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE a.atttypid IN ('order_status'::regtype, 'order_status[]'::regtype)
AND a.attnum > 0
AND NOT a.attisdropped
AND c.relkind IN ('r', 'p', 'v', 'm', 'c')
ORDER BY schema_name, relation, column_name;The relkind letters mean: r ordinary table, p partitioned table, v view, m materialized view, c composite type. Views appear here because their output columns carry the type, which tells you which views to drop. This one finds functions that mention the type in their arguments or return value:
SELECT p.oid::regprocedure AS function_signature
FROM pg_proc AS p
WHERE p.prorettype = 'order_status'::regtype
OR 'order_status'::regtype = ANY (p.proargtypes::oid[]);Neither query sees dependencies inside function bodies written as strings, such as a PL/pgSQL function that casts to order_status internally. Search your migration files and application code for the type name as well.
The full migration
Putting it together for the orders table, in a single transaction. PostgreSQL supports transactional DDL, so if any statement fails, everything rolls back and the old type is untouched.
BEGIN;
LOCK TABLE orders IN ACCESS EXCLUSIVE MODE;
UPDATE orders SET status = 'canceled' WHERE status = 'refunded';
DROP VIEW open_orders;
CREATE TYPE order_status_new AS ENUM (
'pending', 'paid', 'shipped', 'delivered', 'canceled'
);
ALTER TABLE orders ALTER COLUMN status DROP DEFAULT;
ALTER TABLE orders
ALTER COLUMN status TYPE order_status_new
USING status::text::order_status_new;
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
DROP TYPE order_status;
ALTER TYPE order_status_new RENAME TO order_status;
CREATE VIEW open_orders AS
SELECT id, status FROM orders WHERE status IN ('pending', 'paid');
COMMIT;Taking the lock on the first line means no other session can insert a refunded row between your UPDATE and the type change. Without the lock, a concurrent writer could add one in that gap and make the conversion fail, or worse, add it after your check and before your lock is taken by the ALTER.
The index orders_status_idx needs no work. PostgreSQL rebuilds indexes on a column whose type changes, using the new type.
Verify the result:
SELECT enum_range(NULL::order_status);
SELECT id, status FROM orders ORDER BY id;The first query should list {pending,paid,shipped,delivered,canceled}. The second should show the former refunded row now as canceled.
The new type is a different type
After the swap, the type named order_status is a new object with a new OID (the internal numeric identifier of a type). The name is the same, but anything that remembered the old OID can misbehave:
- Prepared statements and cached plans on existing connections may fail with errors about cached plan types until they are re-prepared. Connection pools can keep such sessions alive for a long time.
- Client libraries and drivers that cache type information by OID may need to reload it. Some do this on reconnect only.
- Logical replication subscribers, foreign data wrappers, and other systems that define their own copy of the enum have to be changed to match.
- Any privileges granted on the old type (
GRANT USAGE ON TYPE) and its comment are gone. Reapply them to the new type. - The array type is replaced too. The old
_order_statusgoes with the old type, and the new type gets its own array type.
Plan to restart or recycle application connections right after the migration.
Alternatives to replacing the type
Full replacement is the right tool only when the label must disappear. Consider these first:
- Leave the label in place. An unused label costs almost nothing. Document it as deprecated and stop writing it from the application. Add a
CHECK (status <> 'refunded')constraint on the table if you want the database to enforce that. This keeps the type OID, the lock-free path, and all your views. - Rename it. If the real problem is a bad name,
ALTER TYPE ... RENAME VALUEis instant and does not touch rows. - Switch to a lookup table. If you expect to remove or reshape values often, the enum may be the wrong tool. A lookup table with a foreign key lets you delete a row once nothing references it. The last chapter compares the options.
For a table too large to rewrite under one lock, the usual approach is a staged migration. This is a sketch and each step needs its own testing:
- Add a nullable column of the new type.
- Add a trigger or change application writes so new rows fill both columns.
- Backfill the new column in small batches, committing between them.
- Add a
NOT NULLcheck (asNOT VALID, then validated) and switch reads and writes to the new column. - Drop the old column and old type in a short final transaction.
This avoids one long lock but takes weeks of care. Use it only when the single-transaction rewrite is not acceptable.
Summary of failure modes
| Symptom | Cause | Fix |
|---|---|---|
| `invalid input value for enum ...` during `ALTER COLUMN TYPE` | A row still holds the removed label | `UPDATE` those rows before the conversion |
| `default for column ... cannot be cast automatically` | Default still typed as the old enum | `DROP DEFAULT` before, `SET DEFAULT` after |
| `cannot alter type of a column used by a view or rule` | A view reads the column | Drop the view, recreate it after |
| `cannot drop type ... because other objects depend on it` | Another column, function, or composite still uses the old type | Find it with the catalog queries and convert or drop it |
| Reads and writes hang during migration | The rewrite holds an `ACCESS EXCLUSIVE` lock | Test timing, schedule a window, or use the staged approach |
| Errors in app sessions after the migration | Cached type OIDs or plans | Recycle connections |
Exercise
You run the replacement migration and the ALTER COLUMN ... TYPE order_status_new USING status::text::order_status_new statement fails with invalid input value for enum order_status_new: "refunded". What state is the database in if you ran everything inside one BEGIN ... COMMIT block, and what is the first thing you should do to fix it?
Show answer
The transaction is aborted, so nothing from the block is applied: the new type was not created, the default and old type are unchanged, and any dropped view is restored. Roll back, then migrate the offending rows with UPDATE orders SET status = 'canceled' WHERE status = 'refunded'; (or whatever mapping the business wants), confirm no refunded rows remain in any table using the type, and run the block again.
Exercise
A table shipments has a column status order_status, and a function next_status(s order_status) RETURNS order_status exists. You want to remove refunded from order_status. List every step you must add beyond changing orders, and say why DROP TYPE order_status CASCADE is a poor shortcut.
Show answer
Convert shipments.status the same way as orders.status: drop its default if it has one, change the type with USING status::text::order_status_new, and restore the default. Drop next_status before DROP TYPE order_status and recreate it with the new type after the rename, since a function that takes or returns the old type blocks the drop. CASCADE is a poor shortcut because it silently drops every dependent object, such as functions and views, and also can drop columns that use the type along with their data. You would find out what was lost only after the fact.
Exercise
After a successful migration, the application throws errors from pooled connections that were open before the migration, although the type name order_status is unchanged. Why does this happen, and what should you do?
Show answer
The renamed type is a new object with a new OID. Pooled connections can hold prepared statements, cached plans, or driver-side type caches that refer to the old OID. Recycle or restart those connections so they re-prepare statements and reload type information. Also reapply any grants and comments that were on the old type.