Re: [SQL] Better way to sort a JSONB array? - Mailing list pgsql-sql

From David G. Johnston
Subject Re: [SQL] Better way to sort a JSONB array?
Date
Msg-id CAKFQuwb4G490jXsXusxzKe7EWdRbejHzXtPXXw3AJMbijLUXzg@mail.gmail.com
Whole thread Raw
In response to [SQL] Better way to sort a JSONB array?  (Michael Moore <michaeljmoore@gmail.com>)
Responses Re: [SQL] Better way to sort a JSONB array?  (Michael Moore <michaeljmoore@gmail.com>)
List pgsql-sql
On Mon, Aug 7, 2017 at 1:13 PM, Michael Moore <michaeljmoore@gmail.com> wrote:
This works, but surely there is a better way to do it:

What do you mean by "better"?

 select jsonb_agg(row_to_json(alias)) from 
       (Select * from jsonb_populate_recordset(null::tx_portal, json_table2) order by portal_name) alias 
                                                           into json_table2;

It sorts the json_table2 array in "portal_name" order. 

​The only other possibility would be:

CREATE TABLE json_table2 AS
select jsonb_agg(row_to_json(alias) order by portal_name) from
(select * from jsonb_populate_recordset(...)) alias​;

i.e., move the order by into the aggregate; I prefer CREATE TABLE AS over SELECT INTO ...

I don't know why you are thinking there is a better way...you are doing two distinct actions here and you have two invocations of select...seems like the minimal possible number of sub-statements to me.  No one has written a c-language function for core that provides a more friendly interface to this.  Looking at your query doing so using dynamic SQL within a pl/pgsql function would seem reasonably easy.

I would suggest not using "json_table2" as both the name of the input variable and the target table name - it can be confusing to follow when you overload names like that.

David J.

pgsql-sql by date:

Previous
From: Michael Moore
Date:
Subject: Re: [SQL] Better way to sort a JSONB array?
Next
From: Michael Moore
Date:
Subject: Re: [SQL] Better way to sort a JSONB array?