Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Search in an array in PostgreSQL

You can search in a an array by using the ANY function:

create table numbers as 
  select * from (
    values 
      (1, array[1,2]), 
      (2, array[2,3,4]), 
      (3, array[4,5,6])
  )
as numbers(id, positions);

select *
from numbers
where 4 = any(positions);
 id | positions
----+-----------
  2 | {2,3,4}
  3 | {4,5,6}
(2 rows)
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.