Using COALESCE to handle NULL values in PostgreSQL

后端 未结 2 1498
清酒与你
清酒与你 2020-12-07 19:55

I have the following query

SELECT  DISTINCT 
     pt.incentive_marketing, 
     pt.incentive_channel, 
     pt.incentive_advertising 
FROM test.pricing pt 
         


        
2条回答
  •  攒了一身酷
    2020-12-07 20:52

    You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

    COALESCE( NULLIF(yourField,'') , '0' )
    

    The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                     QUERY                     |                RESULT 
    ---------------------------------------------------------------------------------
    SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
    SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
    SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'
    

提交回复
热议问题