0

I have a JSONB that looks something like this

[{
"foo":"bar",
"date":"2020-01-01"
},
{
"foo":"bar",
"date":"2020-02-03"
},
{
"foo":"bar",
"date":"2020-01-02"
}]

I need a query to return true if ALL of the "date"s are less than 1 year ago. I have looked at the postgres JBON documentation and the only thing sort of fitting I found was using ?& but I'm not just trying to compare strings but dates that are strings so I am kind of lost here

2
  • Which Postgres version are you using? Commented Mar 5, 2020 at 11:03
  • @a_horse_with_no_name 9.6 Commented Mar 5, 2020 at 11:22

1 Answer 1

2

You will need to iterate over all elements and then convert the strings to dates in order to be able to compare them.

select .... other columns ...., 
       current_date - interval '1 year' < all (select (x.entry ->> 'date')::date
                                               from jsonb_array_elements(t.data) as x(entry))
from the_table t
Sign up to request clarification or add additional context in comments.

3 Comments

That gives me the error cannot extract elements from an object
Then apparently your JSON doesn't contain an array - contrary to what you wrote in your question dbfiddle.uk/…
you're right, there are some entries in my DB where there's no data so its just {}, guess I'll need to filter those out

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.