I would like to delete rows which contain a foreign key, but when I try something like this:
DELETE FROM osoby WHERE id_osoby='1'
I get this statement:
ERROR: update or delete on table “osoby” violates foreign key constraint “kontakty_ibfk_1” on table “kontakty”
DETAIL: Key (id_osoby)=(1) is still referenced from table “kontakty”.
How can I delete these rows?
To automate this, you could define the foreign key constraint with
ON DELETE CASCADE.I quote the the manual for foreign key constraints:
Look up the current FK definition like this:
Then add or modify the
ON DELETE ...part toON DELETE CASCADE(preserving everything else as is) in a statement like:There is no
ALTER CONSTRAINTcommand. Drop and recreate the constraint in a singleALTER TABLEstatement to avoid possible race conditions with concurrent write access.You need the privileges to do so, obviously. The operation takes an
ACCESS EXCLUSIVElock on tablekontaktyand aSHARE ROW EXCLUSIVElock on tableosoby.If you can’t
ALTERthe table, then deleting by hand (once) or by triggerBEFORE DELETE(every time) are the remaining options.