Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT vs UPDATE performance with index

Tags:

If I SELECT IDs then UPDATE using those IDs, then the UPDATE query is faster than if I would UPDATE using the conditions in the SELECT.

To illustrate:

SELECT id FROM table WHERE a IS NULL LIMIT 10; -- 0.00 sec UPDATE table SET field = value WHERE id IN (...); -- 0.01 sec 

The above is about 100 times faster than an UPDATE with the same conditions:

UPDATE table SET field = value WHERE a IS NULL LIMIT 10; -- 0.91 sec 

Why?

Note: the a column is indexed.

like image 582
rid Avatar asked Jul 14 '11 15:07

rid


People also ask

Does indexing improve update performance?

The update performance, just like insert and delete , also depends on the number of indexes on the table. The only difference is that update statements do not necessarily affect all columns because they often modify only a few selected columns.

Is update faster than SELECT?

If I SELECT IDs then UPDATE using those IDs, then the UPDATE query is faster than if I would UPDATE using the conditions in the SELECT .

Do indexes affect performance of updates and inserts?

Yes, it absolutely does affect performance for INSERT\UPDATE\DELETE operations. When data has been manipulated, all of the affect indexes need to also reflect the update. You can consider using a single index to span across the use of multiple queries.

Does database index improve speed of update operation?

Database indexes make database updates slower and faster at the same time.


2 Answers

Most likely the second UPDATE statement locks much more rows, while the first one uses unique key and locks only the rows it's going to update.

like image 101
Maxim Krizhanovsky Avatar answered Sep 21 '22 17:09

Maxim Krizhanovsky


The two queries are not identical. You only know that the IDs are unique in the table.

UPDATE ... LIMIT 10 will update at most 10 records.

UPDATE ... WHERE id IN (SELECT ... LIMIT 10) may update more than 10 records if there are duplicate ids.

like image 28
Benoit Avatar answered Sep 19 '22 17:09

Benoit