postgresql and Delete statement violates foreign key constraint

Pompom Pidou picture Pompom Pidou · Feb 5, 2012 · Viewed 10.5k times · Source

I have a problem with my delete statement.

I have two tables:

table vehicule_loan(
    vehicule TEXT NOT NULL UNIQUE,
);

table vehicule_uid (
    id UUID NOT NULL DEFAULT uuid_generate_v4(),
    vehicule TEXT NOT NULL REFERENCES vehicule_loan(vehicule) ON DELETE NO ACTION
);

When I delete a vehicule from the table vehicule_loan I want that referencing rows in the table vehicule_uid are kept.

But when I try to delete one I get this error:

ERROR:  update or delete on table "vehicule_loan" violates foreign key constraint "vehicule_uid_vehicule_fkey" on table "vehicule_uid"

I think I understand the error: After I delete a vehicule from the table vehicule_loan, the vehicule in vehicule_uid would point to nothing.

But is there a way to keep the rows in vehicule_uid ?

Answer

dani herrera picture dani herrera · Feb 5, 2012

You should allow NULL values in the foreign key attribute and define the foreign key constraint as ON DELETE SET NULL.

I quote chapter 5.3. Constraints from the PostgreSQL manual:

There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted.

Could look like this:

table vehicule_uid (
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    vehicule text REFERENCES vehicule_loan(vehicule) ON DELETE SET NULL
);

With this setting, when you delete a row in vehicule_loan all referencing rows in vehicule_uid remain in database.