-1

I'm working with Rails 5 + Postgres.

I have a Postgres JSONB column named data with data that looks something like:

{username: 'McGruff', timestamp: 123456789}

I would like to query for data that is between two timestamps, to get a subset of records that all have a timestamp within some range (say, the last 24 hours).

Using comments from below, the answer is:

Model.where("(data->'timestamp')::int BETWEEN ? AND ?", start, end)

Thanks for the help!

1
  • Executive summary of the duplicate: -> gives you a jsonb value, not a string or integer; ->> gives you a string back, then cast that string to an integer to get the right comparison logic: (data->>'timestamp')::int between ? and ?. Commented Apr 24, 2019 at 17:33

1 Answer 1

1

Use where clause by providing start & end inputs as strings. as the data stored in string format in jsonb column.

somewhat like below:

Model.where((data->>'timestamp')::int between ? and ?, start, end)
Sign up to request clarification or add additional context in comments.

2 Comments

(1) -> yields a jsonb value, not a string. (2) Strings-containing-numbers don't compare the same as the numbers themselves.
Wow, thanks UdAY ... that's embarrassing. Using where combined with what @muistooshort said above was the solution: Model.where((data->>'timestamp')::int between ? and ?, start, end)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.