PostgreSQL – ARRAY_FILL Function
The array_fill
function in PostgreSQL is used to create an array of a specified dimension and fill it with a specified value. This function is useful when you want to generate arrays with a specific structure and initialize all elements to a common value.
Below is the syntax for the array_fill
function:
array_fill(value, dimensions)
value
is the value with which you want to fill the array. It can be of any data type, including scalar values or arrays.
dimensions
is an array that defines the dimensions of the resulting array. Each element in the dimensions
array specifies the size of a dimension in the resulting array.
Below is an example of how to use the array_fill
function:
Below is the sql to create a 2×3 array filled with the value 5:
SELECT array_fill(5, ARRAY[2, 3]);
The result of this query would be a two-dimensional array with dimensions 2×3, filled with the value 5:
{{5, 5, 5}, {5, 5, 5}}
You can also use other data types and dimensions as needed. For example, if you want to create a one-dimensional array of strings filled with “Hello”:
SELECT array_fill('Hello', ARRAY[4]);
The result would be:
{"Hello", "Hello", "Hello", "Hello"}
The array_fill
function is helpful when you need to initialize arrays with specific values, especially when working with multi-dimensional arrays. It allows you to generate arrays of various dimensions and populate them with the desired data.