3

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;
$$;
0

1 Answer 1

5

You must move ORDER BY into aggregate function, to afect aggragate order see manual:

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  ORDER BY lower(xrow) DESC) FROM x

    );
    RAISE NOTICE '%', x;
END;
$$;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.