Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 829
Keshan Avatar asked Nov 17 '10 14:11

Keshan


People also ask

Does MySQL update insert if not exists?

Often you have the situation that you need to check if an table entry exists, before you can make an update. If it does not exist, you have to do an insert first. Unfortunately, this the 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns.

Can I insert with update MySQL?

When you insert a new row into a table if the row causes a duplicate in UNIQUE index or PRIMARY KEY , MySQL will issue an error. However, if you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement, MySQL will update the existing row with the new values instead.

Does insert update?

If the row being inserted already exists, INSERT OR UPDATE performs an UPDATE operation, updating the row with the specified column values. An update occurs even when the specified data values are identical to the existing data.


1 Answers

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 
like image 200
Donnie Avatar answered Sep 30 '22 07:09

Donnie