JRehkemper.de

Upsert in PostgreSQL - Update if exists

It is quite a common scenario: You have a table and want to insert a new record, but in case it already exists, you want to update it.
One way would be to start with the update, look at the rows affected and execute the insert if the rowCount is 0.

But there is a neater way. The so called Upsert.

INSERT INTO table1 (id, firstname, lastname, age)
VALUES (1, 'john', 'doe', 25)
ON CONFLICT(id) DO UPDATE
SET
	id = 1,
	firstname = 'john',
	lastname = 'doe',
	age = 25
;

This will try an insert but if there is already an entry with the same id it will update that one.

profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.