Postgres Array Append & Array Length for 'Array Push'

后端 未结 1 1075
醉话见心
醉话见心 2021-01-03 22:01

What is the best way to add an element to an array when the size of the array is not provided?

With array_append this is what I can thi

相关标签:
1条回答
  • 2021-01-03 22:58

    The simplest thing would be:

    update table
    set array = array_append(array, 'element')
    where ...
    

    or perhaps use the || operator:

    update table
    set array = array || 'element'
    where ...
    

    Both of those are equivalent to the more common set n = n + 11 for numbers. Depending on the types involved, you might need to disambiguate which || operator you mean by including a typecast:

    update table
    set array = array || 'element'::text
    where ...
    

    so that PostgreSQL knows you want the array || element version of || rather than the array || array version. Thanks to ak5 for bringing this to my attention.

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