Whitelist Status Values With CHECK
Constrain a status column to an explicit whitelist with CHECK ... IN so invalid states are rejected at write time with a named constraint.
Code
-- 状态机白名单:CHECK ... IN 把非法状态挡在写入之前
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
status text NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'failed'))
);
INSERT INTO tasks (title) VALUES ('nightly-report');
-- 合法状态可正常流转
UPDATE tasks SET status = 'running' WHERE id = 1;
-- whitelist: only these status values may be written;越界即拒绝:
-- ERROR: new row for relation "tasks" violates check constraint "tasks_status_check"
-- INSERT INTO tasks (title, status) VALUES ('bad-job', 'cancelled');
-- 想让报错更好定位,可以表级命名约束:
-- CONSTRAINT tasks_status_rule CHECK (status IN ('queued', 'running', 'done', 'failed'))
-- 备选:PostgreSQL 枚举类型(值固定在建型时);需要热加值时 IN 白名单更灵活
SELECT id, title, status FROM tasks ORDER BY id;What the code does
The file runs SELECT / INSERT / UPDATE / CREATE statements, touching tasks.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the tasks table.
Statements that matter
UPDATE tasks SET status = 'running' WHERE id = 1;
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
status text NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'failed'))
);
INSERT INTO tasks (title) VALUES ('nightly-report');
Interactive Tools for This Topic
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.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.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.HTTP Status Code ExplorerBrowse and explore HTTP status codes with their meanings, categories, and common use cases. Search by code or description to understand 1xx through 5xx responses.
FAQ
- Which tables does the SQL touch?
- The references are `tasks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.