2

This my jonb data

contact:{
    "name": "Jonh",
    "country": ["USA", "UK"],
  }

And my query:

SELECT * FROM public.product where contact -> 'country' = ARRAY['USA','UK'];

Executed the query and got this ERROR: operator does not exist: jsonb = text[] So how do I fix this error?

2 Answers 2

3

You need to compare it with a JSONB array:

select *
from product
where contact -> 'country' = '["USA","UK"]'::jsonb;

But this depends on the order of the elements in the array. If you want to test all keys regardless of the order, the ?& operator might be better:

where contact -> 'country' ?& array['UK','USA']

That would however also return rows that contain additional elements in the array. If you need to match all elements exactly regardless of the order you could use the @> operator twice:

where contact -> 'country' @> '["USA","UK"]'::jsonb
  and contact -> 'country' <@ '["USA","UK"]'::jsonb
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this I want. One more thing, where I can read more about ?& operator.
-1

Use to_jsonb():

SELECT (('{"a": ["x","y","z"]}'::jsonb)->'a') = to_jsonb(array['x','y','z']);

^^ Returns true.

1 Comment

This does not take the order of elements into account. SELECT (('{"a": ["x","z","y"]}'::jsonb)->'a') = to_jsonb(array['x','y','z']); would return false.

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.