Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - Select oldest of 3 dates, but ignore NULLs [duplicate]

I have this Oracle SQL statement to get the oldest of 3 dates:

SELECT LEAST(DATE_1,DATE_2,DATE_3) FROM MYTABLE

However, if one of the dates is NULL, the entire LEAST function will return NULL, regardless of whether the the other dates are not NULL. I would like to get the oldest of the three dates, but ignore any NULL dates, so that the only time LEAST would return NULL is if all three dates are NULL.

I also cannot have the function return incorrect dates, so this will not work:

SELECT LEAST(NVL(DATE_1,SYSDATE),NVL(DATE_2,SYSDATE),NVL(DATE_3,SYSDATE)) FROM MYTABLE

What's the cleanest way to do this?

like image 425
user3163495 Avatar asked Jan 24 '26 14:01

user3163495


2 Answers

Here is one way:

SELECT LEAST(COALESCE(DATE_1, DATE_2, DATE_3),
             COALESCE(DATE_2, DATE_1, DATE_3),
             COALESCE(DATE_3, DATE_2, DATE_1)
            )
FROM MYTABLE
like image 140
Gordon Linoff Avatar answered Jan 27 '26 06:01

Gordon Linoff


How about this?

SELECT
    LEAST
    (
        NVL(DATE_1,DATE '9999-01-01'),
        NVL(DATE_2,DATE '9999-01-01'),
        NVL(DATE_3,DATE '9999-01-01')
    ) LEAST_DATE
FROM MYTABLE;

The only downside is that it returns 9999-01-01 instead of NULL if all three are NULL.

like image 22
Szellem Avatar answered Jan 27 '26 04:01

Szellem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!