% in the beginning of like clause

前端 未结 7 1459
你的背包
你的背包 2021-01-06 10:10

I heard that its not advised to use % in the beginning of LIKE clause in SQL Server due to performance reasons.Why is this is so?

Some more details on this will help

7条回答
  •  走了就别回头了
    2021-01-06 11:03

    why is LIKE '%...' not good? you can't use any index and must scan the entire table.

    here is a good example:

    go to the phone book and find me all names that match '%ch'. That will take quite a while since you are not able to use the clustered index, and must scan the entire book!

    Given the data 'abcdefg'

    WHERE Column1 LIKE '%cde%'  --can't use an index
    
    WHERE Column1 LIKE 'abc%' --can use and index
    
    WHERE Column1 Like '%defg' --can't use an index, but see note below
    

    Note: If you have important queries that require '%defg', you could use a persistent computed column where you REVERSE() the column and then index it. Your can then query on:

    WHERE Column1Reverse Like REVERSE('defg')+'%' --can use the persistent computed column's index
    

    to add a persisted computed column (that reverses the string) and index on it, use this code:

    ALTER TABLE YourTable ADD ReversedYourString  AS REVERSE(YourString) PERSISTED 
    
    CREATE NONCLUSTERED INDEX IX_YourTable_ReversedYourString 
    ON YourTable (ReversedYourString) 
    

提交回复
热议问题