Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 420
Kamilski81 Avatar asked Jun 13 '17 21:06

Kamilski81


Video Answer


2 Answers

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)    
like image 118
klin Avatar answered Oct 23 '22 22:10

klin


If you use postgres version >= 9.3, then you can:

select * from t
where (json->>'key')::numeric >= 90
like image 26
Oto Shavadze Avatar answered Oct 23 '22 23:10

Oto Shavadze