HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

SQL query with Like operator with Leading Wildcards

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
leadingoperatorsqlwithquerywildcardslike

Problem

I have a query as follows:

select top (30000) * from table1 where licenseplate like '%as43bv%'


I have an index on licenseplate but the query will not hit the index due to leading wildcard.

Since the column queries license plate numbers full text search wont come to any benefit we are searching on some letter or number rather than words

The above query fetches millions of rows and brings the CPU usage around 100%.

Is there any efficient way to rewrite the query and make use of the indexes.

Solution

What first comes to mind, is that if you are searching for some symbols inside the licenseplate that will always start, for example at 4th symbol (example data 123as43bvxxx ), and it will be always be fixed, you can consider adding computed persisted column to your table

alter table [table1]
add LicenseplateComputed as substring(licenseplate,4,50) persisted


And then create nonclustered index on your newly added computed column "LicenseplateComputed"

After this you will be able to query your table

select top (30000) * from table1 where LicenseplateComputed like 'as43bv%'


and it will perform efficient Index Seek

Code Snippets

alter table [table1]
add LicenseplateComputed as substring(licenseplate,4,50) persisted
select top (30000) * from table1 where LicenseplateComputed like 'as43bv%'

Context

StackExchange Database Administrators Q#252315, answer score: 2

Revisions (0)

No revisions yet.