Skip to content
Advertisement

Ordering within a json_agg of json objects

I have a simple query as follows:

I have simplified the above for the purposes of this question.

This results in something like this being returned:

Is there a way I can order the underlying json_agg by the score within the object?

I’ve tried:

And also this:

But both of the above fail

Advertisement

Answer

I don’t see how random() fits in. But you can generate the record in the from clause and then access the field:

The problem is that Postgres over-optimizes the above and returns the same score for all rows. One solution is to correlate the subquery, forcing evaluation for each row in t. Here is one method that works:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement