Subject | Re: Parameterised like query won't use index in the plan |
---|---|
Author | roydamman |
Post date | 2012-10-30T07:45:44Z |
> Don't use LIKE for an equivalence query. The purpose of LIKE is to pass a string with wildcard characters (_ or % in SQL). Your literal query self-converts to an equivalence query, viz.,Hello Helen, you are right, not to use LIKE for a normal search. But LIKE was used to give the users of my programs, the most flexibel search options. It seems not a good practice.
>
> select * from mytable where myfield = 'test'
> or to a STARTING WITH query
> select * from mytable where myfield starting with 'test'
>
> Both of these operators use indexes if they are available.
>
> Your parameterised query is prepared in anticipation of a string that starts or ends (or both) with a wildcard, e.g., test%, %test or %test%. In preparing this query the engine does not know what it will get in the parameter. It can't speculatively prepare a plan that anticipates the possibility that it will get a literal with no wildcards (like your example) or test% (which it can convert to STARTING WITH) - so the plan is stuck with LIKE's inability to use an index.
>
Thank you,
Roy