简体   繁体   中英

mysql UPDATE, performance WHERE check vs no check

I have a very long table that has 10000 rows. 9500 rows have a column set to 1 and the remaining 500 have that column set to 0. I want to update the table so all rows have that column set to 1.

Would it be faster to use WHERE column = 0 or is it better to skip the WHERE and just UPDATE all ? Im using a prepared statement.

  • thanks

This is an interesting question. In general, I would say it is better to have where column = 0 . It should never be detectably worse, but in MySQL it might not make a difference.

With no index on the column, then the query will need to read all the rows anyway in order to identify the ones that need to be updated. So, the query is going to do a full table scan regardless. Even with an index, the optimizer may still choose a full table scan, unless you have a clustered index on column .

Then, the overhead on doing an update is maintaining the log. I'm pretty sure that MySQL only logs actual changes to the database. In other words, it is doing the comparison anyway. So, MySQL is not going to "re-update" values to the same value. Note: not all databases behave this way.

All that said, I would always put the where column = 0 if that is your intention. On 10,000 rows, performance isn't the big issue. Clarity of code ranks higher, in my opinion. Also, I write code for multiple databases, so I prefer to write code that will work well across all of them.

With my script execution time measurements, for the MariaDB it's pretty much the same result with that queries (I mean result & time).

I will try it on MySQL too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM