In PostgreSQL how can I create a trigger that deletes the previous row when a new row is…
- User
In PostgreSQL how can I create a trigger that deletes the previous row when a new row is appended with the same primary key?
Assistant
Here is how you can create a trigger in PostgreSQL that deletes the previous row when a new row with the same primary key is inserted:
sqlCREATE OR REPLACE FUNCTION delete_old_row() RETURNS trigger AS $$ BEGIN DELETE FROM table_name WHERE id = NEW.id; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER delete_old_row BEFORE INSERT ON table_name FOR EACH ROW EXECUTE PROCEDURE delete_old_row();This creates a trigger function
delete_old_row()that deletes any existing row with the same primary key as the new row being inserted.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.