I have two tables in a Postgres 17 database: site and page. Each site can have multiple pages and each page can have a parent page:
CREATE TABLE site (
id INT PRIMARY KEY
);
CREATE TABLE page (
id INT PRIMARY KEY,
site_id INT references site(id),
parent_id INT references page(id)
);
Now suppose I have two sites:
INSERT INTO site (id) VALUES (1);
INSERT INTO site (id) VALUES (2);
And one root page for each site:
INSERT INTO page (id, site_id, parent_id) VALUES (1, 1, NULL);
INSERT INTO page (id, site_id, parent_id) VALUES (2, 2, NULL);
How to prevent inserting a new page for site 2 with a parent page which belongs to site 1?
INSERT INTO page (id, site_id, parent_id) VALUES (3, 2, 1);