Don't update column if update value is null

前端 未结 3 1772
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 06:18

I have a query like this (in a function):

UPDATE some_table SET
  column_1 = param_1,
  column_2 = param_2,
  column_3 = param_3,
  column_4 = param_4,
  column_         


        
相关标签:
3条回答
  • 2021-02-02 06:33

    Additionally, to avoid empty updates:

    UPDATE some_table SET
      column_1 = COALESCE(param_1, column_1),
      column_2 = COALESCE(param_2, column_2)
      ...
    WHERE id = some_id;
    AND  (param_1 IS DISTINCT FROM column_1 OR
          param_2 IS DISTINCT FROM column_2 OR
          ...
         );
    

    This assumes target columns to be defined NOT NULL. Else, see Geir's extended version.

    0 讨论(0)
  • 2021-02-02 06:34

    Neat trick, thanks Przemek, Frank & Erwin!

    I suggest a minor edit to Erwin's answer to avoid empty updates. If any parameters were null (meaning: "use the old value"), the row was updated each time even though the row values did not change (after the first update).

    By adding "param_x IS NOT NULL", we avoid empty updates:

    UPDATE some_table SET
        column_1 = COALESCE(param_1, column_1),
        column_2 = COALESCE(param_2, column_2),
        ...
    WHERE id = some_id
    AND  (param_1 IS NOT NULL AND param_1 IS DISTINCT FROM column_1 OR
          param_2 IS NOT NULL AND param_2 IS DISTINCT FROM column_2 OR
         ...
     );
    
    0 讨论(0)
  • 2021-02-02 06:53

    Drop the SELECT statement, there is no need for, just use the current value:

    UPDATE some_table SET
      column_1 = COALESCE(param_1, column_1),
      column_2 = COALESCE(param_2, column_2),
      column_3 = COALESCE(param_3, column_3),
      column_4 = COALESCE(param_4, column_4),
      column_5 = COALESCE(param_5, column_5)
    WHERE id = some_id;
    
    0 讨论(0)
提交回复
热议问题