Doing upsert (insert or update) in MariaDb

MariaDb

Upsert in MariaDB

It is a very common scenario when you need to either insert a new row or update one if it already exists. It is also important to do it as an atomic operation with a single DB call

In MariaDB (MySql syntax) the way to do insert or update in one command is as following:


INSERT INTO SomeTable (`Key`,Value) VALUES (@key,@value) 
                    ON DUPLICATE KEY UPDATE Value=@value;

It checks whether there is a conflict with the inserted key and if there is, it does the update

More information can be found here: https://mariadb.com/kb/en/insert-on-duplicate-key-update/

Post a Comment

Previous Post Next Post