I have this PL/pgSQL function to aggregate rows from two tables in a jsonb value (data_table_1 and data_table_2). fk_id is a common foreign key id in both tables:
DECLARE
v_my_variable_1 jsonb;
v_my_variable_2 jsonb;
v_combined jsonb;
BEGIN
SELECT json_agg( data_table_1 ) INTO v_my_variable FROM data_table_1 WHERE fk_id = v_id;
SELECT json_agg( data_table_2 ) INTO v_my_variable_2 FROM data_table_2 WHERE fk_id = v_id;
SELECT v_my_variable || v_my_variable_2 INTO v_combined;
Now I want to sort v_combined by the field "ts", a timestamp column common to both tables, and consequently a common key in all array objects in the jsonb value.
Example:
v_combined = '[{"id": 1, "type": 4, "param": 3, "ts": 12354355}
, {"id": 1, "txt": "something", "args": 5, "ts": 12354345}]';
How do I sort array elements in v_combined in ascending order for ts?
If I were selecting from a table I could simply use:
select * into v_combined from v_combined ORDER BY v_combined->>'ts' ASC;
But when I try that, it says that v_combined does not exist. Is there a way of storing it in a temp table and sorting there, or is there a direct way to sort the array of JSON objects in PL/pgSQL?
SELECT v_combined || v_my_variable into v_my_variable_2;. I assume you meant to writeSELECT v_my_variable || v_my_variable_2 into v_combined;?jsonbdoes have a concept of ordering for array elements.