Sub topic 1
Creating and Using Enum Types
Prerequisites
This chapter assumes you can already do the following:
- Write basic SQL:
CREATE TABLE,INSERT,SELECT, andWHERE. - Use PostgreSQL's built-in types such as
text,integer, andnumeric. - Explain what
CHECKandNOT NULLconstraints do. - Describe a foreign key at a high level.
The examples work on any supported PostgreSQL version. Run them in psql or any SQL client, against a scratch database.
What an enum type is
An enum (short for enumerated type) is a data type whose values come from a fixed list of text labels. You declare the list once. After that, a column of that type accepts only those labels and rejects everything else.
Many columns hold a small set of known states: an order status, a ticket priority, a day of the week. A plain text column accepts any string, so a typo such as 'shiped' gets stored without complaint. An enum moves that rule into the type itself, so every table that uses the type gets the same check.
Two properties set enums apart from a text column with a CHECK constraint:
- The enum is a real type with its own name, registered in the database catalog. You can reuse it in many tables, in function arguments, and in arrays.
- The labels are ordered. The order is the order in which you declared them. The next chapter covers ordering in detail.
This chapter covers creating an enum, using it in a table, how PostgreSQL validates input, and the typing rules that cause most beginner errors.
Creating an enum and using it in a table
You create an enum with CREATE TYPE ... AS ENUM, followed by the labels in single quotes:
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');The first statement creates the type. The second uses it as the type of the status column, exactly where you would otherwise write text or integer. Three details are worth noting:
NOT NULLis a separate decision. An enum column allowsNULLunless you say otherwise.DEFAULT 'pending'is checked when you create the table. If you wroteDEFAULT 'pendng', theCREATE TABLEwould fail immediately.- The string
'paid'in theINSERTis an untyped literal. PostgreSQL sees that the target column isorder_statusand converts the literal to that type.
Query the table as usual:
SELECT id, status FROM orders; id | status
----+---------
1 | paid
2 | shippedClients receive the label as text. Your application code does not need special handling to read an enum column, and most drivers return a plain string.
In psql, the \dT+ command shows a type and its labels:
\dT+ order_statusHow PostgreSQL validates values
Every time a value is converted to order_status, PostgreSQL checks it against the list of labels registered for that type. This happens on INSERT, on UPDATE, and on explicit casts such as 'paid'::order_status. A match is stored, and anything else raises an error.
The check is an exact string match. PostgreSQL does not trim whitespace, ignore case, or guess what you meant.
INSERT INTO orders (status) VALUES ('returned');ERROR: invalid input value for enum order_status: "returned"The same error appears for 'Paid' (wrong case) and 'paid ' (trailing space). Labels are case-sensitive, and spaces count. If your application normalizes input before inserting, do it before the value reaches the database.
A failed insert in a multi-row statement writes nothing. In a transaction, the error aborts the whole transaction until you roll back or use a savepoint.
The error is the SQL state 22P02 (invalid_text_representation). Application code that needs to tell a bad enum value apart from other failures can catch that code.
Enums and text: casts and operators
PostgreSQL treats an enum as its own type, not as a kind of text. This matters when you mix an enum column with a value whose type is already known.
A literal in quotes is fine, because its type is not yet decided. PostgreSQL picks the enum type:
SELECT id FROM orders WHERE status = 'paid';A text value is different. Suppose the labels come from a list of values or another table:
WITH incoming(label) AS (VALUES ('paid'::text))
SELECT o.id
FROM orders o
JOIN incoming i ON o.status = i.label;ERROR: operator does not exist: order_status = textThe incoming.label column is text, and there is no = operator between an enum and text. You have two ways to fix it. Prefer the first, which keeps the comparison in the enum domain and can use an index on status:
WITH incoming(label) AS (VALUES ('paid'::text))
SELECT o.id
FROM orders o
JOIN incoming i ON o.status = i.label::order_status;The second converts the enum to text, which also works but changes what the comparison means:
SELECT id FROM orders WHERE status::text LIKE 'ship%';Use that form when you need text operations such as LIKE or ||. A filter on status::text cannot use a plain index on status.
The cast from text to enum raises the same invalid input value error for an unknown label. If bad values are possible, validate them first or handle the error.
Enums are distinct types
Two enums with the same labels are not the same type
Each CREATE TYPE ... AS ENUM defines a separate type, even when the labels are identical:
CREATE TYPE shipment_status AS ENUM ('pending', 'shipped', 'delivered');
SELECT 'pending'::order_status = 'pending'::shipment_status;ERROR: operator does not exist: order_status = shipment_statusPostgreSQL will not compare values of different enum types. Cast through text if you really need to: a::text = b::text. If you find yourself doing that often, the two columns probably share a meaning, and you should use one type for both.
Type names share a namespace with tables
Every table also defines a composite row type with the same name. A type and a table in the same schema therefore cannot have the same name:
CREATE TYPE orders AS ENUM ('a', 'b');ERROR: type "orders" already existsName enum types for the concept they hold, such as order_status, and use singular names. That avoids collisions with plural table names.
Types live in schemas
An enum belongs to a schema. If you create it in public, any table in the database can use it. If you create it in another schema, qualify the name or put that schema on your search_path:
CREATE SCHEMA IF NOT EXISTS shop;
CREATE TYPE shop.priority_level AS ENUM ('low', 'normal', 'high');
CREATE TABLE shop.tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
priority shop.priority_level NOT NULL DEFAULT 'normal'
);By default, every role has USAGE on new types, so any role that can reach the table can read and write the enum column. To restrict it, use REVOKE USAGE ON TYPE ... FROM PUBLIC and grant USAGE to specific roles.
Everyday operations on enum columns
Once the column exists, most SQL features work without extra effort.
Filtering, grouping, and joining use the normal operators:
SELECT status, count(*) AS order_count
FROM orders
GROUP BY status;Indexes work, including partial indexes on a single label. A partial index is useful when one state is rare and queried often, such as unfinished orders:
CREATE INDEX orders_status_idx ON orders (status);
CREATE INDEX orders_pending_idx ON orders (id) WHERE status = 'pending';You can build arrays of an enum, and every element is validated:
SELECT ARRAY['paid', 'shipped']::order_status[];Functions can take or return an enum, so the same list of labels constrains function arguments:
CREATE FUNCTION is_open(s order_status) RETURNS boolean
LANGUAGE sql IMMUTABLE
AS $$ SELECT s IN ('pending', 'paid', 'shipped') $$;
SELECT id, is_open(status) FROM orders;Adding an enum column to an existing table follows the usual ALTER TABLE rules. A constant default such as 'normal' does not rewrite the table in PostgreSQL 11 and later:
ALTER TABLE shop.tickets
ADD COLUMN escalation shop.priority_level NOT NULL DEFAULT 'normal';Creating the type only if it is missing
CREATE TYPE has no IF NOT EXISTS clause. Migration scripts that must be safe to run twice usually catch the duplicate error:
DO $$
BEGIN
CREATE TYPE ticket_state AS ENUM ('open', 'closed');
EXCEPTION
WHEN duplicate_object THEN NULL;
END
$$;This only checks that a type with that name exists, not that its labels match. If an older version of the type has different labels, the block hides the difference. A migration tool that tracks which scripts have run is a safer approach.
Dropping an enum type
You cannot drop a type that a column still uses:
DROP TYPE order_status;ERROR: cannot drop type order_status because other objects depend on it
DETAIL: column status of table orders depends on type order_status
HINT: Use DROP ... CASCADE to drop the dependent objects too.The CASCADE option removes the dependent column and its data, so check the DETAIL lines before you use it. Dropping a type you no longer need is rare. You will see this dependency check again when you replace a type to remove a label in a later chapter.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `invalid input value for enum` | The label does not match exactly, including case and spaces | Correct the value, or normalize it in the application |
| `operator does not exist: order_status = text` | A `text` column or parameter is compared with an enum | Cast the text side to the enum, or the enum to text |
| `operator does not exist: order_status = shipment_status` | Two different enum types are compared | Use one type, or cast both sides to `text` |
| `type "..." already exists` | A type or table in the schema has the same name | Rename the type, or check the schema with `\dT` |
| `cannot drop type ... because other objects depend on it` | A column or function still uses the type | Move the dependents off the type first |
| Column accepts `NULL` unexpectedly | The enum type does not imply `NOT NULL` | Add `NOT NULL` to the column |
What comes next
You now have the working model: an enum is a named type with a fixed, exact list of labels, validated on every write. The next chapters build on it:
- How enum values sort and compare by declaration order.
- How to list labels with
enum_range,enum_first, andenum_last. - How to add and rename values, and the restrictions on using a new value inside a transaction.
- How labels are stored, and the limits on label length.
Exercise
You run SELECT * FROM orders WHERE status = lower(:input) from an application that sends the parameter as text, and PostgreSQL reports operator does not exist: order_status = text. Explain why this happens and write the corrected condition.
Show answer
lower() returns text, so the comparison has an enum on one side and a known text value on the other, and no = operator exists between those types. A quoted literal would have been converted automatically, but a text expression is not. Cast the result to the enum: WHERE status = lower(:input)::order_status. If the input might not be a valid label, the cast raises invalid input value for enum, so validate the input or handle that error.
Exercise
Create an enum priority_level with the labels 'low', 'normal', and 'high'. Create a table tasks with an identity primary key id and a priority column of that type that defaults to 'normal' and rejects NULL. Insert one task with the default priority, then show the statement that PostgreSQL rejects when you insert a task with priority 'urgent'.
Show answer
CREATE TYPE prioritylevel AS ENUM ('low', 'normal', 'high');
CREATE TABLE tasks (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, priority prioritylevel NOT NULL DEFAULT 'normal');
INSERT INTO tasks DEFAULT VALUES;
The statement INSERT INTO tasks (priority) VALUES ('urgent'); fails with: ERROR: invalid input value for enum prioritylevel: "urgent". If a schema already has a table or type named tasks or `prioritylevel`, choose different names, because types and tables share one namespace.
Exercise
A teammate creates CREATE TYPE order_status AS ENUM ('pending', 'paid') in schema public and a second type CREATE TYPE shipment_status AS ENUM ('pending', 'paid') in the same schema. Can a query compare orders.status to shipments.status directly? What are your options?
Show answer
No. They are different types, so PostgreSQL reports that the operator does not exist, even though the labels are identical. You can compare them through text with orders.status::text = shipments.status::text, which gives up index use on those columns. A better fix is usually to use a single enum type for both columns if they represent the same concept.