Sub topic 10
Multidimensional arrays and their limits
PostgreSQL arrays can have more than one dimension. A two-dimensional array works like a matrix with rows and columns, and the same idea extends to three or more dimensions. This is useful for small grids such as game boards, seating plans, or coefficient matrices. The feature has sharp edges, though. Many array functions only accept one dimension, and the declared shape of a column is not enforced.
This chapter assumes you know the basics from earlier chapters: array literals and the ARRAY[...] constructor, 1-based subscripts and slices, unnest, and array_agg. You should also be comfortable with CHECK constraints and with how NULL behaves in a condition.
Declaring and writing multidimensional values
You declare a multidimensional column by adding more brackets. The brackets are documentation only. integer[][], integer[3][3], and integer[] all name the same type, and PostgreSQL does not enforce the dimension count or the sizes you write.
CREATE TABLE grids (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
cells integer[][] NOT NULL
);
INSERT INTO grids (name, cells) VALUES
('small', ARRAY[[1,2,3],[4,5,6]]),
('literal', '{{7,8,9},{10,11,12}}');Both forms describe a 2-row, 3-column array. With the constructor, nest ARRAY[...] brackets inside the outer pair. With the string literal, nest braces.
Every dimension must be rectangular. Each inner array must have the same length as its siblings, and ragged input is rejected:
SELECT ARRAY[[1,2],[3]];
-- ERROR: multidimensional arrays must have array expressions with matching dimensions
SELECT '{{1,2},{3}}'::integer[];
-- ERROR: malformed array literal
-- DETAIL: Multidimensional arrays must have sub-arrays with matching dimensions.PostgreSQL has no "array of arrays" type. If your data is ragged, a multidimensional array cannot hold it.
Inspecting the shape
Four functions describe a multidimensional value:
| Function | Returns |
|---|---|
| `array_ndims(a)` | Number of dimensions |
| `array_dims(a)` | Text such as `[1:2][1:3]` with the bounds of every dimension |
| `array_length(a, d)` | Length of dimension `d` |
| `cardinality(a)` | Total number of elements across all dimensions |
SELECT name,
array_ndims(cells) AS ndims,
array_dims(cells) AS dims,
array_length(cells, 1) AS n_rows,
array_length(cells, 2) AS n_cols,
cardinality(cells) AS total
FROM grids;For the small row this returns 2, [1:2][1:3], 2, 3, and 6.
Remember the empty-array behavior from the NULLs chapter. For '{}', array_ndims, array_dims, and array_length return NULL, while cardinality returns 0. That difference matters when you write constraints, as shown later in this chapter.
Subscripts and slices
A subscript for each dimension picks out one element. A slice returns a sub-array that keeps the number of dimensions.
SELECT cells[2][3] AS one_cell,
cells[1:1][1:3] AS first_row,
cells[1:2][2:3] AS right_block,
cells[2][1:2] AS surprise,
cells[3][1] AS out_of_range
FROM grids
WHERE name = 'small';The results are:
one_cellis6.first_rowis{{1,2,3}}. It is still two-dimensional, with one row.right_blockis{{2,3},{5,6}}.out_of_rangeisNULL. As with one-dimensional arrays, a position outside the bounds is not an error.
The surprise column is {{1,2},{4,5}}, not the second row's first two values.
PostgreSQL has no subscript syntax that returns a row as a one-dimensional array. Use generate_subscripts with ARRAY(subquery) for that, as shown in the next section.
Converting between 2D arrays and rows
unnest on a multidimensional array ignores the shape. It returns every element as one row, in row-major order, meaning the last subscript varies fastest. With WITH ORDINALITY you can recover coordinates from the flat position:
SELECT g.name,
(u.pos - 1) / array_length(g.cells, 2) + 1 AS row_no,
(u.pos - 1) % array_length(g.cells, 2) + 1 AS col_no,
u.val
FROM grids AS g
CROSS JOIN LATERAL unnest(g.cells) WITH ORDINALITY AS u(val, pos)
ORDER BY g.name, u.pos;This arithmetic assumes lower bounds of 1, which is true for arrays built with the constructor or a plain literal.
To get whole rows back as one-dimensional arrays, use generate_subscripts to walk each dimension and ARRAY(subquery) to collect values:
SELECT g.name,
i AS row_no,
ARRAY(SELECT g.cells[i][j]
FROM generate_subscripts(g.cells, 2) AS j
ORDER BY j) AS row_values
FROM grids AS g
CROSS JOIN LATERAL generate_subscripts(g.cells, 1) AS i
ORDER BY g.name, i;Going the other way, array_agg over one-dimensional arrays builds a two-dimensional array. All inputs must have the same length, or PostgreSQL raises cannot accumulate arrays of different dimensionality:
WITH row_arrays AS (
SELECT i,
ARRAY(SELECT g.cells[i][j]
FROM generate_subscripts(g.cells, 2) AS j
ORDER BY j) AS vals
FROM grids AS g
CROSS JOIN LATERAL generate_subscripts(g.cells, 1) AS i
WHERE g.name = 'small'
)
SELECT array_agg(vals ORDER BY i) AS rebuilt
FROM row_arrays;
-- {{1,2,3},{4,5,6}}ARRAY(subquery) follows the same rule. If the subquery returns array values, the result has one more dimension, and every returned array must have identical dimensions.
Modifying multidimensional arrays
Single elements and slices can be assigned directly. A slice assignment needs a value with matching shape:
UPDATE grids SET cells[2][3] = 60 WHERE name = 'small';
UPDATE grids
SET cells[1:2][1:2] = ARRAY[[0,0],[0,0]]
WHERE name = 'small';Assignment cannot grow a multidimensional array. Writing to a position outside the current bounds raises an error. For one-dimensional arrays, assigning to an adjacent position extends the array, but that does not work here.
Many helper functions are limited to one dimension:
array_appendandarray_prependraise an error on multidimensional input.array_removeandarray_replacedo not work on arrays with more than one dimension in the way you would expect.array_removeraises an error, because removing an element would break the rectangular shape.array_positionandarray_positionsraise an error. They search only one-dimensional arrays.
The one tool for growing is array_cat (or its operator form ||). It joins two arrays of the same dimension count and compatible sizes, or adds a one-dimensional array as a new row:
SELECT array_cat(ARRAY[[1,2],[3,4]], ARRAY[5,6]);
-- {{1,2},{3,4},{5,6}}
UPDATE grids
SET cells = array_cat(cells, ARRAY[13,14,15])
WHERE name = 'small';The new row must have the same length as the existing rows. Adding a column has no direct function. You would rebuild the array with the generate_subscripts technique above.
Searching ignores the shape
Containment, overlap, and ANY/ALL treat a multidimensional array as one flat bag of elements. Dimensions play no part:
SELECT ARRAY[[1,2],[3,4]] @> ARRAY[4,1] AS contains,
4 = ANY (ARRAY[[1,2],[3,4]]) AS any_match,
ARRAY[[1,2],[3,4]] = ARRAY[1,2,3,4] AS equal;
-- contains: true, any_match: true, equal: false@> is true because both 4 and 1 appear somewhere in the grid, and it does not matter where. The = comparison is false because equality also compares dimensions, and the two arrays have different shapes.
This also governs indexing. A GIN index on a multidimensional column indexes the individual elements. It can answer "which grids contain the value 7?" but it cannot answer "which grids have a 7 in the top-left corner?". Positional questions need a scan, an expression index on the specific subscript (for example on (cells[1][1])), or a different design.
Limits at a glance
| Limit | Detail |
|---|---|
| Maximum dimensions | 6 |
| Shape | Must be rectangular. No ragged rows. |
| Declared sizes | Ignored. Any array of the element type fits any array column. |
| Element search | `array_position` and `array_positions` need one dimension |
| Element removal | `array_remove` is not supported |
| Growth by assignment | Only one-dimensional arrays |
| Value size | A single field value is limited to about 1 GB, and large values are stored compressed out of line (TOAST) |
| Updates | Changing one cell writes a new copy of the whole array |
| Indexing | GIN indexes elements, not positions |
The last two rows have practical effects. A 1,000 by 1,000 grid of integers is roughly 4 MB. Each single-cell UPDATE rewrites that whole value, and MVCC also keeps the old version until vacuum removes it. An array suits data that you read and write as a unit, not data that you update cell by cell.
Enforcing a shape with a CHECK constraint
Because PostgreSQL ignores declared sizes, enforce the shape yourself. Be careful with empty arrays here. For '{}', array_ndims and array_length return NULL, and a CHECK constraint passes when its condition is NULL. Including cardinality, which returns 0, closes that gap.
CREATE TABLE boards (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
board text[][] NOT NULL
DEFAULT ARRAY[['','',''],['','',''],['','','']]
CONSTRAINT board_is_3x3 CHECK (
cardinality(board) = 9
AND array_ndims(board) = 2
AND array_length(board, 1) = 3
)
);
INSERT INTO boards DEFAULT VALUES;
UPDATE boards SET board[2][2] = 'X' WHERE id = 1;
INSERT INTO boards (board) VALUES ('{}');
-- ERROR: new row for relation "boards" violates check constraint "board_is_3x3"Nine elements in two dimensions with 3 rows means 3 columns, so the three conditions together pin down a 3 by 3 grid. The empty array fails because cardinality is 0.
When another design fits better
Reach for a multidimensional array only when the whole grid is small, has a fixed shape, and is read and written as one value. Otherwise, move to one of these alternatives:
- A table with columns
(grid_id, row_no, col_no, value)lets you query, update, and index single cells. It also handles sparse grids, since you store only the cells that have values. - A
jsonbcolumn handles ragged or nested data and varying depth. You give up element type checking and the array operators. - An array of a composite type, or one row per line of the grid, is a middle path when each "row" has its own meaning.
Common mistakes
- Expecting
cells[2]to return the second row. It returnsNULLfor a two-dimensional array, because a subscript list must supply a position for every dimension (or use slice syntax). - Mixing single subscripts and slices in one expression and getting a different shape than intended.
- Trusting
integer[3][3]in the column declaration to enforce a 3 by 3 shape. - Writing a
CHECKonarray_ndimsalone, which silently accepts empty arrays. - Using
array_positionorarray_removeand discovering the error only when the first multidimensional row arrives. - Using
@>to test for a value at a given position. It tests only for membership.
Exercise
Given cells = ARRAY[[1,2,3],[4,5,6]], what does cells[2][1:2] return, and how do you write an expression that returns only the second row's first two values as a two-dimensional array?
Show answer
cells[2][1:2] is read as cells[1:2][1:2] because one subscript contains a colon, so it returns {{1,2},{4,5}}. To get just the second row, write cells[2:2][1:2], which returns {{4,5}}.
Exercise
A table has board text[][] with a CHECK of array_ndims(board) = 2 AND array_length(board, 1) = 3 AND array_length(board, 2) = 3. Why can INSERT ... VALUES ('{}') still succeed, and how do you fix the constraint?
Show answer
For an empty array, array_ndims and array_length return NULL, so the whole condition evaluates to NULL, and a CHECK constraint accepts NULL. Add cardinality(board) = 9, which returns 0 for an empty array and makes the condition false.
Exercise
You need to find every grid that has the value 7 in cell [1][1]. Does a GIN index on the array column help, and what would you use instead?
Show answer
No. GIN indexes the elements as a flat set and ignores position, so it can only answer whether 7 appears anywhere. Create a B-tree expression index on (cells[1][1]) and query WHERE cells[1][1] = 7, or store one row per cell in a table and index (row_no, col_no, value).