PostgreSQL: sort an array of elements using some sorting condition
问题 Suppose you need to sort an array of numranges by, say, descending left boundary. Is the following approach the simplest: unnest the array into a table, sort the table, array_agg it back into an array. How would that look in code? Here is my non-working attempt: DO $$ DECLARE x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}'; BEGIN x := ( WITH x AS ( SELECT xrow FROM unnest(x) AS xrow ) SELECT array_agg(xrow) FROM x ORDER BY lower(xrow) DESC ); RAISE NOTICE '%', x; END; $$; 回答1: You