It seems so simple, but I could not find the answer to this question.
What I need? A master table with rows that delete themselves when they are not referenced (via foreign keys). The solution may or may not be specific to PostgreSql.
How? One of my approaches to solving this problem (in fact, the only approach so far) includes the following: for each table that references this main table, on UPDATE or DELETE rows, to check the reference row in the main, how many others other lines still refer to the reference line. If it drops to zero, I also delete this line in master.
(If you have a better idea, I would like to know!)
More: I have one main table that many others link to.
CREATE TABLE master ( id serial primary key, name text unique not null );
All other tables have the same format:
CREATE TABLE other ( ... master_id integer references master (id) ... );
If one of them is not NULL , they refer to a string in master . If I go over this and try to delete it, I will get an error message because it is already mentioned:
ERROR: update or delete on table "master" violates foreign key constraint "other_master_id_fkey" on table "other" DETAIL: Key (id)=(1) is still referenced from table "other". Time: 42.972 ms
Note that it does not take too long to figure it out, even if I have many tables referencing master . How can I find this information without error?
sql database postgresql
cassava
source share