Mysql ON DUPLICATE KEY UPDATE for multiple rows insert in single query
To perform a bulk **INSERT**
with **ON DUPLICATE KEY UPDATE**
, list the new values and define the update rule per column. This way, existing rows will be modified with the new data in case of key conflicts:
This means for each duplicate key encountered, col1
and col2
will be updated based on the corresponding values in the VALUES
list.
The Power of ON DUPLICATE KEY UPDATE
ON DUPLICATE KEY UPDATE is highly useful during bulk insertions. You combine the power of INSERT
and UPDATE
in one neat package. It lowers database load, reduces network latency and simplifies your application layer.
Starting from MySQL 8.0.19, you'd get to use the VALUE
keyword instead of VALUES(col1)
which enhances your code readability. The VALUE
keyword points out the new values you intend to update, a true example of reading code like a book.
Non-primary unique keys require some attention, grasp the unique constraints and avoid unexpected data overrides. Bulk operations will get a substantial efficiency boost thanks to this MySQL feature.
SQL Server Alternative Approach
On SQL Server, a temporary table with the MERGE
statement will give you a similar effect. The MERGE
statement offers when matched then update
and when not matched then insert
logic.
Boosting Performance While Ensuring Security
Protect against SQL injection by using placeholders (?
) and passing values as arrays. This ensures robust security while performing your bulk data operations.
In a JavaScript environment, using async/await
, coupled with Promises
, means efficient asynchronous database operations and robust error handling. Arrow functions are another way to make your code more readable.
Keeping Up with Decimal Values
To ensure accurate handling of decimal values, utilize the backtick symbol (`). This preserves the true decimal points during database transactions:
Was this article helpful?