3

My goal is to take an array, unnest it into a table with unnest and then aggregate it back into an array with array_agg. Why does the first DO block fail and the second succeed?

DO $$
DECLARE
    x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}';
BEGIN

    x := (SELECT array_agg(x) FROM unnest(x));
    RAISE NOTICE '%', x;
END;
$$;


DO $$
DECLARE
    x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}';
BEGIN

    x := (SELECT array_agg(y) FROM unnest(x) AS y);
    RAISE NOTICE '%', x;
END;
$$;
3
  • 1
    Why are you doing this? What is the real problem you are trying to solve? Commented Nov 27, 2015 at 9:45
  • I would like to sort the ranges in the array by descending right boundaries. I am thinking of making a table and sorting it with upper() or something Commented Nov 27, 2015 at 9:46
  • @a_horse_with_no_name here is my comment recast into a question: stackoverflow.com/questions/33954733/… Commented Nov 27, 2015 at 9:56

1 Answer 1

4

In first DO name of the column is unnest. You don't have column x.

DO $$
DECLARE
    x numrange[] := '{"[0, 3]", "[0, 1]", "[3, 5]", "[3, 8]"}';
BEGIN

    x := (SELECT array_agg(unnest) FROM unnest(x));
    RAISE NOTICE '%', x;
END;
$$;

In second DO name of the column is y and You can do string_agg() on this column.

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.