least_not_null(arr)
This SQL function returns the least (minimum) value among multiple columns in the array <arr>, while properly handling NULL values.
CREATE OR REPLACE FUNCTION `justfunctions.eu.least_not_null`(`arr` any type) AS ((SELECT min(a) FROM UNNEST(arr) a WHERE a is not NULL)
)
OPTIONS ( description = '''This SQL function returns the least (minimum) 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.least_not_null`([col_1, col_2, col_3])
FROM sample
[3,7,4,1]
| col_1 | col_2 | col_3 | greatest_value |
|-------|-------|-------|----------------|
| 5 | 3 | NULL | 3 |
| NULL | 10 | 7 | 7 |
| 4 | NULL | 6 | 4 |
| NULL | NULL | 1 | 1 |