I have a Postgres table which has column of type JSON which has a bunch of JSON objects in them. I want to query the table records and order the results by a value stored in the JSON field. I'm getting the queries to run, but they don't sort correctly. I'm not finding a ton of documentation on ordering JSON field types specifically, so hoping someone has run into this.
data: {name: "stuff", value: "third option"} data: {name: "stuff", value: "awesome stuff"} data: {name: "stuff", value: "way cooler stuff"}
The following SQL executes but the results return unordered
select * from table ORDER BY data->>'value asc'
I'm using rails, but have tried running SQL directly as well w/ same result
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
JSON stands for JavaScript Object Notation. It is used to store data in the form of key-value pairs and is generally used for communicating between the server and the client. Contrary to other formats, JSON is human-readable text. PostgreSQL has support for native JSON data type since version 9.2.
PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.
You put asc
in the fieldname. There's no key named value asc
in the json, so data ->> 'value asc'
will always return NULL
.
You actually want:
select * from table ORDER BY data->>'value' ASC
to match the json, possibly even:
select * from table WHERE data ->> 'name' = 'stuff' ORDER BY data->>'value' ASC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With