Numeric Range Rules With CHECK Constraints

Pin numeric columns to valid domains with CHECK constraints: BETWEEN bounds, positive amounts, and cross-column date order — mind that NULL passes.

SqlData Integrity

Code

snippet
-- CHECK 把非法数值挡在写入之前
CREATE TABLE discounts (
    id           integer PRIMARY KEY,
    label        text NOT NULL,
    -- CHECK 不拦 NULL:percent 为 NULL 时表达式结果是 NULL,视为通过
    percent      numeric CHECK (percent BETWEEN 0 AND 100),
    -- 单边界约束:金额必须严格为正
    amount_cents integer NOT NULL CHECK (amount_cents > 0),
    valid_from   date NOT NULL,
    valid_until  date NOT NULL,
    -- 跨列规则放表级:起止日期必须构成有效区间
    CHECK (valid_from < valid_until)
);

-- 边界值合法:BETWEEN 两端都含
INSERT INTO discounts VALUES (1, 'free-shipping', 100, 500, '2026-12-01', '2026-12-31');

-- NULL 溜过 CHECK:三值逻辑下未知不算违规
INSERT INTO discounts VALUES (2, 'unset', NULL, 900, '2026-12-01', '2026-12-31');

-- 越界写入被拒绝并报出约束名:
-- ERROR:  new row for relation "discounts" violates check constraint "discounts_percent_check"
-- INSERT INTO discounts VALUES (3, 'bad', 150, 500, '2026-12-01', '2026-12-31');

-- 要禁止 NULL 需另加 NOT NULL(列级或 CHECK (percent IS NOT NULL))
SELECT id, label, percent FROM discounts ORDER BY id;

How it works

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

In terms of clauses, the statements use: 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.

Putting it to use

Run it in the discounts database context.

Core lines

CREATE TABLE discounts (
id           integer PRIMARY KEY,
label        text NOT NULL,
percent      numeric CHECK (percent BETWEEN 0 AND 100),
amount_cents integer NOT NULL CHECK (amount_cents > 0),
valid_from   date NOT NULL,
valid_until  date NOT NULL,
CHECK (valid_from < valid_until)
);
INSERT INTO discounts VALUES (1, 'free-shipping', 100, 500, '2026-12-01', '2026-12-31');
INSERT INTO discounts VALUES (2, 'unset', NULL, 900, '2026-12-01', '2026-12-31');

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `discounts`.