Array Bounds: Reads Return NULL, Writes Grow

Reading beyond an array's bounds returns NULL, not an error; writing past the end of a one-dimensional array grows it, filling skipped positions with NULL.

SqlData Integrity

Code

snippet
-- 数组下标越界:读越界下标返回 NULL,一维数组写越界会扩容并补 NULL
CREATE TABLE job_runs (
    id         int PRIMARY KEY,
    exit_codes int[] NOT NULL DEFAULT '{}'
);

INSERT INTO job_runs VALUES (1, ARRAY[0, 2, 0]), (2, ARRAY[0]);

-- 读越界下标:返回 NULL 而不是报错,NULL 也不代表元素存在且为 NULL
SELECT id, exit_codes[5] AS beyond_bounds, exit_codes[1] AS first_slot
FROM job_runs ORDER BY id;

-- 用 cardinality 拿真实长度,与越界读区分
SELECT id, cardinality(exit_codes) AS len, exit_codes[3] AS slot3
FROM job_runs ORDER BY id;

-- 一维数组写越界:不报错,数组扩容到下标 5,中间位置自动补 NULL
UPDATE job_runs SET exit_codes[5] = 0 WHERE id = 2
RETURNING exit_codes, cardinality(exit_codes) AS new_len;
-- id = 2 的 exit_codes 变为 [0,NULL,NULL,NULL,0],new_len = 5

-- 扩容仅限一维数组:多维数组写越界才报 array subscript out of range
-- UPDATE grids SET cells[2][3] = 9;  -- 2x2 的 int[][] 上执行即失败

DROP TABLE job_runs;

How the snippet works

What runs here is SELECT / INSERT / UPDATE / CREATE — job_runs are the objects involved.

Concretely, the SQL combines: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Using it

The job_runs table is the working surface here.

Key statements

UPDATE job_runs SET exit_codes[5] = 0 WHERE id = 2
RETURNING exit_codes, cardinality(exit_codes) AS new_len;
CREATE TABLE job_runs (
    id         int PRIMARY KEY,
    exit_codes int[] NOT NULL DEFAULT '{}'
);
SELECT id, exit_codes[5] AS beyond_bounds, exit_codes[1] AS first_slot
FROM job_runs ORDER BY id;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`job_runs`.