Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order by JSON data type postgres

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

like image 342
user1767105 Avatar asked Sep 22 '14 06:09

user1767105


People also ask

How do I query JSON data in PostgreSQL?

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.

What is JSON data type in PostgreSQL?

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.

What is -> in PostgreSQL?

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.


1 Answers

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  
like image 184
Craig Ringer Avatar answered Oct 08 '22 09:10

Craig Ringer