Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL replace vs. doing an insert or update statement

Tags:

java

sql

mysql

I was wondering what the advantages/disadvantages or doing a MySQL replace vs. doing either an update or insert statement are.

Basically,

doing

dao.replaceEntry(entry);

instead of:

if(existing){
     dao.insertEntry(entry);
} else {
     dao.updateEntry(entry);
}

Also, would it be misleading to call the dao.replaceEntry call dao.insertOrUpdate?

like image 814
stevebot Avatar asked Jan 25 '26 13:01

stevebot


1 Answers

I would do insertOrUpdate instead of replace. As per Mysql's docs

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

In case the row exists it is performing a delete and then inserting a new row. Update is the better way to do it then delete and insert as the REPLACE is doing i.e., one operation vs. two.

One more issue I can think of is having triggers or cascade delete in the database. As in case of REPLACE you mind end up having related rows deleted as REPLACE will first delete and then insert if the row with the same ID already exists.

like image 55
Faisal Feroz Avatar answered Jan 27 '26 03:01

Faisal Feroz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!