Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order By a field being equal to a specific value?

Tags:

sql

mysql

Let's say I have this MySQL query:

SELECT * FROM A WHERE x='abc' OR y=0;

How can I prioritize the rows so that cases where x='abc' are ordered FIRST? If y=0 but x!='abc', I want those rows to come after cases where x='abc'.

Can this be accomplished with a simple ORDER BY clause?

Thanks!

like image 498
DivideByHero Avatar asked Aug 10 '10 20:08

DivideByHero


1 Answers

SELECT *
FROM A 
WHERE x='abc' 
    OR y=0
order by case when x='abc' then 0 else 1 end;
like image 131
D'Arcy Rittich Avatar answered Oct 22 '22 06:10

D'Arcy Rittich