Skip to content

Instantly share code, notes, and snippets.

@KyleGobel
Last active June 27, 2016 16:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KyleGobel/d21103e009fd8791c71c to your computer and use it in GitHub Desktop.
Save KyleGobel/d21103e009fd8791c71c to your computer and use it in GitHub Desktop.
Insert/Update Upsert Trigger in Postgres
CREATE OR REPLACE FUNCTION upsert_user()
RETURNS trigger AS
$upsert_user$
declare
existing record;
begin
if (select EXISTS(select 1 from users where user_id = NEW.user_id)) then
select user_name, user_class, user_age into strict existing from users where user_id = new.user_id;
--found; update, and return null to prevent insert
UPDATE users SET
user_class = coalesce(new.user_class, existing.user_class),
user_name = coalesce(new.user_name, existing.user_name),
user_age = coalesce(new.user_age, existing.user_age),
modified = current_timestamp
WHERE user_id = new.user_id;
return null;
end if;
new.modified = current_timestamp;
return new;
end
$upsert_user$
LANGUAGE plpgsql;
create trigger users_insert
before insert
on users
for each row
execute procedure upsert_user();
@kixorz
Copy link

kixorz commented Mar 20, 2016

Your first IF will lower the performance of your trigger. I think this can be much simpler. Thanks for the template.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment