Sub topic 12
Enumerated types
This chapter assumes you can write CREATE TABLE and INSERT statements, run queries in psql, and know what a CHECK constraint does. It builds on the earlier chapters on character types and casting.
What an enum is
An enumerated type (enum) is a data type with a fixed, ordered list of allowed values. Each value is a text label, such as 'pending' or 'paid'. You create the type once with CREATE TYPE, then use it as a column type like any other.
PostgreSQL stores each enum value as a 4-byte identifier that points to a row in the pg_enum system catalog. The label text is not repeated in every row of your table. Storage is small and comparisons are fast. You still read and write the readable labels.
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped', 'delivered');
CREATE TABLE shipments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status order_status NOT NULL DEFAULT 'pending'
);
INSERT INTO shipments (status) VALUES ('paid'), ('pending'), ('delivered');The column rejects any label that is not in the list. Labels are case-sensitive:
INSERT INTO shipments (status) VALUES ('Paid');
-- ERROR: invalid input value for enum order_status: "Paid"This is the main reason to use an enum. The database enforces the value set in the type itself, so you don't need a CHECK constraint on every table that uses it.
Ordering and comparison
Enum values sort and compare by their position in the declaration, not alphabetically. In order_status, 'pending' is the smallest value and 'delivered' is the largest.
SELECT status
FROM shipments
ORDER BY status;
-- pending, paid, delivered
SELECT id, status
FROM shipments
WHERE status >= 'paid';
-- rows with paid, shipped or deliveredRange comparisons like status >= 'paid' are useful when the values form a progression. The result depends on declaration order, so an enum whose order carries no meaning (such as country codes) gets no benefit from this. Don't write queries that depend on an accidental order.
To sort alphabetically, cast to text:
SELECT status FROM shipments ORDER BY status::text;Enums are also strictly typed. You cannot compare values of two different enum types, even when they share labels. Both sides need the same type, or you must cast both to text.
Inspecting an enum
Three functions help you read the value list without querying the catalog:
SELECT enum_range(NULL::order_status) AS all_values,
enum_first(NULL::order_status) AS first_value,
enum_last(NULL::order_status) AS last_value;The NULL::order_status argument only tells PostgreSQL which type you mean. The result is {pending,paid,shipped,delivered}, then pending, then delivered. Application code can use enum_range to populate a drop-down menu without hard-coding the list.
You can also list the values with their sort positions from the catalog:
SELECT e.enumlabel, e.enumsortorder
FROM pg_enum e
WHERE e.enumtypid = 'order_status'::regtype
ORDER BY e.enumsortorder;Changing an enum
Enums are easy to read and hard to change. You can add and rename values. You cannot remove them.
-- Add a value at the end
ALTER TYPE order_status ADD VALUE 'returned';
-- Add a value at a specific position
ALTER TYPE order_status ADD VALUE 'cancelled' BEFORE 'shipped';
-- Make the command safe to re-run
ALTER TYPE order_status ADD VALUE IF NOT EXISTS 'returned';
-- Rename a label (PostgreSQL 10 and later)
ALTER TYPE order_status RENAME VALUE 'pending' TO 'new';There is no ALTER TYPE ... DROP VALUE. To remove a label, you create a new type, convert every column that uses the old type, and drop the old type:
CREATE TYPE order_status_v2 AS ENUM ('new', 'paid', 'shipped', 'delivered');
ALTER TABLE shipments ALTER COLUMN status DROP DEFAULT;
ALTER TABLE shipments
ALTER COLUMN status TYPE order_status_v2
USING status::text::order_status_v2;
ALTER TABLE shipments ALTER COLUMN status SET DEFAULT 'new';
DROP TYPE order_status;
ALTER TYPE order_status_v2 RENAME TO order_status;The conversion rewrites the table and takes a strong lock, which matters on large tables. The USING clause goes through text because PostgreSQL has no direct cast between two enum types. The default is dropped and restored because the old default is a value of the old type. This sequence fails if any row still holds a label that the new type lacks.
Enum or alternatives
An enum is one of three common ways to restrict a column to a fixed set of values. The others are text with a CHECK constraint, and a lookup table referenced by a foreign key.
-- text with CHECK
CREATE TABLE tickets_a (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL CHECK (status IN ('open', 'closed'))
);
-- lookup table
CREATE TABLE ticket_status (
code text PRIMARY KEY,
description text NOT NULL
);
CREATE TABLE tickets_b (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL REFERENCES ticket_status (code)
);| Approach | Strengths | Weaknesses |
|---|---|---|
| Enum | Compact, built-in ordering, one definition shared by many tables | Values cannot be dropped, adding is restricted, extra data per value is impossible |
| `text` + `CHECK` | Simple, easy to change by replacing the constraint | The list is repeated in each table, no ordering, larger rows |
| Lookup table + foreign key | Add or remove values with `INSERT` and `DELETE`, can hold descriptions and flags | A join or extra lookup to show descriptions, more objects |
Use an enum when the set is small, stable and shared, such as days of the week or a short lifecycle with a clear order. Use a lookup table when the business edits the list, when each value needs attributes (a display name or a flag), or when values are retired over time. Use text with CHECK for a one-off column where adding a type feels heavy.
Common errors and gotchas
- Wrong case or spelling.
'Paid'is not'paid'. The error isinvalid input value for enum. Check the exact label withenum_range. - Comparing with text.
status = 'paid'works because the quoted literal is read as anorder_status. A text column or parameter needs a cast, for examplestatus = some_text::order_status. - Pattern matching.
status LIKE 'pa%'fails becauseLIKEhas no operator for enums. Writestatus::text LIKE 'pa%'. - Mixed enum types. Two enums with identical labels are still different types, so they cannot be compared or assigned to each other without going through
text. - Label length. A label can be at most 63 bytes.
- Unused values. Adding values is cheap, so lists tend to grow. Since you can't drop one, add only labels you need.
- Client libraries. Some drivers return enums as plain strings. Others need a registered type. Check how yours maps them.
Exercise
A table has a column of type order_status with the values 'pending', 'paid', 'shipped', 'delivered' declared in that order. (1) What does SELECT 'shipped'::order_status > 'paid'::order_status return? (2) You need to delete the label 'paid' from the type. Why can't you run ALTER TYPE order_status DROP VALUE 'paid', and what is the general procedure?
Show answer
(1) It returns true, because enum values compare by declaration order and 'shipped' comes after 'paid'. (2) PostgreSQL has no DROP VALUE command for enums. You create a new enum without the label, change each column with ALTER TABLE ... ALTER COLUMN ... TYPE new_type USING column::text::new_type (first migrating any rows that hold 'paid', and dropping and restoring any column default), then drop the old type and rename the new one.