I need to compare two dates using the Oracle decode function to see if one is less than or equal
to the other.
I found this article - http://www.techonthenet.com/oracle/functions/decode.php
Which states (at the bottom) that the below decode function will return date2 if date1 > date2 :
decode((date1 - date2) - abs(date1 - date2), 0, date2, date1)
Would this not return date2 if date1 >= date2 ?
Or is it just if date1 > date2?
Is there an easier solution?
That function will return date2 if date2 <= date1. Plugging in the values and translating to pseudo-code, you get if 0 - 0 = 0 then date2 else date1
where both dates are the same.
A better solution, if you're using 8i or later is to use case
:
SELECT CASE WHEN date1 >= date2 THEN date2 ELSE date1 END FROM Your_Table;
Since case
allows inequality operators, it's much more readable.
Or, if you want to be more succinct, you could use the function that's designed to return the lower of n values:
SELECT LEAST(date1, date2) FROM Your_Table;
(There is also a GREATEST
function, which does the opposite.)