Indexing SQL for Between query with only one match?

为君一笑 提交于 2019-11-30 18:45:29

Are the ranges always non-overlapping? You mention that there is always only one match. If they are, you can write it as:

SELECT * FROM table1 
   WHERE 8 <= Col2 
   ORDER BY Col2 ASC
   LIMIT 1

This will give you the row with the lowest value of Col2 which is above 8 - which is the range you are interested in. The index would only be needed on Col2, and the cost should be small.

Since you did not mention the DBMS you are using, the LIMIT 1 should be replaced with whatever your DB uses to fetch the first N results.

You will have to check Col1 <= your_value in code to ensure that the value you are looking for really is in the range.

I think I have found the answer. I had to start by creating an Unique Clustered Index on Col1, then create an Unique Unclustered Index on Col2. The query then had to be updated to force lookups on each Index.

select * from table1 where Col1 = 
    (select max(Col1) from table1 where Col1 <= 8)
and Col2 = 
    (select min(Col2) from table1 where Col2 >= 8)

Execution plan now reports 0.0098 cost and 1 row handled.

select * from table1 where Col1 <= 8 and Col2 >= 8

Maybe the "between" with two columns is causing an issue.

Also, you should just have 1 composite index on both columns (Col1, Col2).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!