Say, there is a table A, with columns a
and b
, both are int
type with unique index.
I want to select from A
where
- if there a tuple whose
a
equal to 100, then return this tuple - otherwise, return a tuple whose
b
is smallest and less than 10000
This can be easily done with two SQL statements:
select * from A where a = 100
If first SQL returns nothing, then run:
select * from A where b < 10000 order by b limit 1
But I want to implement this logic in a single SQL statement. Is it possible?
2
Answers
You’ll get unneeded column "priority", if you don’t want to list all columns in the SQL, and use
*
, but I suppose that it is not a problem.I don’t know why you want that to be one statement, but
UNION ALL
, sorting and aLIMIT
should do the trick:The disadvantage is that you have to execute the second statement even if the first returns a result, so running two statements might be preferable.
A more complicated version that might perform better would be