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.

SqlData Integrity

Code

snippet
-- 状态机白名单: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

FAQ

Which tables does the SQL touch?
The references are `tasks`.