greatest_not_null(arr)
This SQL function returns the greatest (maximum) value among multiple columns in the array <arr>, while properly handling NULL values.
CREATE OR REPLACE FUNCTION `justfunctions.eu.greatest_not_null`(`arr` any type) AS ((SELECT max(a) FROM UNNEST(arr) a WHERE a is not NULL)
)
OPTIONS ( description = '''This SQL function returns the greatest (maximum) value among multiple columns in the array <arr>, while properly handling NULL values.''')
Example
WITH sample AS (
SELECT 5 as col_1, 3 as col_2, NULL as col_3 UNION ALL SELECT NULL, 10, 7 UNION ALL SELECT 4, NULL, 6 UNION ALL SELECT NULL, NULL, 1
)
SELECT `justfunctions.eu.greatest_not_null`([col_1, col_2, col_3])
FROM sample
[5,10,6,1]
| col_1 | col_2 | col_3 | greatest_value |
|-------|-------|-------|----------------|
| 5 | 3 | NULL | 5 |
| NULL | 10 | 7 | 10 |
| 4 | NULL | 6 | 6 |
| NULL | NULL | 1 | 1 |