You have a column foo, of some string type, with a index on that column. You want to SELECT from the table WHERE the foo column has the prefix 'pre'. Obviously, the index should be able to help here.
Here is the most obvious way to search by prefix:
SELECT * FROM tab WHERE foo LIKE 'pre%';
Unfortunately, this does not get optimized to use the index (in Oracle or Postgres, at least).
The following, however, does work:
SELECT * FROM tab WHERE 'pre' <= foo AND foo < 'prf';
But are there better ways to accomplish this, or are there ways of making the above more elegant? In particular:
- I need a function from
'pre'to'prf', but this has to work for any underlying collation. Also, it's more complicated than above, because if searching for e.g.'prz'then the upper bound would have to be'psa', and so on. - Can I abstract this into a stored function/procedure and still hit the index? So I could write something like
... WHERE prefix('pre', foo);?
Answers for all DBMSes appreciated.
Where Foo like 'bar%'will enable an index.LIKE 'pre%'can't use an index in those DBMSes. It is sargable in SQL Server, at least.