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.
Code
-- 枚举类型的取值顺序 = 声明顺序,不是字母序
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.