0

I'm working on a real estate application that uses a postgres database. I need to query a json field for a specific condition and I'm not sure how to do that.

The json data is stored in a column called "conditions". For example, a buyer might have the following conditions:

{
    "subject to financing": {"date": "2020-05-30", "time": "2100", "done": true},
    "inspection": {"date": "2020-05-30", "time": "2100", "done": true},
    "be my friend": {"date": "2020-05-30", "time": "2100", "done": true}
}

I want to write query that checks if all conditions are met. In the above case, that means cycling through all conditions and checking that their "done" property is true.

How does one write a query like that with json data? Thanks.

1 Answer 1

1

You can do that with a NOT EXISTS condition.

select t.*
from the_table t
where not exists (select *
                  from jsonb_each(t.conditions) as c(k,val)
                  where (c.val -> 'done')::boolean = false)

The subquery iterates over all key/value pairs (of each row in the outer query) and checks if none is set to false

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

2 Comments

Thanks a_horse... that seems to work. If I were to refine it a little to detect when 'done' doesn't exist in the json object, how would I add that?
Use the ? operator, not c.val ? 'done'

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.