Ignore NULL values in GREATEST and LEAST functions

Moderator: NorbertKrupa

Post Reply
User avatar
Julie
Master
Master
Posts: 221
Joined: Thu Apr 19, 2012 9:29 pm

Ignore NULL values in GREATEST and LEAST functions

Post by Julie » Thu Dec 06, 2012 5:12 pm

Hi guys,

Can anyone think of a way to get the greatest and least functions to ignore NULLs?

That is, these examples return NULL:

Code: Select all

dbadmin=> SELECT greatest('A', 'B', 'C', NULL);
greatest
----------

(1 row)

dbadmin=> SELECT least('A', 'B', 'C', NULL);
least
-------

(1 row)
I'd like to ignore the NULL values and get these results if possible:

Code: Select all

dbadmin=> SELECT greatest('A', 'B', 'C', NULL);
greatest
----------
C
(1 row)

dbadmin=> SELECT least('A', 'B', 'C', NULL);
least
-------
A
(1 row)
Thanks!
Thanks,
Juliette

id10t
GURU
GURU
Posts: 732
Joined: Mon Apr 16, 2012 2:44 pm

Re: Ignore NULL values in GREATEST and LEAST functions

Post by id10t » Thu Dec 06, 2012 5:53 pm

HI Julie!

Only by filtering NULLs you can solve it. No exists such data type char/varchar/number/date that a greatest and a lowest value in the same time, so no casting as option - only filtering, i.e. ignorance in selection not in function.

harryrundles
Intermediate
Intermediate
Posts: 96
Joined: Thu Jul 19, 2012 12:33 am

Re: Ignore NULL values in GREATEST and LEAST functions

Post by harryrundles » Fri Dec 07, 2012 2:23 pm

Here's a suggestion...

On columns where you know there could be NULLS that you want to ignore, use the NVL function to replace the NULL with an appropriate value that can't be the greatest or the least.

Example for text:

Code: Select all

dbadmin=> SELECT greatest('A', 'B', 'C', NVL(NULL, CHR(0)));
 greatest
----------
 C
(1 row)

dbadmin=> SELECT least('A', 'B', 'C', NVL(NULL, CHR(177)));
 least
-------
 A
(1 row)
Example for numbers:

Code: Select all

dbadmin=> SELECT greatest(1, 2, 3, NVL(NULL, -9999999999999999999));
 greatest
----------
        3
(1 row)

dbadmin=> SELECT least(1, 2, 3, NVL(NULL, 9999999999999999999));
 least
-------
     1
(1 row)
So as skwa indicated my suggestion is kind of filtering out NULLS...
Thanks,
Harry

User avatar
Julie
Master
Master
Posts: 221
Joined: Thu Apr 19, 2012 9:29 pm

Re: Ignore NULL values in GREATEST and LEAST functions

Post by Julie » Sat Dec 08, 2012 2:00 pm

Thanks, guys! Great answers!
Thanks,
Juliette

Post Reply

Return to “Vertica SQL”