Insert into a MySQL table or update if exists
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.
For example:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
Let’s say the unique key is ID
, and in my Database, there is a row with ID = 1
. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE
it will ignore the error, but it still won’t update.
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
Check out REPLACE
http://dev.mysql.com/doc/refman/5.0/en/replace.html
REPLACE into table (id, name, age) values(1, "A", 19)
When using batch insert use the following syntax:
INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
name = VALUES (name),
...
Any of these solution will work regarding your question:
INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
or
INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
or
REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
If you want to know in details regarding these statement visit this link
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.