Adding value to Postgres integer array
Asked Answered
U

4

43

I am looking for help in adding a value 10 to an int[] in PostgreSQL 9.5.

Looking at the documentation I should be able to use this format to update it but it is not working:

int[] + int   push element onto array (add it to end of array)

I have tried running this:

update table1 set integer_array = integer_array + 10::Integer. 

It did not work and I got this error:

ERROR: operator does not exist: integer[] + integer
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
  Position: 67

I feel this is the same format like the one presented in the documentation on how to perform this operation.

Uninhibited answered 16/11, 2016 at 18:50 Comment(1)
postgresql.org/docs/current/functions-array.htmlBregma
C
72

Use array_append function to append an element at the end of an array:

UPDATE table1
SET integer_array = array_append(integer_array, 5);

5 is a value of choice, it's of an integer datatype in your case. You probably need some WHERE clause as well not to update the entire table.

Try below to see how it works:

SELECT ARRAY[1,2], array_append(ARRAY[1,2],3);

Result:

 array | array_append
-------+--------------
 {1,2} | {1,2,3}
Cassondracassoulet answered 16/11, 2016 at 18:54 Comment(0)
S
23

I like this way better:

UPDATE table1 SET integer_array = integer_array || '{10}';

You can also add multiple values with single query:

UPDATE table1 SET integer_array = integer_array || '{10, 11, 12}';
Statolith answered 25/1, 2019 at 13:1 Comment(0)
A
10

single:

UPDATE table1
SET integer_array = array_append(integer_array, 3);

multiple:

UPDATE table1
SET integer_array = array_cat(integer_array, ARRAY[4,5]);

https://www.postgresql.org/docs/9.1/functions-array.html#ARRAY-FUNCTIONS-TABLE

Azevedo answered 17/8, 2020 at 21:52 Comment(0)
K
8
-- Declaring the array

arrayName int8[];

-- Adding value 2206 to int array

arrayName := arrayName || 2206;

-- looping throught the array

FOREACH i IN ARRAY arrayName 
LOOP 

 RAISE NOTICE 'array value %', i;

END LOOP;

cheers

Katharynkathe answered 11/7, 2019 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.