Do indexes speed up greater than > comparison in MySQL?

前端 未结 3 344
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 12:31

I have an events tables in my db, which includes among others start_date and end_date columns.

I frequently run queries like

where start_date > \         


        
相关标签:
3条回答
  • 2020-12-16 13:04

    Yes, database will use those indexes and it should increase performance.

    Note: it cannot use the two disctinct indexes simultaneously for good performance you need a multi-column index.

    0 讨论(0)
  • 2020-12-16 13:11

    In my experience, indexes are often not used for greater than / less than conditions, because the range is open-ended and thus there will be O(n) matching rows for a table with n rows.

    However, betweens generally do use indexes, as the range is limited, so there will be O(1) matching rows, so you can use this trick:

    where start_date between 'some starting date' and 'some end date'
    and end_date beween 'some starting date' and 'some end date'
    

    Since the end date can't be earlier than the start date, these comparisons still make sense.

    0 讨论(0)
  • 2020-12-16 13:12

    The MySQL optimizer will use the indexes where it thinks it is appropriate to do so:

    A B-tree index can be used for column comparisons in expressions that use the =, >, >=, <, <=, or BETWEEN operators.

    ...

    Sometimes MySQL does not use an index, even if one is available. One circumstance under which this occurs is when the optimizer estimates that using the index would require MySQL to access a very large percentage of the rows in the table. (In this case, a table scan is likely to be much faster because it requires fewer seeks.)

    Source: Comparison of B-Tree and Hash Indexes

    You might find these interesting:

    How MySQL Uses Indexes

    And this answer and this answer to Why does MySQL not use an index for a greater than comparison?.

    0 讨论(0)
提交回复
热议问题