Skip to content
Advertisement

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I have a SQL query where I want to insert multiple rows in single query. so I used something like:

The problem is when I execute this query, I want to check whether a UNIQUE key (which is not the PRIMARY KEY), e.g. 'name' above, should be checked and if such a 'name' already exists, the corresponding whole row should be updated otherwise inserted.

For instance, in the example below, if 'Katrina' is already present in the database, the whole row, irrespective of the number of fields, should be updated. Again if 'Samia' is not present, the row should be inserted.

I thought of using:

Here is the trap. I got stuck and confused about how to proceed. I have multiple rows to insert/update at a time. Please give me a direction. Thanks.

Advertisement

Answer

Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).


For earlier versions use the keyword VALUES (see reference, deprecated with MySQL 8.0.20).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement