2

Im writing a query for searching an element in an array. Search using "for" loop is not efficient because my array is having a lot of elements. Because of this the query is taking lot of time to execute. So can any one say how to search an element in an array without "for" loop which should be faster. I have to get the index on searching

Thanks, Karthika

0

2 Answers 2

1

Use the ANY operator:

where 1 = ANY (array_column) 

That will return all rows where array_column contains the value 1 at least once. If you want to check for multiple values, see Clodoaldo's answer.

If you create an index on that column, this should be very fast. Something like this:

create index on the_table using gin (the_array_column);

The following is inspired by the solution shown here: Finding the position of a value in PostgreSQL arrays

with sample_data (pk_column, array_data) as (
   values 
     (1, array[1,2,3,4,5]),
     (2, array[7,8,9,11]),
     (3, array[5,4,3,2,1]),
     (4, array[10,9,8,1,4,6]),
     (5, array[7,8,9])
)
select *
from (
  select pk_column, 
         unnest(array_data) as value, 
         generate_subscripts(array_data, 1) as array_index
  from sample_data
  where 1 = any(array_data)
) t
where value = 1

The inner where will reduce the total work that needs to be done to only those rows that actually contain the value. The outer query will then "explode" the array to get the value's index. But using the function shown in the linked question might actually be what you are after.

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

2 Comments

@user2659199: if only a few rows from the table actually contain that value, that condition could at least reduce the number of arrays you have to search and thus should improve the overall performance. I don't have an idea on how to get the actual index though (btw.: you should have added that piece of information right from the start!)
+1, here's sqlfiddle - sqlfiddle.com/#!12/d41d8/1633. You also have a typo - change data to sample_data in the from clause
0

Check the contains operator @>

select array[1,2] @> array[1];
 ?column? 
----------
 t

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

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.