Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, is UPDATE always faster than DELETE+INSERT?

Say I have a simple table that has the following fields:

  1. ID: int, autoincremental (identity), primary key
  2. Name: varchar(50), unique, has unique index
  3. Tag: int

I never use the ID field for lookup, because my application is always based on working with the Name field.

I need to change the Tag value from time to time. I'm using the following trivial SQL code:

UPDATE Table SET Tag = XX WHERE Name = YY; 

I wondered if anyone knows whether the above is always faster than:

DELETE FROM Table WHERE Name = YY; INSERT INTO Table (Name, Tag) VALUES (YY, XX); 

Again - I know that in the second example the ID is changed, but it does not matter for my application.

like image 235
Roee Adler Avatar asked Aug 13 '09 12:08

Roee Adler


People also ask

Is delete and insert faster than UPDATE?

It is faster than updating then inserting the ones that did not already exist.

Which is faster insert or UPDATE SQL?

Insert would be faster because in case of update you need to first search for the record that you are going to update and then perform the update.

Which is faster insert or delete in SQL?

That said, if you're keeping notably more records than you're deleting, and if you don't have a lot of indexes on the original table, it's entirely possible that deleting would be faster. NOTE: If you don't need to keep all columns, then the INSERT method is almost certainly your best bet.

Is UPDATE slower than insert?

Insertion is inserting a new key and update is updating the value of an existing key. If that is the case (a very common case) , update would be faster than insertion because update involves an indexed lookup and changing an existing value without touching the index.


1 Answers

A bit too late with this answer, but since I faced a similar question, I made a test with JMeter and a MySQL server on same machine, where I have used:

  1. A transaction Controller (generating parent sample) that contained two JDBC Requests: a Delete and an Insert statement
  2. A sepparate JDBC Request containing the Update statement.

After running the test for 500 loops, I have obtained the following results:

DEL + INSERT - Average: 62ms

Update - Average: 30ms

Results: Results

like image 200
Dyptorden Avatar answered Sep 17 '22 16:09

Dyptorden