SQL - Where criteria to find names between A-F

戏子无情 提交于 2019-12-04 08:36:58

In a comment you expand the requirement to include A - Fxxx.

SET @start = 'A'
SET @end   = 'Fxxx'

SELECT
  *
FROM
  table
WHERE
  (name >= @start AND name < @end)
  OR (name LIKE @end + '%')

Note that this does not include functions on the name field; such functions prevent range seeks on indexes. However, the inclusion of the OR degrades the index seek too. Although it's extra code, this actually can be more performant is some cases...

SELECT
  *
FROM
  table
WHERE
  (name >= @start AND name < @end)

UNION ALL

SELECT
  *
FROM
  table
WHERE
  (name LIKE @end + '%')


EDIT

In hindsight, your Solution 2, although you don't like it, is probably the best.

Turning Fxxx to FxxxZZZZZZZZZZ is simple enough with STUFF(), provided that you know the max string length, which you should do as the database is yours.

It doesn't have any functions on the name field, and it doesn't use an OR in the WHERE clause. Which means that you get a pure range seek on any index.

Performance wise, I do not think you can improve on this.

Lamak

You can do:

WHERE name >= 'A' AND name < 'G'

How about this?

WHERE SUBSTR(name, 1, 1) >= 'A' AND SUBSTR(name, 1, 1) <= 'F'

Will this work for you:

select * 
from MyTable
where left(name, 1) between 'a' and 'f'

How much more simple can you make it?

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