Search code examples
postgresqljsonb

How can I do less than, greater than in JSON Postgres fields?


If I have some json:

id = 1, json = {'key':95}
id = 2, json = {'key':90}
id = 3, json = {'key':50}

Is there a way I can use Postgres fields to query for key greater than >= 90?


Solution

  • Use the operator ->> (Get JSON object field as text), e.g.

    with my_table(id, json) as (
    values
    (1, '{"key":95}'::json),
    (2, '{"key":90}'),
    (3, '{"key":50}')
    )
    
    select *
    from my_table
    where (json->>'key')::int >= 90;
    
     id |    json    
    ----+------------
      1 | {"key":95}
      2 | {"key":90}
    (2 rows)