Enum Rename Value Preserves Order
ALTER TYPE RENAME VALUE relabels an enum member without touching its sort position, and both a missing old value and an already-used new name fail outright.
Code
CREATE TYPE ticket_state AS ENUM ('open', 'working', 'closed');
CREATE TABLE tickets (
id int PRIMARY KEY,
state ticket_state NOT NULL
);
INSERT INTO tickets VALUES (1, 'open'), (2, 'closed');
-- 重命名只换标签:排序位置不受影响(renamed 值仍按原次序参与 ORDER BY)
ALTER TYPE ticket_state RENAME VALUE 'working' TO 'in_progress';
INSERT INTO tickets VALUES (3, 'in_progress');
-- 按枚举声明次序输出:open, in_progress, closed
SELECT id, state FROM tickets ORDER BY state;
-- 旧标签随即失效:invalid input value for enum
-- INSERT INTO tickets VALUES (4, 'working');
-- 旧值不存在同样报错;新名字已被占用也报错
-- ALTER TYPE ticket_state RENAME VALUE 'draft' TO 'open';
-- 现有枚举值不能删除、排序位置也不能改变(只能删型重建)What the code does
The file runs SELECT / INSERT / CREATE / ALTER statements, touching tickets.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The tickets table is the working surface here.
Statements that matter
CREATE TABLE tickets (
id int PRIMARY KEY,
state ticket_state NOT NULL
);
CREATE TYPE ticket_state AS ENUM ('open', 'working', 'closed');
INSERT INTO tickets VALUES (1, 'open'), (2, 'closed');
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
- What are the relations in play here?
- `tickets`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.