4

For example, where the element is 'hi', and where N is 3, I need a PostgreSQL snippet I can use in a SELECT query that returns the following array:

['hi', 'hi', 'hi']

3 Answers 3

10

Postgres provides array_fill for this purpose, e.g.:

SELECT array_fill('hi'::text, '{3}');
SELECT array_fill('hi'::text, array[3]);

The two examples are equivalent but the 2nd form is more convenient if you wish to replace the dimension 3 with a variable.

See also: https://www.postgresql.org/docs/current/functions-array.html

Sign up to request clarification or add additional context in comments.

Comments

2

You may use array_agg with generate_series

select array_agg(s) from ( values('hi')) as t(s) cross join generate_series(1,3)

Generic

select array_agg(s) from ( values(:elem)) as t(s) cross join generate_series(1,:n)

DEMO

1 Comment

You can simplify it a little: SELECT array_agg('hi'::text) FROM generate_series(1, 3)
0

sql demo

with cte as (
  select 'hi' as rep_word, generate_series(1, 3) as value
)                                         -- ^^^ n = 3
select array(SELECT rep_word::text from cte);

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.