Thanks in advance. Assume, I have a table that contains the value in an array something like this.
CREATE TABLE example (
id serial4 NOT NULL,
name varchar(100) NOT NULL,
content_type json NULL
CONSTRAINT example_pkey PRIMARY KEY (id)
);
id |name |content_type
-----------------------
1 | P | ['a','b','c']
2 | Q | ['a',]
3 | R | ['b','c']
4 | S | ['a','c']
I want to find which row contains 'c' in content_type
I have tried but couldn't get,
select * from table where ARRAY['c'] && content_type;
Is there someone to help me to build the query?
Bergi
670k162 gold badges1k silver badges1.5k bronze badges
asked Dec 1, 2021 at 9:40
Rakibul Islam
6879 silver badges20 bronze badges
1 Answer 1
Updated for change column type from text[] to json
If your column type is JSON you can use two scenarios:
- convert to jsonb and use
?operator (Postgres document)
select * from test where content_type::jsonb ? 'c';
- Use
json_array_elements_text
select distinct on(t.id) t.*
from
test t
cross join json_array_elements_text(content_type) je
where
je.value = 'c';
Old scenario
You can use any function to check values exist in an array or according to Postgres document use array operator @>
- With
any
select * from test where 'c' = any(content_type);
- With
@>
select * from test where content_type @> array['c'];
answered Dec 1, 2021 at 9:51
Pooya
3,2032 gold badges16 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Rakibul Islam
As the data type of
content_type is JSON, it shows "ERROR: op ANY/ALL (array) requires array on right side"Pooya
I updated the post for the JSON scenario
lang-sql
content_typea char array or a JSON? Edit the question and add theCREATEstatement of the table to clarify. And also why isn't this modeled the relational way? That could have easily been done with another table linking the content types. Then it would be a simple join query...content_typeis a JSON column.char[]ortext[], to make it an actual array column (and have Pooya's answer work)