In my rails psql application I have an emails array column. The element in the first index of this column is the primary email. I want to be able to search the db for all people with primary email x.
2 Answers
No need to test for array inclusion. Just get the first element and compare that to the string:
User.where("emails[1] = ?", "[email protected]")
1 Comment
ryan2johnson9
Thanks, easier to understand. I did some Benchmark.measure to compare with the Array inclusion answer and there seems to be little difference in Performance.
I could not see this in the documentation but thanks to this answer I can see that in Postgres 9.5 or older you can use
arr[1:1]
syntax to look only in the first element
So this is the answer
User.where("emails[1:1] @> ARRAY[?]", "[email protected]")