21

Is there a way to concatenate multiple arrays into one array in Postgres?

For example, something like this:

ARRAY_CAT(
    ARRAY_FILL(5, ARRAY[4]),
    ARRAY_FILL(2, ARRAY[3]),
    ARRAY_FILL(11, ARRAY[3])
)

For this example, I'd like to see an output of

[5,5,5,5,2,2,2,11,11,11]

2 Answers 2

25

Use the || concatenation operator

select 
    array_fill(5, array[4]) ||
    array_fill(2, array[3]) ||
    array_fill(11, array[3])
Sign up to request clarification or add additional context in comments.

Comments

5

You can do it with repeated concatenations:

ARRAY_CAT(
  ARRAY_CAT(
    ARRAY_FILL(5, ARRAY[4]),
    ARRAY_FILL(2, ARRAY[3])
  ),
  ARRAY_FILL(11, ARRAY[3])
)

As @Clodoaldo Neto pointed out, you can use the || operator too. You can choose freely from these two, but keep in mind:

  • || can behave differently depending on the operand types. This can cause confusion.

  • in the case when both operands are array, || is just an alias to array_cat. (source)

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.