Last active
June 27, 2016 16:37
-
-
Save KyleGobel/d21103e009fd8791c71c to your computer and use it in GitHub Desktop.
Insert/Update Upsert Trigger in Postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your first IF will lower the performance of your trigger. I think this can be much simpler. Thanks for the template.