Sub topic 10
Multidimensional arrays and their limits
Assume you know basic SELECT, array subscripts, NULL, and PostgreSQL data types. This chapter focuses on arrays with two or more dimensions, such as a grid of values.
A multidimensional array is rectangular
A multidimensional array stores values in a fixed rectangular shape. For example, this array has two rows and three columns:
SELECT ARRAY[
[10, 20, 30],
[40, 50, 60]
] AS grid;The array has six integer elements. It is not stored as two separate row arrays. PostgreSQL stores one array value together with metadata describing its dimensions and bounds.
The number of dimensions is written with repeated brackets in a column declaration:
CREATE TEMP TABLE sensor_grids (
sensor_id text PRIMARY KEY,
readings integer[][]
);
INSERT INTO sensor_grids (sensor_id, readings)
VALUES (
'north',
ARRAY[
[10, 11, 12],
[20, 21, 22]
]
);However, PostgreSQL does not treat integer[] and integer[][] as different data types. The number of dimensions is not part of the array type. The declaration documents the intended shape, but it does not enforce that every inserted value has two dimensions.
Read elements and slices
Array subscripts are normally one-based. Give one subscript for each dimension:
SELECT
readings[1][2] AS first_row_second_column,
readings[2][3] AS second_row_third_column
FROM sensor_grids
WHERE sensor_id = 'north';The results are 11 and 22.
A slice uses a lower and upper bound for a dimension. This query returns the second and third columns from both rows:
SELECT readings[1:2][2:3] AS smaller_grid
FROM sensor_grids
WHERE sensor_id = 'north';The result is still an array, not a set of rows. A slice can have fewer elements than requested when its bounds extend beyond the array. Accessing an individual position outside the array returns NULL.
Inspect dimensions and shape
Use array_ndims to count dimensions. Use array_dims to display each dimension's lower and upper bounds. array_length reports the size of one selected dimension, while cardinality reports the total number of elements.
SELECT
array_ndims(readings) AS dimensions,
array_dims(readings) AS bounds,
array_length(readings, 1) AS row_count,
array_length(readings, 2) AS column_count,
cardinality(readings) AS total_values
FROM sensor_grids
WHERE sensor_id = 'north';For this value, the results describe two dimensions, bounds [1:2][1:3], two rows, three columns, and six total values.
The functions inspect the value that is present. They do not confirm that a column always contains the same shape. If an application requires every value to be two rows by three columns, enforce that with a constraint or validate the shape before writing:
ALTER TABLE sensor_grids
ADD CONSTRAINT readings_are_two_by_three
CHECK (
array_dims(readings) = '[1:2][1:3]'
);This constraint also requires the expected lower bounds. A check based on array_length can be more flexible if other lower bounds are acceptable.
Limits and irregular shapes
A multidimensional PostgreSQL array cannot contain ragged rows. This value is invalid because the inner arrays have different lengths:
SELECT ARRAY[
[1, 2],
[3, 4, 5]
];PostgreSQL reports that multidimensional arrays must have matching dimensions. Use a separate related table when rows can have different lengths or when each element needs its own identity, metadata, or relationships.
Array bounds do not have to start at one. Functions such as array_fill can create an array with another lower bound:
SELECT array_fill(0, ARRAY[2, 3], ARRAY[0, 0]) AS zero_based_grid;This creates two dimensions with bounds [0:1][0:2]. Therefore, inspect array_dims when code receives arrays from different sources. Do not assume that every valid array starts at one.
unnest flattens a multidimensional array into values, but it does not preserve row and column coordinates. Use generate_subscripts when positions matter:
SELECT
rows.row_no,
cols.column_no,
g.readings[rows.row_no][cols.column_no] AS reading
FROM sensor_grids AS g
CROSS JOIN LATERAL generate_subscripts(g.readings, 1) AS rows(row_no)
CROSS JOIN LATERAL generate_subscripts(g.readings, 2) AS cols(column_no)
WHERE g.sensor_id = 'north'
ORDER BY rows.row_no, cols.column_no;Choose a shape deliberately
| Requirement | Suitable design |
|---|---|
| A fixed-size grid used as one value | Multidimensional array |
| Rows with different lengths | Related table |
| Searchable elements with attributes | Related table |
| A small matrix passed to calculations | Multidimensional array |
Multidimensional arrays work well for compact, fixed-shape data. They become awkward when the shape changes, individual elements need updates, or queries must search and join on each element.
Exercise
Why does PostgreSQL reject an array whose first row has two elements and whose second row has three?
Show answer
A multidimensional array must be rectangular. Every row in the same dimension must have the same length.