Razinar
Razinar

Reputation: 767

Postgres jsonb and query

I have a postgres database. Inside "match" table I store a JSONB like this one, inside "when" column:

{{"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}, {"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}}

and it works like a list of object storing a start time and an end time. Now i want to query all matches that are not past. How can i do that? Is it possible to compare a single "start" value with the current data?

Upvotes: 0

Views: 310

Answers (1)

rotarydial
rotarydial

Reputation: 2591

Have a look at this SQL Fiddle.

You can query into the jsonb using the ->> operator. For dates/times, you'll need to convert the results in order to compare. This query returns only values with a future start:

SELECT when_col->>'start' FROM match
WHERE to_date(when_col->>'start','YYYY-MM-DD"T"HH24:MI:SS') >= NOW();

Note that the JSON you gave above was malformed. I broke it out into separate rows in the fiddle:

CREATE TABLE match
(
  when_col jsonb
 );

 INSERT INTO match (when_col) VALUES ('{"end": "2017-01-04T17:22:13.311693Z", "start": "2017-01-04T16:22:13.311693Z"}');
 INSERT INTO match (when_col) VALUES ('{"end": "2017-02-04T17:22:13.311693Z", "start": "2017-02-04T16:22:13.311693Z"}');
 INSERT INTO match (when_col) VALUES ('{"end": "2019-02-04T17:22:13.311693Z", "start": "2019-02-04T16:22:13.311693Z"}');
 INSERT INTO match (when_col) VALUES ('{"end": "2029-02-04T17:22:13.311693Z", "start": "2029-02-04T16:22:13.311693Z"}');

Upvotes: 2

Related Questions