There is a Postgres database. There is a Foo
table with the id
primary key. There is a many-to-many table Bar
which contains a row which holds a Foreign Key key which references a non-existent foo object. Resulting in:
ERROR: insert or update on table "Bar" violates foreign key constraint "resu_foo_id_62eaf76ab86870ae_fk_foo_id"
DETAIL: Key (foo_id)=(123) is not present in table "Foo".
What is the way to get all rows in all tables whose foreign keys reference non-existent objects?
I would like to find those and delete them.
In other words, I want a script which will keep the database integrity by removing all non-existent references to already deleted objects.
For example there is this guide: https://www.cybertec-postgresql.com/en/index-your-foreign-key/. Which seems to find foreign keys without indexes. I want to get the opposite - the indexes that point to non-existing primary keys.