I want to write a query that will fetch nearest matching strings of given string and its sub-strings in that order.
For example, lets say am having table of all names in a column. If I want to search name "ATUL"
, then results should list all distinct names matching first "ATUL%"
then "ATU%"
then "AT%"
and then "A%"
and finally all remaining records.
(Then I am going to pick up first N records out of it based on my needs)
Distinct union of queries is one solution I can think of. Is there any more efficient way to do this?
UPDATE:
Thanks for answers below. Meanwhile I was trying something on my own and found this query producing expected results, provided I have username column indexed
select * FROM all_usernames WHERE (username LIKE 'atul%') or (username LIKE 'atu%') or (username LIKE 'at%') or (username LIKE 'a%') or (username LIKE '%');
But is it standard behaviour or is it that I am just getting it coincidently?