Programming Tips - How can I do: If (key exists) update else insert
Date: 2016oct10
Product: mysql
Keywords: create, replace, upsert
Q. How can I do: If (key exists) update else insert
A.
Mysql:
Use INSERT ... ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
This is atomic and doesn't require a transaction from the programmer.
Unfortunately the syntax requires that you code insert syntax and an update.
Postgresql:
Use INSERT ... ON CONFLICT UPDATE
https://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT