I'm having difficulty understanding how I can order a postgres result by the properties of an array of JSON objects that I've built in a sub-select. This is a simplification of what I have:
SELECT
id,
(
SELECT
array_agg(json_build_object('id', id, 'name', name))
FROM
files
WHERE
id = ANY ("images")
ORDER BY name
) AS "images"
FROM
my_table
ORDER BY json_array_elements("images") ->> 'name' ASC;
But that results in the error:
ERROR: column "images" does not exist
json_array_elements
presumably can only operate on actual columns in a table, not a result?
So is there anyway order by the name
property at the top level (I'm not bothered about the order of the sub-select - that's actually selecting from a CTE called files
which has an ORDER BY)?