46

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

3 Answers 3

89

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 
Sign up to request clarification or add additional context in comments.

6 Comments

I had tried that too. it runs, but still doesn't order the records correctly. (by the values for stuff) do i need to cast the value or something?
@user1767105 See update. You're trying to get a non-existent key 'stuff', so it'll be equivalent to ORDER BY NULL.
got it. sorry i had the data objects incorrect above. really it was data: {"stuff" => {"name" => "stuff", "value": "awesome stuff"}} query ends up as select....order by data->"stuff"->>"value" your help got me there though so thanks! additionally a good resource as well: clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json
How is this supposed to work with integer? They seems to be sorted as if they were string: 1, 10, 46, 6 rather than 1, 6, 10, 46
@Natim Please post a new, separate question and link to this one for context. Include complete examples.
|
39

Use -> instead of ->> (->> gets a JSON object field as text):

select * from my_table ORDER BY data->'some_number' asc; 

1 Comment

While this does directly answer the question, I am grateful I found this. It helped me to solve a JSON column being sorted alphabetically when it is a number.
20

Try:

ORDER BY cast(data->>'value' as integer) ASC

1 Comment

@EugenKonkov fixed the question & answers

Your Answer

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.