Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIN from a list of fields in a record

Tags:

sql

oracle

I have a table with 3 date fields. I am trying to find the smallest of the three dates in each record.

What I'd like to do is this:

Select id, some_value, date_a, date_b, date_c,
        min(date_a, date_b, date_c) as smallest_date
from some_table;

but this clearly doesn't work. There is no rule that suggests which date might be larger than others, and sometimes any number of them (none to all) could be NULL. I am sure I've seen an elegant solution for this somewhere that didn't involve lots of ugly case statements and checks for null, but I just can't seem to remember how to do it.

(Oracle 10g)

like image 776
FrustratedWithFormsDesigner Avatar asked Feb 24 '23 14:02

FrustratedWithFormsDesigner


1 Answers

You want the LEAST function:

SELECT LEAST(date_a, date_b, date_c) as smallest_date
FROM some_table;

AFAIK, if some could be null, then you're going to have to use NVL on each column to set a default:

SELECT LEAST(NVL(date_a,sysdate), NVL(date_b,sysdate), NVL(date_c,sysdate)) as smallest_date
FROM some_table;
like image 160
DCookie Avatar answered Mar 03 '23 14:03

DCookie