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.
Code
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
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.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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.
FAQ
- Which tables or CTEs does it reference?
- `warehouses`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.