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.
INSERT INTO users (username, email, account_creation) VALUES ('Shane', 'firstname.lastname@example.org', NOW()) ON DUPLICATE KEY UPDATE last_login = NOW()
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”.