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.

SqlData Integrity

Code

snippet
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

FAQ

Name the tables involved in this file.
The references are `vehicles`, `prototypes`.