array_fill Builds Uniform Arrays

Construct fixed-shape arrays with array_fill, choosing each dimension length and optionally a non-1 lower bound per dimension.

SqlData Integrity

Code

snippet
-- array_fill(值, 各维长度):2×3 的全 0 矩阵
SELECT array_fill(0, ARRAY[2, 3]) AS zeros_2x3;

-- 可选第三参数指定每维下界:下界 2 的三个元素
SELECT array_fill('pending', ARRAY[3], ARRAY[2]) AS lower_bound_two;

-- 填充的是"副本"而非引用:改一个元素不影响其他槽位
SELECT (array_fill(9, ARRAY[3]))[1] AS first_slot,
       (array_fill(9, ARRAY[3]))[3] AS last_slot;

-- 与 generate_series 组合:先造骨架再逐格覆盖
SELECT array_fill(0, ARRAY[4]) AS skeleton,
       ARRAY[1, 2, 3, 4]       AS values;

-- 多维时按行长展开:外层 2 行、内层每行 3 列
SELECT array_fill(11, ARRAY[2, 3]) AS matrix;

How it works

Every statement in the file is a SELECT that returns an array in a single column; there are no tables involved, so nothing has to be created before running it.

The first two statements show the two constructor shapes. array_fill(0, ARRAY[2, 3]) takes only the fill value and the per-dimension lengths, while array_fill('pending', ARRAY[3], ARRAY[2]) adds a third array holding the lower bound of each dimension.

Reading the shaped output

A multi-dimensional result is printed row-major: the outer length is the first entry of the lengths array and each row carries the second. array_fill(11, ARRAY[2, 3]) therefore shows two rows of three 11s.

Key statements

SELECT (array_fill(9, ARRAY[3]))[1] AS first_slot,
       (array_fill(9, ARRAY[3]))[3] AS last_slot;

Interactive Tools for This Topic