Sub topic 2
How enum values are ordered and compared
This chapter explains how PostgreSQL decides which enum value is smaller, how that rule affects sorting, filtering, indexes and aggregates, and where it surprises people. It assumes you can create an enum type and use it as a column type. It also assumes you are comfortable with ORDER BY, WHERE, and basic indexes.
The rule: declaration order
An enum type is an ordered list of labels. The order is the one in which the labels were declared in CREATE TYPE ... AS ENUM, or the position you chose when you added a label later. It has nothing to do with alphabetical order or with the label text.
Every comparison operator on an enum uses that order: <, <=, =, <>, >=, >, and BETWEEN. So do ORDER BY, min, max, and btree indexes.
The examples in this chapter use the following setup. It drops and recreates the type and table, so you can run it from scratch.
DROP TABLE IF EXISTS orders;
DROP TYPE IF EXISTS order_status;
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 ('shipped'), ('pending'), ('cancelled'), ('paid'), ('delivered');The rows were inserted in a scrambled order on purpose. Ids 1 to 5 are shipped, pending, cancelled, paid, delivered.
Sorting and range filters
Sorting by an enum column follows the diagram above.
SELECT id, status FROM orders ORDER BY status;The result is:
| id | status |
|---|---|
| 2 | pending |
| 4 | paid |
| 1 | shipped |
| 5 | delivered |
| 3 | cancelled |
Alphabetically, cancelled would come first and shipped last. Enum sorting ignores that. ORDER BY status DESC reverses the list.
Comparison operators work the same way:
SELECT id FROM orders WHERE status >= 'paid' AND status < 'delivered';This returns ids 4 and 1, the paid and shipped rows. The string literals 'paid' and 'delivered' are converted to order_status because the other operand has that type. You can also write the range as status BETWEEN 'paid' AND 'shipped'. BETWEEN includes both ends.
Minimum and maximum
min and max are defined for enums and use the same order:
SELECT min(status), max(status) FROM orders;This returns pending and cancelled. Without enum ordering, you would have to cast to text and get the alphabetical minimum and maximum, which are cancelled and shipped.
Grouping and joining
Enums also support equality hashing, so GROUP BY, DISTINCT, hash joins, and UNION work without special handling. Ordering only matters when you sort, compare with < or >, or use an ordered index.
Why ordering is a design decision
Because comparison follows declaration order, the order of labels is part of your schema's meaning. In order_status, cancelled is declared last. A condition such as status >= 'paid' reads like "paid or later in the lifecycle", but it also matches cancelled, because cancelled is greater than paid.
Use range comparisons only when the declared order expresses a real progression and every label fits it. A cancelled order does not come "after" delivery. For states that do not fit the progression, list them explicitly:
SELECT id FROM orders WHERE status IN ('paid', 'shipped', 'delivered');An explicit list stays correct when someone adds a new label later. A range predicate silently changes meaning.
How the order is stored
PostgreSQL records each label in the system catalog pg_enum. Each row has the label, an internal object ID (OID), and a sort position called enumsortorder. You can read it:
SELECT enumlabel, enumsortorder
FROM pg_enum
WHERE enumtypid = 'order_status'::regtype
ORDER BY enumsortorder;For the type as created above, the positions are 1, 2, 3, 4, and 5. A column of this type stores only the 4-byte OID of the label, not the text. The comparison function looks at the positions, not the label text. This is why comparing enums is cheap and why renaming a label does not touch table data or change the order.
enumsortorder is a floating-point number, not an integer. When you add a label between two existing ones, PostgreSQL gives it a position between its neighbors. This lets it insert a label without rewriting existing positions.
ALTER TYPE order_status ADD VALUE 'refunded' AFTER 'delivered';
SELECT enumlabel, enumsortorder
FROM pg_enum
WHERE enumtypid = 'order_status'::regtype
ORDER BY enumsortorder;The new label refunded sits between delivered (position 4) and cancelled (position 5), so its position is 4.5. The existing labels keep their positions, and the stored rows are unchanged.
After this change the declared order is pending, paid, shipped, delivered, refunded, cancelled. The range query status >= 'paid' now also matches refunded, as well as cancelled.
PostgreSQL cannot reorder labels that already exist. If you need a different order, you must replace the type with a new one that lists the labels in the order you want. Chapter 6 of this tutorial covers replacing a type.
Comparing with other types
Enum comparison has strict typing rules. Most of the errors you will see come from them.
Enum and string literal
An untyped literal such as 'paid' is read as a value of the enum type. That is why status = 'paid' works. It also means the literal must be a valid label, even in a query that you expect to return no rows:
SELECT id FROM orders WHERE status = 'returned';This fails with invalid input value for enum order_status: "returned". It does not return zero rows. If the label comes from user input and might not exist, either validate it first or compare as text (see below).
Enum and text
A value that has already been given the type text does not convert implicitly. This query fails with operator does not exist: order_status = text:
SELECT id FROM orders WHERE status = 'paid'::text;Two fixes are available. Cast the column to text, which compares as text and ignores the enum order:
SELECT id FROM orders WHERE status::text = 'paid';Or cast the text to the enum type, which compares as an enum and fails if the text is not a label:
SELECT id FROM orders WHERE status = 'paid'::text::order_status;The same difference shows up in sorting. ORDER BY status follows declaration order. ORDER BY status::text sorts alphabetically, subject to the database collation.
Casting the column to text also stops PostgreSQL from using a plain index on status. If you must compare as text, create an expression index on (status::text), or cast the other side instead.
Two different enum types
Two enum types are unrelated to each other, even when they have identical labels. Comparing a column of one type with a column of another fails with operator does not exist. Convert through text if you really need to compare them:
CREATE TYPE shipment_status AS ENUM ('pending', 'shipped', 'delivered');
SELECT o.id
FROM orders o
JOIN (VALUES ('pending'::shipment_status)) AS s(status)
ON o.status::text = s.status::text;A join like this is usually a sign that the two types should be one type, or that a lookup table would suit better.
NULL
As with any type, comparing an enum with NULL yields NULL, not true or false. ORDER BY places NULL values last in ascending order and first in descending order, unless you add NULLS FIRST or NULLS LAST. A NOT NULL column avoids the question.
Indexes and enum order
A btree index on an enum column stores entries in enum order. It supports equality, range comparisons, and ORDER BY in either direction:
CREATE INDEX orders_status_idx ON orders (status);
SELECT id FROM orders WHERE status >= 'paid' AND status < 'delivered';On a large table, PostgreSQL can use orders_status_idx for this range query. On the five-row example it will normally read the table directly, because that is cheaper. Adding a label does not require rebuilding the index, because the index compares through the catalog positions and not through the label text.
Getting a rank number
Sometimes you want the position of a label as a number, for example to sort a report or to compute how many steps apart two states are. Use enum_range with array_position:
SELECT id,
status,
array_position(enum_range(NULL::order_status), status) AS rank
FROM orders
ORDER BY rank;enum_range(NULL::order_status) returns an array of all labels in declared order. array_position returns the 1-based index of the value in that array. The rank counts the labels that currently exist, so it shifts when you add a label before the current one. Do not store it in a table. Compute it when you need it.
The next chapter covers enum_range, enum_first, and enum_last in detail.
Summary of behaviors
| Operation | Uses enum order? | Notes |
|---|---|---|
| `ORDER BY status` | Yes | Declaration order, not alphabetical |
| `status < 'paid'`, `BETWEEN` | Yes | Depends on label positions |
| `min(status)`, `max(status)` | Yes | Returns an enum value |
| `status = 'paid'` | Not applicable | Unknown literal read as the enum; invalid label raises an error |
| `status = 'paid'::text` | Not applicable | Error: no operator for enum and text |
| `status::text` in `ORDER BY` | No | Alphabetical |
| Comparing two enum types | Not applicable | Error unless you cast through text |
| Btree index on `status` | Yes | Supports range scans and ordered output |
Common mistakes
- Treating the order as a lifecycle when it is not.
cancelledis declared last, sostatus > 'delivered'matches it. UseIN (...)when the labels do not form a straight line. - Adding a label in the middle without reviewing range queries. The new label changes which rows each range matches.
- Casting to text for comparison and then wondering why the sort is alphabetical. A text cast removes the enum order.
- Filtering by a label that does not exist. The query raises an error instead of returning no rows. This is a common failure when a label is removed from the type but remains in application code.
- Storing a rank number derived from
enum_range. The number changes when labels are added. Store the enum value instead.
Exercise
A table tickets has a column priority of type ticket_priority, declared as ENUM ('low', 'medium', 'high', 'urgent'). A teammate runs SELECT * FROM tickets ORDER BY priority::text; and reports that the result starts with high rows and ends with urgent rows, which is not the intended order. What causes this, and how do you fix the query? Which rows does WHERE priority >= 'high' return?
Show answer
The cast to text removes the enum ordering, so the rows sort alphabetically: high, low, medium, urgent. Fix it by sorting on the enum column itself: ORDER BY priority (add DESC for most urgent first). The filter priority >= 'high' returns rows with high and urgent, because high and urgent are the labels at or after high in declared order.
Exercise
You have order_status with the order pending, paid, shipped, delivered, cancelled. You run ALTER TYPE order_status ADD VALUE 'on_hold' BEFORE 'paid';. What is the new declared order, what enumsortorder does on_hold get, and how does the result of SELECT count(*) FROM orders WHERE status >= 'paid'; change if no row has the label on_hold? What does SELECT count(*) FROM orders WHERE status = 'returned'; do?
Show answer
The new order is pending, onhold, paid, shipped, delivered, cancelled. `onhold is placed between positions 1 (pending) and 2 (paid), so it gets 1.5. The count for status >= 'paid' does not change, because onhold is smaller than paid and no row has that label anyway. A range that began at pending or onhold would be affected only if rows with onhold existed. The query with 'returned' raises invalid input value for enum orderstatus: "returned", because returned` is not a label of the type. It does not return a count of 0.