Today I Learned

hashrocket A Hashrocket project

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) |
See More #sql TILs
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.