Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - Repeating an element N times as array

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']
like image 260
eye_mew Avatar asked Oct 26 '25 00:10

eye_mew


2 Answers

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

like image 80
Tavin Avatar answered Oct 28 '25 02:10

Tavin


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

like image 30
Kaushik Nayak Avatar answered Oct 28 '25 04:10

Kaushik Nayak