I have a table where one column has an array – but stored in a text format:
mytable
id ids
-- -------
1 '[3,4]'
2 '[3,5]'
3 '[3]'
etc ...
I want to find all records that have the value 5 as an array element in the ids column.
I was trying to achieve this by using the “string to array” function and removing the [ symbols with the translate function, but couldn’t find a way.
You can do this: http://www.sqlfiddle.com/#!1/5c148/12
Output:
You can also use bool_or: http://www.sqlfiddle.com/#!1/5c148/11
To see the original elements:
Output:
Postgresql DDL is atomic, if it’s not late yet in your project, just structure your stringly-typed array to a real array: http://www.sqlfiddle.com/#!1/6e18c/2
Query:
Output:
You can also use contains operator: http://www.sqlfiddle.com/#!1/6e18c/6
I prefer the
&&syntax though, it directly connotes intersection. It reflects that you are detecting if there’s an intersection between two sets(array is a set)http://www.postgresql.org/docs/8.2/static/functions-array.html