Nov 23, 20265 min read

Postgres Enum vs Check Constraint

Two ways to limit a Postgres column to a fixed set of values, compared on storage, ordering, adding and removing values, migrations and error handling, plus the lookup table option.

Illustration for Postgres Enum vs Check Constraint

Every status column eventually needs a rule about which values are allowed, and Postgres gives you two common ways to write it: an enum type or a text column with a CHECK constraint.

Both reject bad values at the database, and they differ mostly in what happens six months later, when product asks for a new status or wants to retire an old one.

At a glance

CHECK (status IN (...))Enum type
Column typetextCustom type
Storage per valueString length plus overhead4 bytes
Sort orderAlphabeticalDeclaration order
Add a valueSwap the constraintALTER TYPE ... ADD VALUE
Remove a valueSwap the constraintNot supported, recreate the type
Use a new value in the same transactionYesNo
Error on bad inputcheck_violationinvalid_text_representation

Enum types

An enum is a type with an ordered list of labels, stored in 4 bytes per value according to the enum documentation. Comparison follows declaration order, so 'delivered' > 'created' is true when the type lists created first, which is useful for "at least shipped" queries.

CREATE TYPE shipment_status AS ENUM ('created', 'in_transit', 'delivered'); ALTER TYPE shipment_status ADD VALUE 'returned'; ALTER TYPE shipment_status ADD VALUE 'held' BEFORE 'in_transit';

Adding is cheap, and the ALTER TYPE documentation lists the limits: a value added inside a transaction block cannot be used until the transaction commits, and there is no way to drop a value. Removing held later means a new type, an ALTER COLUMN ... TYPE with a USING cast on every table that uses it, and a full rewrite of each one.

Check constraints

A text column with a CHECK constraint stores the plain string, so the values are readable in every client and driver without a custom type. Changing the allowed set is a constraint swap, and NOT VALID lets you add the new rule without scanning the table while holding a strong lock:

ALTER TABLE shipments DROP CONSTRAINT shipments_status_check, ADD CONSTRAINT shipments_status_check CHECK (status IN ('created', 'in_transit', 'delivered', 'returned')) NOT VALID; -- Checks existing rows with a weaker lock that allows reads and writes. ALTER TABLE shipments VALIDATE CONSTRAINT shipments_status_check;

The ALTER TABLE documentation describes VALIDATE CONSTRAINT as taking only a SHARE UPDATE EXCLUSIVE lock, so normal traffic continues while existing rows are checked. The cost is storage: in_transit takes its length in bytes plus a byte of header instead of 4, which matters only on very large tables with many such columns.

The lookup table option

A third pattern is a shipment_statuses table with a foreign key from shipments.status. It lets you attach metadata such as a display label or an "is terminal" flag, and adding a value is an INSERT rather than a schema change. It costs a join whenever you need that metadata, plus an index on the foreign key column.

How to choose

  • The set changes with product decisions (order states, plan names, ticket categories): CHECK constraint.
  • The set is fixed by definition (days of the week, a protocol's message types) or ordering matters: enum.
  • Values need their own attributes or non-engineers manage them: lookup table.

Best fit: a CHECK constraint for status columns in application tables, enums for small fixed sets whose order means something.

Allowed values in Encore

Encore

Encore is a backend framework with built-in infrastructure, and a service's migrations live beside the endpoint that writes the column, so the allowed values and the error the API returns for anything else change in the same pull request. This shipments service uses a CHECK constraint, and the second migration shows how a new status is added later:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- shipments/migrations/1_create_shipments.up.sql CREATE TABLE shipments ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, tracking text NOT NULL UNIQUE, status text NOT NULL DEFAULT 'created' CONSTRAINT shipments_status_check CHECK (status IN ('created', 'in_transit', 'delivered')), updated_at timestamptz NOT NULL DEFAULT now() );
-- shipments/migrations/2_add_returned_status.up.sql ALTER TABLE shipments DROP CONSTRAINT shipments_status_check, ADD CONSTRAINT shipments_status_check CHECK (status IN ('created', 'in_transit', 'delivered', 'returned'));
// shipments/shipments.go package shipments import ( "context" "encore.dev/beta/errs" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("shipments", sqldb.DatabaseConfig{Migrations: "./migrations"}) type StatusParams struct { Status string `json:"status"` } //encore:api private method=PUT path=/shipments/:tracking/status func SetStatus(ctx context.Context, tracking string, p *StatusParams) error { res, err := db.Exec(ctx, ` UPDATE shipments SET status = $2, updated_at = now() WHERE tracking = $1 `, tracking, p.Status) if sqldb.ErrCode(err) == sqlerr.CheckViolation { return &errs.Error{Code: errs.InvalidArgument, Message: "unknown status: " + p.Status} } if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.NotFound, Message: "shipment not found"} } return nil }

sqldb.ErrCode turns the Postgres error into a typed code, and the endpoint returns a 400 with the bad value instead of a 500, using the codes in the API errors docs. The databases docs explain how migrations are numbered and applied, and changing the database schema covers adding the second file. encore run applies both migrations to the local Postgres it starts, and deploys apply them to RDS or Cloud SQL in your account.

When an AI coding agent is asked to add a returned status, the whole change is a new migration plus whatever code sets the status, and because the constraint is enforced locally, a typo in either place fails in encore run or a test instead of in production.

Best fit: services whose status sets change with the product and that want the database and the API to agree on them.

Frequently asked questions

Should I use an enum or a check constraint in Postgres?

Use a text column with a CHECK constraint when the set of values may change, because adding or removing a value is a quick constraint swap. Use an enum when the values are stable, you want 4-byte storage or you need them to sort in a defined order.

Can you remove a value from a Postgres enum?

No. ALTER TYPE supports adding and renaming values but not dropping them. Removing one means creating a new type, converting every column that uses it and dropping the old type, which rewrites those tables.

Can I use a new enum value in the same transaction that added it?

No. ALTER TYPE ... ADD VALUE can run inside a transaction block, but the new value cannot be used until that transaction commits, so Postgres raises an unsafe use of new value error. Split it into two migrations.

How do I enforce allowed status values in an Encore service?

Add a CHECK constraint on the column in the service's migration and map sqldb.ErrCode(err) == sqlerr.CheckViolation to an InvalidArgument error in the endpoint. encore run applies the migration to the local Postgres it starts, so the rule is enforced in local development too.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders