1

I am trying to delete rows from a table that has a self-referential foreign key:

CREATE TABLE items (
    id        SERIAL  PRIMARY KEY,
    parent_id INTEGER      NOT NULL,
    FOREIGN KEY (parent_id) REFERENCES refers(id)
);

Now when I simply do:

DELETE FROM items;

the query freezes forever. If I kill it with Ctrl-C, it says

ERROR: canceling statement due to user request CONTEXT: SQL statement "UPDATE ONLY "public"."items" SET "parent" = NULL WHERE $1 OPERATOR(pg_catalog.=) "parent""

How to delete rows from such a table?

1 Answer 1

3

According to this answer, foreign keys in Postgres are implemented as triggers, so you can temporarily disable foreign key checks like this:

ALTER TABLE items DISABLE TRIGGER ALL; 
DELETE FROM items; 
ALTER TABLE items ENABLE TRIGGER ALL;
Sign up to request clarification or add additional context in comments.

2 Comments

Please post a minimal reproducible example for debug help. By the way your table Items does not contain a self-reference , The column foreign key parent_id references the table refer not item. Also if you actually want a self reference in a table be extremely cautious of not null for the child column. That forces an entry to be its own parent. IMHO not a good design.
there's no way to post a minimal example. The freeze was not a deadlock; it was a very very long operation)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.