views:

24

answers:

3

Let's say I have table [users] with the field [Name] and I've written a query in my application to search by name.

The names in the database are:

Lala Ally

My SQL query is:

SELECT * FROM users WHERE [Name] LIKE '%al%'

where 'al' is my search term.

How would I sort the results by search term found in the beginning i.e. '%al' and only afterwards '%al%'.

The result set should be

Ally Lala

I'm using SQL SERVER.

Thanks.

+2  A: 

Something like this:

SELECT 0, [Name] FROM users WHERE [Name] LIKE 'al%'

UNION

SELECT 1, [Name] FROM users WHERE [Name] LIKE '%al%'
  AND NOT [Name] LIKE 'al%'

ORDER BY
  1, 2
Andrei K.
If you have values Ally,Lally,bbally then this will return you results as Ally,bbally,Lally whereas the OP needs it in Ally,Lally,bbally order.
Sachin Shanbhag
A: 

If your DBMS supports it, I guess you could wrap your select in another select that uses index_of on the name, such as:

select index_of('al', Name) as sortorder, * from (select * FROM users WHERE [Name] LIKE '%al%')
order by sortorder
klausbyskov
+2  A: 

Try this. This will work for all strings as you require assuming you are using sql server-

SELECT * FROM users WHERE [Name] LIKE '%al%'
ORDER BY PATINDEX('%al%',[Name])
Sachin Shanbhag
I like this answer, but it didn't work when I tested it. I think the following answer will work. SELECT [name], PATINDEX('%al%',[name]) from users WHERE [name] like '%al%' ORDER by PATINDEX('%al%',[name])
Fillet
SELECT patindex('al','lala') -> 0. SELECT patindex('%al%','lala') -> 2. I just tested on SQL-Server 2005. It looks to me like you need the %al%.
Fillet
@Fillet - I am sorry, you are right. You need a %al% in PATINDEX. Thank you for the information. Have edited my answer.
Sachin Shanbhag
SQL-Server 2005. I got this message "'PATHINDEX' is not recognized an an integrated function". I think it should be PATINDEX. After I removed the H it ran, but I think it needs the % to do the order correctly.
Fillet
OK, now it works. Upvote from me now, as it's simple and general.
Fillet