How do I perform an IF…THEN in an SQL SELECT?

前端 未结 30 1828
梦如初夏
梦如初夏 2020-11-21 22:50

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = \'N\' OR InStock = \'Y\' ? 1 :          


        
30条回答
  •  忘了有多久
    2020-11-21 23:14

    For the sake of completeness, I would add that SQL uses three-valued logic. The expression:

    obsolete = 'N' OR instock = 'Y'
    

    Could produce three distinct results:

    | obsolete | instock | saleable |
    |----------|---------|----------|
    | Y        | Y       | true     |
    | Y        | N       | false    |
    | Y        | null    | null     |
    | N        | Y       | true     |
    | N        | N       | true     |
    | N        | null    | true     |
    | null     | Y       | true     |
    | null     | N       | null     |
    | null     | null    | null     |
    

    So for example if a product is obsolete but you dont know if product is instock then you dont know if product is saleable. You can write this three-valued logic as follows:

    SELECT CASE
               WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
               WHEN NOT (obsolete = 'N' OR instock = 'Y') THEN 'false'
               ELSE NULL
           END AS saleable
    

    Once you figure out how it works, you can convert three results to two results by deciding the behavior of null. E.g. this would treat null as not saleable:

    SELECT CASE
               WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
               ELSE 'false' -- either false or null
           END AS saleable
    

提交回复
热议问题