Postgres Array Append & Array Length for 'Arra

2020-03-01 03:46发布

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 think of:

UPDATE table SET array = array_append((SELECT array FROM table WHERE ...), 'element') WHERE ...;

With array_length this is what I can think of:

UPDATE table SET array[array_length((SELECT array FROM table WHERE ...), 1)+1] = element;

1条回答
家丑人穷心不美
2楼-- · 2020-03-01 04:17

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.

查看更多
登录 后发表回答