0

In other words, is there a way to make an array column to work like a set, that is, when a duplicate value is added to it, it is simply ignored?

One possibility is to use triggers or to ensure uniqueness of elements when a SELECT is performed, but ideally I want the array to act more like a set.

1
  • I don't think that is possible. The usual way in a relational database would be to create proper 1:n relationship where you can control uniqueness. Commented Feb 15, 2014 at 9:03

1 Answer 1

4

No it is not possible. But, you can use a own append function, that appends only unique values.

CREATE OR REPLACE FUNCTION append_unique(anyarray, anyelement)
RETURNS anyarray AS $$
  SELECT CASE WHEN $2 = ANY($1) THEN $1 ELSE $1 || $2 END; 
$$ LANGUAGE sql;

postgres=# SELECT append_unique(ARRAY[1,2,3], 4);
 append_unique 
---------------
 {1,2,3,4}
(1 row)

postgres=# SELECT append_unique(ARRAY[1,2,3,4], 4);
 append_unique 
---------------
 {1,2,3,4}
(1 row)
Sign up to request clarification or add additional context in comments.

1 Comment

In the second select I think you mean SELECT append_unique(ARRAY[1,2,3,4], 4)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.