3

I am looking for a way to find if a string exists in a Postgres column of type "jsonb" that has values like below:

id | numbers(jsonb)
1  | ["54954565","16516516","565196212"]
2  | ["195195159","252432","275782872"]
3  | ["54954565","61595161","728278"]
4  | ["245735435","75454","2782"]

Eg:

If "16516516" exists in array corresponding to any entry in numbers, I want to get the whole row.

So if I query for "16516516".

The row I get should be:

id | numbers
1  | ["54954565","16516516","565196212"]```

2 Answers 2

8

that's what the ? operator will do:

select *
from the_table
where numbers ? '16516516'

Online example

Sign up to request clarification or add additional context in comments.

Comments

5

Use the contains operator @>

SELECT * FROM t 
WHERE numbers @> '["16516516"]'

Demo db<>fiddle:

WITH t (id ,numbers) AS (
  VALUES (1,'["54954565","16516516","565196212"]'::jsonb),
         (2,'["195195159","252432","275782872"]'::jsonb),
         (3,'["54954565","61595161","728278"]'::jsonb),
         (4,'["245735435","75454","2782"]'::jsonb)
)
SELECT * 
FROM t WHERE numbers @> '["16516516"]';
 id |                numbers                
----+---------------------------------------
  1 | ["54954565", "16516516", "565196212"]
(1 row)

2 Comments

Thanks, @jim for this nice answer. I am searching for two more questions: 1. How to implement contains some for an array. Here, some of elements should contains in jsonb column ["54954565","16516516"] 2. How to implement contains none for an array. Here, none of elements should contains in jsonb column ["54954565","16516516"] Thanks in advance.
@Md.SajedulKarim thanks. I'm afraid I did not understand your question. Could you post a question with some sample data and the expected result? cheers

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.