Reputation: 20345
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!
Upvotes: 15
Views: 10353
Reputation: 1129
I would do it with a case statement:
SELECT *,
CASE WHEN column_one = 0 THEN 0
WHEN column_two = 'ADMIN' THEN 1
END AS multi_column
FROM sometable
ORDER BY multi_column;
Upvotes: 0
Reputation: 171491
SELECT *
FROM A
WHERE x='abc'
OR y=0
order by case when x='abc' then 0 else 1 end;
Upvotes: 20