Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing an UPDATE or INSERT depending whether a row exists or not in MySQL

In MySQL, I'm trying to find an efficient way to perform an UPDATE if a row already exists in a table, or an INSERT if the row doesn't exist.

I've found two possible ways so far:

  1. The obvious one: open a transaction, SELECT to find if the row exists, INSERT if it doesn't exist or UPDATE if it exists, commit transaction
  2. first INSERT IGNORE into the table (so no error is raised if the row already exists), then UPDATE

The second method avoids the transaction.

Which one do you think is more efficient, and are there better ways (for example using a trigger)?

like image 693
Enrico Detoma Avatar asked Nov 30 '22 06:11

Enrico Detoma


1 Answers

INSERT ... ON DUPLICATE KEY UPDATE

like image 191
manji Avatar answered Dec 10 '22 09:12

manji