Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving column priority first in SQL Search (LIKE) statement

Tags:

sql

sql-server

This is my SQL Search statement.......

I want to return values on column NAME with first priority and then column Desc_Work.

Select * from posts
where Province = 'Western_Cape'
and NAME LIKE '%Etienne%' 
or Desc_Work LIKE '%Etienne%'

What changes must I make to this to make sure that the rows in column NAME will be displayed first?

like image 722
Etienne Avatar asked Dec 16 '22 20:12

Etienne


1 Answers

ORDER BY CASE
WHEN NAME LIKE '%Etienne%' THEN 1
ELSE 2
END

I also believe that you wanted where Province = 'Western_Cape' and (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%')

UPDATE

Select * from posts
where Province = 'Western_Cape'
and (NAME LIKE '%Etienne%' 
or Desc_Work LIKE '%Etienne%')
ORDER BY CASE
WHEN NAME LIKE '%Etienne%' THEN 1
ELSE 2
END

I assume you need (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%') in brackets - your original query returns records where (Province = 'Western_Cape' and NAME LIKE '%Etienne%' ) or Desc_Work LIKE '%Etienne%')...

like image 84
a1ex07 Avatar answered Dec 28 '22 05:12

a1ex07