Dave's Brain

Browse - 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

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.