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.