1

I have an integer[] column and I want to update this column, but avoid having duplicate entries in the array.

Example: First [123] is the value. Next time I want to add 234. Here array_append() works fine. But it shouldn't allow adding 123 again.

So my question: How can I append a value to an array only if that item is not present yet in the array.

2 Answers 2

4

For integer arrays, you can use the intarray extension's uniq function:

CREATE EXTENSION intarray;

UPDATE thetable SET thecol = uniq(array_append(thecol, 32)) WHERE ...
Sign up to request clarification or add additional context in comments.

Comments

1

Pseudo code:

UPDATE "my_table"
   SET "int_array" = array_append("int_array", :element_to_insert)
 WHERE :some_filters
   AND :element_to_insert <> ALL ("int_array")

More possibilities:

http://www.postgresql.org/docs/9.3/static/functions-array.html http://www.postgresql.org/docs/9.3/static/functions-comparisons.html

2 Comments

Dosnt this flush and update only new entries every time? Does it keep the old entries?
This updates only, when the array doesn't contain the element you want to append. array contains element = element = ANY (array) - array does not contain element = element <> ALL (array)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.