3

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']
Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
eye_mew
  • 8,855
  • 7
  • 30
  • 50

3 Answers3

7

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

Tavin
  • 390
  • 2
  • 13
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

Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45
  • 2
    You can simplify it a little: `SELECT array_agg('hi'::text) FROM generate_series(1, 3)` – Tavin Oct 14 '19 at 13:15
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);
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118