MySQL: Insert else Update

Ever had to check if a record exists using SELECT then perform an INSERT or UPDATE based on the result? Why not combine both the INSERT and UPDATE into one command and remove the SELECT query checking with one easy MySQL feature. Instead of performing two or three queries we can perform just one which will check and perform an INSERT or UPDATE.

Remember performing one query is normally faster than performing multiple queries which is a common mistake allot of programmers make. MySQL is heavily optimised for data processing so it’s best to do as much processing on the database side as possible as you will see a significant performance increase.

Query

The example above will try to insert a new user (Shane) into the users table, the username field is a UNIQUE field and so only one occurrence of the username “Shane” can be used. If there is already a username which matches “Shane” it will skip the INSERT and attempt to UPDATE the field “last_login” with the current date/time where the username is “Shane”.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.