Home > database >  Return MAX(Null) as Null in postgresql
Return MAX(Null) as Null in postgresql

Time:02-10

I have a scenario where the max function should work as follows in PostgreSQL:

select max(3,null) from table

should return 3

whereas,

select max(null) from table

should return null.

Suggestions are welcomed!

CodePudding user response:

max() is an aggregate that works across rows, not columns.

You are looking for greatest()

select greatest(3,null) from table

CodePudding user response:

You can use values clause to build a list of values and call max aggregate function over it:

select (
    select max(v)
    from (values
        (3),
        (null),
        (t.foo),
        (t.bar)
    ) as x(v)
)
from t
  • Related