We're Moving!

The Vertica Forum is moving to a new OpenText Analytics Database (Vertica) Community.

Join us there to post discussion topics, learn about

product releases, share tips, access the blog, and much more.

Create My New Community Account Now


GREATEST ignoring NULL? — Vertica Forum

GREATEST ignoring NULL?

edited February 12 in General Discussion

Is there a function that works like GREATEST that returns the greatest non-null value?

GREATEST ( 1, 0, 1, 1, 0, 0, null, 1, 0) => 1
GREATEST ( 0, 0, null, 0, 0) => 0
GREATEST ( null, null, null, null ) => null

My use case is easily getting the max of a potentially large number of columns for all rows where the columns are not all null e.g.

SELECT GREATEST (a1, a2, ..., a1024) AS a
FROM table
WHERE GREATEST (a1, a2, ..., a1024)  IS NOT NULL

(Here I'm using a1 as a simple version but in practice each could be an expression).

GREATEST doesn't work becuase it returns NULL if any are null, GREATEST(1,1,null, 0,1) => NULL
COALESCE won't work because it'll return the first non-null value, not the greatest e.g. coalesce(null,0,1); => 0

Tagged:

Answers

  • moshegmosheg Vertica Employee Administrator

    For your original use case with many columns, you could write:

    SELECT MAX(value)
    FROM (
        SELECT EXPLODE(ARRAY[a1, a2, ..., a1024]) OVER()
        FROM table
    ) foo;
    

    Or alternatively:

    SELECT EXPLODE(ARRAY[a1, a2, ..., a1024]) OVER()
    FROM table
    ORDER BY value DESC
    LIMIT 1;
    

    OR

    select max(value) from (SELECT EXPLODE(ARRAY[1, 0, 2, 3, 3, 77, null, 1, 0]) OVER()) foo;
     max
    -----
      77
    (1 row)
    
This discussion has been closed.