CHECK Constraint Validates Derived Column

A stored generated column computes load from crates times unit weight, and a CHECK constraint validates that derived total on every write.

SqlData Integrity

Code

snippet
CREATE TABLE warehouses (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name     text NOT NULL,
    crates   integer NOT NULL CHECK (crates >= 0),
    crate_kg numeric NOT NULL CHECK (crate_kg >= 0),
    load_kg  numeric GENERATED ALWAYS AS (crates * crate_kg) STORED,
    -- the CHECK constraint validates the derived total on every write
    CONSTRAINT max_load CHECK (load_kg <= 5000)
);

INSERT INTO warehouses (name, crates, crate_kg) VALUES ('north', 10, 120.5);  -- load 1205: accepted
INSERT INTO warehouses (name, crates, crate_kg) VALUES ('south', 40, 140.0);  -- load 5600: rejected by max_load

-- the derived total recomputes on every write, including updates
UPDATE warehouses SET crates = 20 WHERE name = 'north';

SELECT id, name, crates, crate_kg, load_kg FROM warehouses;

What happens on each run — CHECK Constraint Validates Derived Column

The file runs SELECT / INSERT / UPDATE / CREATE statements, touching warehouses.

Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; 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; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Run the statement against the warehouses table.

Key statements

UPDATE warehouses SET crates = 20 WHERE name = 'north';
INSERT INTO warehouses (name, crates, crate_kg) VALUES ('south', 40, 140.0);  -- load 5600: rejected by max_load
INSERT INTO warehouses (name, crates, crate_kg) VALUES ('north', 10, 120.5);  -- load 1205: accepted

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`warehouses`.