1

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?

7
  • 1
    where column like '%"1"%' Commented Sep 19, 2019 at 10:28
  • no... the number can range upto 300. I dont want results with 10,100,101,201.... Commented Sep 19, 2019 at 10:28
  • 1
    Thanks to the double quotes that will not happen. Commented Sep 19, 2019 at 10:29
  • Oh really? so converting the string to array type and then checking with contains operator is an overkill huh? Commented Sep 19, 2019 at 10:31
  • @404 yes you are right. The dataype is text have updated the question. Commented Sep 19, 2019 at 10:34

2 Answers 2

1

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

select * 
from table 
where column like '%"1"%' 
Sign up to request clarification or add additional context in comments.

2 Comments

Hey can you also post in any postgres doc that says about double quotes. It will be helpful
That's just how LIKE works. The % wild-card stands for any sequence of zero or more characters. In your case look for something that has zero or some arbitrary characters, then "1", and then zero or some arbitrary characters. postgresqltutorial.com/postgresql-like
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.