How do I UPDATE a row in a table or INSERT it if it doesn't exist? How do I UPDATE a row in a table or INSERT it if it doesn't exist? postgresql postgresql

How do I UPDATE a row in a table or INSERT it if it doesn't exist?


MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:

REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');

This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.


SQLite supports replacing a row if it already exists:

INSERT OR REPLACE INTO [...blah...]

You can shorten this to

REPLACE INTO [...blah...]

This shortcut was added to be compatible with the MySQL REPLACE INTO expression.


I would do something like the following:

INSERT INTO cache VALUES (key, generation)ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.