3

Working with PostgreSQL 9.4, is it possible to find numeric values inside a JSON datatype with comparison operators (eg. give me all record where age attribute in the JSON column is superior to 18)?

CREATE TABLE data
(
 id serial NOT NULL,
 attributes jsonb
);
INSERT INTO data (id, attributes) VALUES (1, '{"name": "Value A", "value": 20}');
INSERT INTO data (id, attributes) VALUES (2, '{"name": "Value B", "value": 10}');

I would like to know how to query this table to get all records with the "value" attribute is superior to 18

In the present case, record with id 1 would be the only result.

Equality is working (but it's a string comparison):

SELECT * from data WHERE attributes->>'value' = '10';

How to deal with numeric ?

SELECT * from data WHERE attributes->>'value' > 18;
 ==> ERROR: operator does not exist: text > integer
SELECT * from data WHERE attributes->>'value'::integer > 18;
 ==> ERROR: invalid input syntax for integer: "value"

Thanks.

asked Jan 7, 2015 at 10:43

1 Answer 1

4

The :: cast operator precedes almost any other operator in evaluation priority (except .), so you want to add parentheses:

SELECT * from data WHERE (attributes->>'value')::integer > 18;

Standard-compliant alternative:

 SELECT * from data WHERE cast(attributes->>'value' AS integer) > 18;
answered Jan 7, 2015 at 11:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.