SQL: Select the minimum value from multiple columns with null values -


i have table 1

id   col1   col2   col3 --   ----   ----   ---- 1      7    null    12   2      2     46    null 3     null  null   null 4     245     1    792 

i wanted query yields following result

 id   col1   col2   col3  min  --   ----   ----   ----  ---   1     7    null    12    7   2     2     46    null   2   3    null  null   null  null   4    245    1     792    1 

i mean, wanted column containing minimum values out of col1, col2, , col 3 each row ignoring null values. in previous question (what's best way select minimum value multiple columns?) there answer non null values. need query efficient possible huge table.

select id,        case when col1 < col2 , col1 < col3 col1             when col2 < col1 , col2 < col3 col2              else col3             end min   yourtablenamehere 

assuming can define "max" value (i'll use 9999 here) real values never exceed:

select id,        case when col1 < coalesce(col2, 9999)              , col1 < coalesce(col3, 9999) col1             when col2 < coalesce(col1, 9999)               , col2 < coalesce(col3, 9999) col2              else col3        end min     yourtablenamehere; 

Popular posts from this blog