Insert into a table or update if exists MySQL

DUPLICATE KEY can be used to DUPLICATE to Insert into a table or update if exists in MySQL.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
INSERT INTO tableName (id, name, age)
VALUES(10, "Roy", 34)
ON DUPLICATE KEY
UPDATE
name="Roy", age=34
INSERT INTO tableName (id, name, age) VALUES(10, "Roy", 34) ON DUPLICATE KEY UPDATE name="Roy", age=34
INSERT INTO tableName (id, name, age) 
VALUES(10, "Roy", 34) 
ON DUPLICATE KEY 
UPDATE    
name="Roy", age=34

It will insert a new record if no record exists with id = 10, Otherwise update if any record exists with id = 10;