CHECK NO INHERIT Scopes Parent Constraints
Define a parent CHECK with NO INHERIT so child tables accept rows the parent rejects, then compare inherited and local rules.
Code
CREATE TABLE vehicles (
id int PRIMARY KEY,
kind text NOT NULL,
wheels int NOT NULL,
CONSTRAINT cars_have_four_wheels
CHECK (kind <> 'car' OR wheels = 4) NO INHERIT
);
-- The parent table enforces the rule.
INSERT INTO vehicles (id, kind, wheels) VALUES (1, 'car', 4);
CREATE TABLE prototypes (
max_speed int
) INHERITS (vehicles);
-- The child does not inherit the NO INHERIT check.
INSERT INTO prototypes (id, kind, wheels, max_speed)
VALUES (3, 'car', 6, 120);
SELECT tableoid::regclass AS source, id, kind, wheels
FROM vehicles
ORDER BY id;
-- A local check still applies to the child table.
ALTER TABLE prototypes
ADD CONSTRAINT prototypes_need_speed
CHECK (max_speed IS NULL OR max_speed > 0);
-- The parent rejects this row; the savepoint keeps the session usable.
BEGIN;
SAVEPOINT bad_parent;
INSERT INTO vehicles (id, kind, wheels) VALUES (2, 'car', 6);
ROLLBACK TO SAVEPOINT bad_parent;
COMMIT;What the code does
Several statements share this file — SELECT / INSERT / CREATE / ALTER, with vehicles and prototypes among the objects involved.
Breaking the statements into their working parts: 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.
Applying it
Run the statement against the vehicles table.
Statements that matter
CREATE TABLE vehicles (
id int PRIMARY KEY,
kind text NOT NULL,
wheels int NOT NULL,
CONSTRAINT cars_have_four_wheels
CHECK (kind <> 'car' OR wheels = 4) NO INHERIT
);
SELECT tableoid::regclass AS source, id, kind, wheels
FROM vehicles
ORDER BY id;
INSERT INTO prototypes (id, kind, wheels, max_speed)
VALUES (3, 'car', 6, 120);
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.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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
- Name the tables involved in this file.
- The references are `vehicles`, `prototypes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.