PostgreSQL conditional upserts
So in order to do an "upsert" we use an INSERT
command with a CONFLICT
statement. Then if we need to do some conditional setting in the case of existing data then we can use the "temp table" EXCLUDED
that PostgreSQL provide to us. They have a nice example how to use that in their docs and here's mine example:
INSERT INTO users AS u (email, fullname) VALUES
('darth@example.com', 'Darth Vader'),
('luke@example.com', 'Luke Vader')
ON CONFLICT (email) DO UPDATE
SET fullname = EXCLUDED.fullname || ' (formerly known as ' || u.fullname || ')';
For this to work we have to have an unique
constraint on the column email
and the outcome of this could be:
SELECT email, fullname
FROM users;
| email | fullname |
| --- | --- |
| darth@example.com | Darth Vader |
| luke@example.com | Luke Vader (formerly known as Luke Skywalker) |
Tweet