Created
March 23, 2026 14:26
-
-
Save yahonda/34ca1e096fb2a7571354eb96c83dc729 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #2 It raises "ERROR: insert or update on table "child" violates foreign key constraint "child_parent_fk" | |
| ``` | |
| postgres=# select version(); | |
| version | |
| ----------------------------------------------------------------------------------------------------------------------------- | |
| PostgreSQL 18.3 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit | |
| (1 row) | |
| postgres=# CREATE TABLE parent ( | |
| id INTEGER PRIMARY KEY, | |
| name TEXT NOT NULL | |
| ); | |
| CREATE TABLE | |
| postgres=# CREATE TABLE child ( | |
| id INTEGER PRIMARY KEY, | |
| parent_id INTEGER NOT NULL, | |
| name TEXT NOT NULL, | |
| CONSTRAINT child_parent_fk | |
| FOREIGN KEY (parent_id) | |
| REFERENCES parent(id) | |
| ); | |
| CREATE TABLE | |
| postgres=# SELECT | |
| conname, | |
| contype, | |
| convalidated, | |
| conenforced | |
| FROM pg_constraint | |
| WHERE conname = 'child_parent_fk'; | |
| conname | contype | convalidated | conenforced | |
| -----------------+---------+--------------+------------- | |
| child_parent_fk | f | t | t | |
| (1 row) | |
| postgres=# ALTER TABLE child | |
| ALTER CONSTRAINT child_parent_fk NOT ENFORCED; | |
| ALTER TABLE | |
| postgres=# SELECT | |
| conname, | |
| contype, | |
| convalidated, | |
| conenforced | |
| FROM pg_constraint | |
| WHERE conname = 'child_parent_fk'; | |
| conname | contype | convalidated | conenforced | |
| -----------------+---------+--------------+------------- | |
| child_parent_fk | f | f | f | |
| (1 row) | |
| postgres=# INSERT INTO child VALUES (3, 999, 'orphan-child'); | |
| INSERT 0 1 | |
| postgres=# ALTER TABLE child | |
| ALTER CONSTRAINT child_parent_fk ENFORCED; | |
| ERROR: insert or update on table "child" violates foreign key constraint "child_parent_fk" | |
| DETAIL: Key (parent_id)=(999) is not present in table "parent". | |
| postgres=# DROP TABLE IF EXISTS child; | |
| DROP TABLE | |
| postgres=# DROP TABLE IF EXISTS parent; | |
| DROP TABLE | |
| postgres=# | |
| ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment