1

I was trying to check on a way to query entire json field data in PostgreSQL. But, all I see is querying for a specific field like below.

# SAMPLE DATA
# data = {"test": 1, "test_another": 2}

select * from sample_table where data->>'test' = ('1')

The above condition yields the correct result. But, I have tried querying on the entire block in multiple ways, but, it dosent seem to work and returns below error.

select * from sample_table where data->'{"test": 1, "test_another": 2}'

#ERROR:  argument of WHERE must be type boolean, not type json

1 Answer 1

3

Use the contains operator @>

select * 
from sample_table 
where data @> '{"test": 1, "test_another": 2}'

or if you need an exact match:

select * 
from sample_table 
where data = '{"test": 1, "test_another": 2}';

The above requires data to be defined as jsonb (which it should be anyway). If it's only a json you need to cast it:

where data::jsonb = '{"test": 1, "test_another": 2}'
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately my column is defined as json and not as jsonb
Then you have to cast it: where data::jsonb = ...
Works. Perfect!

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.