Check Constraint Self Parent Reference
Stop a row from being its own parent with a same-row CHECK comparison; parent existence stays the job of a self-referencing foreign key.
Code
-- 行内自引用(self reference)用 CHECK 就够:同一行两列直接比较。
-- CHECK 只能看本行——“父行必须真实存在”是自引用 FOREIGN KEY 的事
CREATE TEMP TABLE categories (
category_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
parent_id bigint REFERENCES categories(category_id),
name text NOT NULL,
-- 一行不能把自己设为父节点
CONSTRAINT categories_no_self_parent
CHECK (parent_id IS NULL OR parent_id <> category_id)
);
INSERT INTO categories (name) VALUES ('hardware'); -- 顶层节点
INSERT INTO categories (parent_id, name) VALUES (1, 'drills'); -- 子节点
UPDATE categories SET parent_id = 1 WHERE category_id = 1;
-- ERROR: violates check constraint "categories_no_self_parent"
-- 试图指向不存在的父行:FK 在 CHECK 之前报另一类错
INSERT INTO categories (parent_id, name) VALUES (99, 'ghost');
-- ERROR: violates foreign key constraintUnder the hood
The file runs INSERT / UPDATE / CREATE statements, touching categories.
categories is spun up inside this file itself as a session-local temp table — nothing to prepare, and it vanishes with the session.
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; a foreign-key REFERENCES guard anchoring child rows to the parent table.
Using it
Nothing outside the file is needed: the session-local tables it touches (categories) are created by the file itself — point it at a scratch database and run the whole thing.
Key statements
UPDATE categories SET parent_id = 1 WHERE category_id = 1;
CREATE TEMP TABLE categories (
category_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
parent_id bigint REFERENCES categories(category_id),
name text NOT NULL,
CONSTRAINT categories_no_self_parent
CHECK (parent_id IS NULL OR parent_id <> category_id)
);
INSERT INTO categories (name) VALUES ('hardware'); -- 顶层节点
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- `categories` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.