简体   繁体   中英

Is sql with more where condition faster than those with less in mysql?

I hava big table need to be queried by a datetime column every 5 minutes.

My solution is like this:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and tag_col = 0;

,and do something with the result set,and if the "something" succeeds,then update the row and set the tag_col to 1.

One of my colleague has a solution like this:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and datetime_col >= '2019-05-26 20:44:00' and tag_col = 0;

,and do something with the result set,and if the "something" fails,update the row and add 5 minutes to the datetime_col(so that it will be selected next time),and if the "something" succeeds,also update the row and set the tag_col to 1.

My question is whose sql is faster (or they are equally fast) when there is index on the datetime_col? Thanks.

If you execute this query:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'

You are presumably going to be returns lots and lots of data, because -- by your description -- you have a "big table". You then have to forage through this to get the results you want.

If you execute:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
order by datetime_col desc;

Then I think MySQL will use the index and be able to return the rows that you want. However, you are still returning lots and lots of rows. You should test if the performance is okay.

Your colleague's query is:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00' and
      datetime_col >= '2019-05-26 20:44:00';'

This returns only the rows you want -- presumably a much smaller set. It should use the index to find those rows.

I would expect that your colleague is correct. Even if the rows don't exist and you have to issue another query, that is probably faster than returning almost the entire table.

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