How to reorder array in JSONB type column

僤鯓⒐⒋嵵緔 提交于 2019-12-02 03:24:51

Unnest the array with jsonb_array_elements() and aggregate its sorted elements using jsonb_agg():

with the_data(val) as (values ('[3,6,78,1]'::jsonb))

select jsonb_agg(elem order by elem) as val
from the_data
cross join lateral jsonb_array_elements(val) as arr(elem);

      val      
---------------
 [1, 3, 6, 78]
(1 row)

You can use the query in a custom function which will be handy in more complex queries:

create or replace function jsonb_sort_array(jsonb)
returns jsonb language sql immutable
as $$
    select jsonb_agg(elem order by elem)
    from jsonb_array_elements($1) as arr(elem)
$$;

with the_data(val) as (values ('[3,6,78,1]'::jsonb))

select jsonb_sort_array(val) as val
from the_data;

      val      
---------------
 [1, 3, 6, 78]
(1 row)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!