Using COALESCE to handle NULL values in PostgreSQL

后端 未结 2 1485
清酒与你
清酒与你 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'
    
    0 讨论(0)
  • 2020-12-07 20:52

    If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

    UPDATE pt.incentive_channel
    SET   pt.incentive_marketing = NULL
    WHERE pt.incentive_marketing = '';
    
    UPDATE pt.incentive_channel
    SET   pt.incentive_advertising = NULL
    WHERE pt.incentive_marketing = '';
    
    UPDATE pt.incentive_channel
    SET   pt.incentive_channel = NULL
    WHERE pt.incentive_marketing = '';
    

    This will make joining and selecting substantially easier moving forward.

    0 讨论(0)
提交回复
热议问题