How to find least non-null column in one particular row in SQL?

后端 未结 8 992
别跟我提以往
别跟我提以往 2020-12-29 07:36

I am trying to find the lowest number in two columns of a row in the same table, with the caveat that one of the columns may be null in a particular row. If one of the colum

8条回答
  •  爱一瞬间的悲伤
    2020-12-29 08:14

    Depending on your corner case situation of having all values be null, I would go for such syntax, which is more readable (An easier solution if you have exactly two columns is below!)

    SELECT LEAST( IFNULL(5, ~0 >> 1), IFNULL(10, ~0 >> 1) ) AS least_date;
    -- Returns: 5
    
    SELECT LEAST( IFNULL(null, ~0 >> 1), IFNULL(10, ~0 >> 1) ) AS least_date;
    -- Returns: 10
    
    SELECT LEAST( IFNULL(5, ~0 >> 1), IFNULL(null, ~0 >> 1) ) AS least_date;
    -- Returns: 5
    
    SELECT LEAST( IFNULL(null, ~0 >> 1), IFNULL(null, ~0 >> 1)) AS least_date
    -- Returns: @MAX_VALUE (If you need to use it as default value)
    
    SET @MAX_VALUE=~0 >> 1;
    SELECT LEAST( IFNULL(null, @MAX_VALUE), IFNULL(null, @MAX_VALUE)) AS least_date;
    -- Returns: @MAX_VALUE (If you need to use it as default value). Variables just makes it more readable!
    
    SET @MAX_VALUE=~0 >> 1;
    SELECT NULLIF(
        LEAST( IFNULL(null, @MAX_VALUE), IFNULL(null,@MAX_VALUE)),
        @MAX_VALUE
    ) AS least_date;
    -- Returns: NULL
    

    That is my prefered way if

    • you can ensure that at least one column cannot be NULL
    • in corner case situation (all columns are NULL) you want a non-null default value which greater than any possible value or can get limited to a certain threshold
    • You can deal with variables to make this statement even more readable

    If you question yourself what ~0 >> 1 means: It's just a short hand for saying "Give me the greatest number available". See also: https://stackoverflow.com/a/2679152/2427579

    Even better, if you have only two columns, you can use:

    SELECT LEAST( IFNULL(@column1, @column2), IFNULL(@column2, @column1) ) AS least_date;
    -- Returns: NULL (if both columns are null) or the least value
    

提交回复
热议问题