Surya
Surya

Reputation: 2699

How to query array which is present as string in postgres?

I have a table called table with column called column with datatype text with values like '["1","2"]'.

I need to get all records which has "1" as one of the element.

select * 
from table 
where column.....?

How should the where clause be?

Upvotes: 1

Views: 57

Answers (2)

jarlh
jarlh

Reputation: 44696

Simply use LIKE. Keep the double quotes to pass 1, but avoid other numbers containing that digit.

select * 
from table 
where column like '%"1"%' 

Upvotes: 1

roman
roman

Reputation: 117347

I think you can use ? operator on jsonb type:

select *
from (
    select '["1","2"]' union all
    select '["0"]'
) as a(data)
where
    a.data::jsonb ? '1'

In general, I'd consider storing your data as jsonb instead of string.

db<>fiddle example

Upvotes: 1

Related Questions