Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prioritize SQL WHERE clause

Basically I want to do this:

SELECT * FROM `table` WHERE x = 'hello' OR x = 'bye' LIMIT 1';

I want it to return 1 value, but to prioritize results from the 1st where clause. So if there exists a row where column x's value is "hello", it will not return the result from the 'bye' value. If the "hello" value doesn't exist though, it will return the result from the 'bye' value.

Can't figure out a way to do it even though it seems fairly trivial. Any ideas?

like image 326
JaTochNietDan Avatar asked Dec 11 '12 22:12

JaTochNietDan


1 Answers

One way to do this is using order by:

SELECT *
FROM `table`
WHERE x = 'hello' OR x = 'bye'
order by (case when x = 'hello' then 1 else 2 end)
LIMIT 1'

The "1" and "2" are just arbitrary numbers being used to prioritize the rows. Values of 'hello' get "1" so they are ordered before other values.

like image 82
Gordon Linoff Avatar answered Oct 23 '22 22:10

Gordon Linoff