Enum Type Sorts By Declaration Order

Give statuses a fixed lifecycle with CREATE TYPE AS ENUM: ORDER BY follows declaration order, comparisons rank labels, and ADD VALUE appends later states.

SqlData Integrity

Code

snippet
-- 枚举类型的取值顺序 = 声明顺序,不是字母序
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped');

CREATE TABLE orders (
    id     integer PRIMARY KEY,
    status order_status NOT NULL
);

INSERT INTO orders VALUES (1, 'pending'), (2, 'paid'), (3, 'shipped');

-- ORDER BY 枚举列:按声明顺序 pending -> paid -> shipped
SELECT id, status FROM orders ORDER BY status;

-- 想要字母序必须显式转 text
SELECT id, status::text FROM orders ORDER BY status::text;

-- 枚举支持比较运算:声明靠后的值更大
SELECT min(status), max(status) FROM orders;

-- 上线后追加新状态用 ADD VALUE,尾部追加不改已有顺序
ALTER TYPE order_status ADD VALUE 'cancelled';

How the snippet works

Several statements share this file — SELECT / INSERT / CREATE / ALTER, with orders among the objects involved.

What the statements actually assemble: MIN, MAX aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the orders table.

Statements that matter

CREATE TABLE orders (
id     integer PRIMARY KEY,
status order_status NOT NULL
);
INSERT INTO orders VALUES (1, 'pending'), (2, 'paid'), (3, 'shipped');
CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped');

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`orders` — referenced directly, no join needed.