← Back to PostgreSQL, page 1

postgresql-0010 · Easy fresher

When is an ENUM type a good fit in PostgreSQL, and what are its limitations?

CREATE TYPE ... AS ENUM defines a fixed, ordered list of labels; invalid values are rejected and sorting follows declaration order. ALTER TYPE ... ADD VALUE adds labels, but there is no way to drop one, so lists that change often are easier as a lookup table or a CHECK constraint.

Full answer

Sample schema and data:

sql
CREATE TYPE ticket_status AS ENUM ('open', 'in_progress', 'resolved');
CREATE TABLE support (id int, status ticket_status);
INSERT INTO support VALUES (1, 'resolved'), (2, 'open'), (3, 'in_progress');
sql
SELECT id, status FROM support ORDER BY status;

PostgreSQL returns:

text
 id |    status
----+-------------
 2  | open
 3  | in_progress
 1  | resolved
(3 rows)
sql
INSERT INTO support VALUES (4, 'closed');

Result on PostgreSQL 17:

text
ERROR:  invalid input value for enum ticket_status: "closed"
sql
ALTER TYPE ticket_status ADD VALUE 'on_hold' BEFORE 'resolved';

Result:

text
ALTER TYPE
sql
SELECT enum_range(NULL::ticket_status)::text AS labels;

Output:

text
                labels
-------------------------------------
 {open,in_progress,on_hold,resolved}
(1 row)

Sorting by status follows the declared order (open, in_progress, resolved), not alphabetical order. An unknown label is rejected with an 'invalid input value for enum' error. ADD VALUE can insert a new label at a chosen position, and enum_range lists the labels in order. The two statements are sent separately on purpose: a new enum value cannot be used in the same transaction that added it, and sending both in one script fails with 'unsafe use of new value'. There is no ALTER TYPE ... DROP VALUE, so retiring a status means creating a new type and converting the column. A CHECK (status IN (...)) constraint on text is simpler to change, and a lookup table can hold extra attributes such as display names.

sql
CREATE TYPE ticket_status AS ENUM ('open', 'in_progress', 'resolved');
CREATE TABLE support (id int, status ticket_status);
INSERT INTO support VALUES (1, 'resolved'), (2, 'open'), (3, 'in_progress');

SELECT id, status FROM support ORDER BY status;

INSERT INTO support VALUES (4, 'closed');

ALTER TYPE ticket_status ADD VALUE 'on_hold' BEFORE 'resolved';

SELECT enum_range(NULL::ticket_status)::text AS labels;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Enums reject invalid labels
  • Order follows declaration
  • ADD VALUE is supported
  • Values cannot be dropped
  • Lookup tables suit changing lists

Common mistakes

  • Using enums for lists that change monthly
  • Assuming ORDER BY sorts enum labels alphabetically

Follow-ups

  • How would you rename an enum label?
  • When is a lookup table better than an enum?

Tips

  • Show declaration-order sorting