Sample Header Ad - 728x90

Is it bad practice to just attempt to delete rows that may be referenced by other tables, and skip them if they fail?

3 votes
3 answers
126 views
As a scheduled cleanup action, I'm looking to delete orphaned rows in a certain table that can be referenced to by various other tables. Now I could go with a difficult-to-implement reference counting system which makes tons of other cascaded deletes much harder, or I could check ALL the possible tables for references pointing at the data. But I can also just simply occasionally try to delete the rows and skip the ones where this fails because of a foreign key constraint violation. Is there anything wrong with this practice? I'm not too worried about performance, if that becomes an issue I can just add a date column for when it was last attempted. Ideally I'd avoid defining functions for it, but some pseudo-code (I know nothing of postgreSQL functions so bear with me for any syntax errors) I'd imagine could quite easily do it: ``` CREATE OR REPLACE FUNCTION try_delete_or_update(p_id INT) RETURNS VOID AS $$ BEGIN DELETE FROM public.file WHERE last_delete_attempt < 1 month ago EXCEPTION WHEN foreign_key_violation THEN UPDATE public.file SET last_delete_attempt = now() WHERE last_delete_attempt < 1 month ago; END; $$ LANGUAGE plpgsql;
Asked by Sebastiaan van den Broek (206 rep)
Jun 26, 2025, 05:40 AM
Last activity: Jun 30, 2025, 12:24 PM