Sub topic 2
How Enum Values Are Ordered and Compared
Assume you know how to create tables, insert rows, filter with WHERE, and use CHECK and NOT NULL constraints. This chapter focuses on PostgreSQL enum ordering, comparisons, and range queries.
An enum type is a PostgreSQL type whose values come from a fixed list. PostgreSQL orders those values by their position in the CREATE TYPE statement. The order is not alphabetical.
Declaration order is sort order
Create an enum with labels in the order that represents the intended sequence:
CREATE TYPE delivery_stage AS ENUM (
'created',
'packed',
'shipped',
'delivered',
'returned'
);
CREATE TABLE parcels (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tracking_code text NOT NULL,
stage delivery_stage NOT NULL DEFAULT 'created'
);
INSERT INTO parcels (tracking_code, stage)
VALUES
('PKG-100', 'shipped'),
('PKG-101', 'created'),
('PKG-102', 'delivered'),
('PKG-103', 'packed'),
('PKG-104', 'returned');The following query sorts by the enum's declared order:
SELECT tracking_code, stage
FROM parcels
ORDER BY stage;The result is ordered like this:
| tracking_code | stage |
|---|---|
| PKG-101 | created |
| PKG-103 | packed |
| PKG-100 | shipped |
| PKG-102 | delivered |
| PKG-104 | returned |
Alphabetical sorting would place created, delivered, packed, returned, and shipped in a different order. Enum ordering follows the business sequence you declared.
Comparing enum values
Enum values support the usual comparison operators:
| Operator | Meaning |
|---|---|
| `=` | values are equal |
| `<>` | values are different |
| `<`, `<=` | value occurs earlier |
| `>`, `>=` | value occurs later |
For example:
SELECT tracking_code, stage
FROM parcels
WHERE stage >= 'packed'::delivery_stage
AND stage < 'delivered'::delivery_stage
ORDER BY stage;This returns parcels in the packed and shipped stages. It includes packed because of >=, but excludes delivered because of <.
This style is a half-open range. The lower boundary is included, and the upper boundary is excluded. Half-open ranges are useful when adjacent ranges should not overlap:
stage >= 'created'::delivery_stage
AND stage < 'shipped'::delivery_stageThe expression selects created and packed, but not shipped.
The explicit casts in these examples make the expected type clear. In a simple comparison such as stage = 'shipped', PostgreSQL can usually infer that the string literal should be treated as a delivery_stage value. Explicit casts are safer in prepared statements, functions, or expressions where PostgreSQL has less type information.
The order is part of the type definition
The enum order is a total order. PostgreSQL can use it for sorting, comparisons, grouping, and indexes that support ordering:
SELECT min(stage), max(stage)
FROM parcels;
SELECT tracking_code, stage
FROM parcels
ORDER BY stage DESC;
CREATE INDEX parcels_stage_idx ON parcels (stage);The first query returns the earliest and latest enum values present in the table. The second reverses the declared order. The index can help PostgreSQL locate and order rows by stage, especially when the table is large and the query planner decides that using the index is worthwhile.
The order does not describe every possible relationship between labels. It only provides one sequence. For example, returned comes after delivered in this type, but that does not mean a returned parcel is “later” in every business sense. The comparison is still useful for a workflow query, but the meaning must match the application.
Comparisons require compatible types
PostgreSQL compares values of the same enum type. Two different enum types are not automatically comparable, even if they contain labels with the same spelling:
CREATE TYPE payment_stage AS ENUM (
'created',
'packed',
'shipped',
'delivered',
'returned'
);delivery_stage and payment_stage have separate types and separate orders. PostgreSQL will not treat their values as interchangeable. If you need to compare their labels, convert both values to a common type such as text:
SELECT
'shipped'::delivery_stage::text =
'shipped'::payment_stage::text AS same_label;This compares text labels, not enum positions. It does not prove that the two enum types have the same ordering or meaning.
Enum labels are exact and case-sensitive. The labels 'shipped' and 'Shipped' would be different labels if both were declared. A value that is not in the type cannot be inserted or cast successfully:
SELECT 'unknown'::delivery_stage;That statement raises an invalid input value error.
When enum ordering is the wrong model
Use enum comparisons when the labels represent a stable sequence, such as workflow stages or severity levels. Do not use the order as a substitute for a separate numeric priority when the relationship changes frequently.
For example, a lookup table is a better fit when administrators must reorder values, rename them with extra metadata, deactivate them, or assign different priorities in different contexts. A plain text column with a CHECK constraint may be simpler when you need membership validation but do not need ordering.
The important question is whether the declared sequence is a stable part of the data model. If it is, enum comparisons make range queries concise. If it is not, store the ordering separately.
Exercise
Given deliverystage values declared as created, packed, shipped, delivered, returned, which rows match `stage > 'packed'::deliverystage AND stage <= 'delivered'::delivery_stage`?
Show answer
Rows with shipped and delivered match. The greater-than operator excludes packed, and the less-than-or-equal operator includes delivered.