28

Is there any other way to search for a certain value in an integer[] column in Postgres?

My currently installed Postgres version does not allow the following statement:

SELECT * FROM table WHERE values *= 10;

Array examples:

'{11043,10859,10860,10710,10860,10877,10895,11251}'
'{11311,10698,10697,10710,10712,10711,10708}'

The statement should return every row where the array contains '10710'.

3 Answers 3

62

For equality checks you can simply:

SELECT * FROM tbl WHERE 10 = ANY (values);

Read about ANY/SOME in the manual.
For big tables / big arrays consider array operators with index support, like:

SELECT * FROM tbl WHERE values @> '{10}'::int[];

See:

For integer arrays consider the additional module intarray:

Related:

Sign up to request clarification or add additional context in comments.

Comments

7

quickly search will be so, but you should use index gist or gin for intarray type Postgres intarray

 SELECT * FROM table WHERE values @> ARRAY[10];

Comments

-2
**Store Integer Array as Strings in Postgresql and Query the Array**    
Finally I could save the integer as string array in one column able to successfully convert into array and query the array using below example.

    CREATE TABLE test
    (
      year character varying,
      id serial NOT NULL,
      category_id character varying,
      CONSTRAINT test_pkey PRIMARY KEY (id)
    )

    Data
    "2005";1;"1,2,3,4"
    "2006";2;"2,3,5,6"
    "2006";3;"4,3,5,6"
    "2007";7;"1,2"


    select distinct(id) from test, (select id as cid, unnest(string_to_array(category_id ,  ',')::integer[]) as cat from test) c where c.cid=test.id and cat in (1,2,3);

    Result:
    2
    1
    3
    7

Comments

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.