Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates in Oracle using the decode function

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?

like image 358
Freddy Avatar asked Sep 01 '10 15:09

Freddy


People also ask

How can I compare two dates in Oracle?

When using a literal you must specify your date in the format YYYY-MM-DD and you cannot include a time element. Remember that the Oracle date datatype includes a time element, so the date without a time portion is equivalent to 1995-12-31 00:00:00 .

What is use of decode function in Oracle?

The DECODE function returns a value that is the same datatype as the first result in the list. If the first result is NULL, then the return value is converted to VARCHAR2. If the first result has a datatype of CHAR, then the return value is converted to VARCHAR2. If no matches are found, the default value is returned.

How can we use greater than in decode function?

To search for values greater than a search value you can combine the SIGN function with the DECODE statement. The SIGN function returns either -1,0 or 1 depending if a value is less than, equal to or greater than a specified value or expression.

How do I use decode?

DECODE compares the expression to each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database. If a match is not found, then default is returned. If default is omitted, then Oracle returns null.


1 Answers

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.)

like image 130
Allan Avatar answered Oct 01 '22 11:10

Allan