Practical technical guides / Core IT: databases

PostgreSQL Array Positions Are Not Always Their Stored Subscripts

Preserve zero-based and multidimensional array coordinates with generate_subscripts; distinguish ordinality, empty arrays and null values.

By Sandeep Belgavi · Published 2026-11-25 · Prepared 2026-11-24

Preserve zero-based and multidimensional array coordinates with generate_subscripts; distinguish ordinality, empty arrays and null values.

Array order and array subscripts are different information

PostgreSQL arrays usually appear with a lower bound of one, so it is tempting to treat their first element as subscript one everywhere. The type permits other lower bounds. A stored array can begin at zero, a negative index or another integer. A function that returns elements in order may number its output rows from one without preserving those original subscripts.

This evergreen guide uses a synthetic measurement vector with three slots. Its array is [0:2]={10,NULL,30}: the value ten belongs to subscript zero, a null element belongs to subscript one and thirty belongs to subscript two. The example contains no personal measurements or production data. Its purpose is to show how a seemingly reasonable unnest-and-index query can join each value to the wrong slot.

The distinction matters whenever subscripts carry meaning, such as an offset within a fixed synthetic signal or a position in an imported numeric format. If the application only needs a list, normalize the representation deliberately and prohibit unexpected shapes. Do not assume the database type enforces the list conventions of the client language.

Inspect the shape before indexing the data

PostgreSQL exposes array_lower, array_upper, array_ndims, array_dims, array_length and cardinality. They answer different questions. Cardinality counts elements across dimensions, while array_length examines one dimension. An empty array can have cardinality zero while array_length for its first dimension is null. A SQL null array is different again: the array value itself is unknown or absent.

-- Author: Sandeep Belgavi. Original synthetic shape fixture.
WITH fixture(a) AS (
  VALUES ('[0:2]={10,NULL,30}'::integer[])
)
SELECT array_dims(a), array_lower(a,1), array_upper(a,1),
       array_length(a,1), cardinality(a), a[0], a[1]
FROM fixture;

The expected shape is [0:2], with lower bound zero, upper bound two, length three and cardinality three. Subscript zero returns ten; subscript one returns a null element. That null is a real position in the array. Filtering nulls before recording positions would collapse the vector and change what later positions mean.

An out-of-range scalar subscript also returns null under PostgreSQL's array rules. Therefore a null result alone does not distinguish an existing null element from a missing subscript. If that distinction matters, compare the requested subscript with the stored bounds or enumerate valid subscripts before retrieving values.

Reproduce the ordinality mismatch

UNNEST returns elements in storage order. WITH ORDINALITY adds a row counter beginning at one to a set-returning function's output. That counter is useful for ordering the emitted rows, but it is not the array's original lower-bound-aware subscript. Naming the column array_index does not change its meaning.

-- Author: Sandeep Belgavi. The final column intentionally demonstrates a bug.
WITH fixture(a) AS (
  VALUES ('[0:2]={10,NULL,30}'::integer[])
)
SELECT u.value, u.ordinal, a[u.ordinal] AS incorrectly_reindexed
FROM fixture
CROSS JOIN LATERAL unnest(a) WITH ORDINALITY AS u(value,ordinal);

The emitted values are ten, null and thirty with ordinalities one, two and three. Reindexing the original array with those numbers reads null, thirty and an out-of-range null. Every individual operation is valid SQL, so no exception announces the misalignment. This is a semantic contract failure rather than a parser or type error.

A count check would miss it: both the correct and incorrect query produce three rows. A sum can also conceal some errors depending on the values and null handling. Tests should compare ordered pairs of original subscript and value. Choose fixtures with a null element and asymmetric values so a shifted mapping cannot accidentally look correct.

When unnesting several arrays together, PostgreSQL can pad a shorter input with nulls. That adds another possible source of a null output value. Validate the intended equal-length relationship before treating parallel arrays as aligned columns. For a measurement vector and a label vector, store or test their shared coordinate contract instead of assuming equal output row counts prove that every label has a corresponding measurement.

Preserve actual subscripts when they matter

Use generate_subscripts for the selected dimension, then index the array using the returned subscript. This keeps the original coordinate with each value. An explicit ORDER BY makes output ordering part of the query rather than an assumption about the planner's chosen execution.

-- Author: Sandeep Belgavi. Preserve the stored coordinates.
WITH fixture(a) AS (
  VALUES ('[0:2]={10,NULL,30}'::integer[])
)
SELECT s.subscript, a[s.subscript] AS value
FROM fixture
CROSS JOIN LATERAL generate_subscripts(a,1) AS s(subscript)
ORDER BY s.subscript;

The result is (0,10), (1,NULL), (2,30). For a one-dimensional array, an application could calculate lower_bound plus ordinality minus one, but generate_subscripts states the intent more directly. That arithmetic is also easy to misuse once a value can have multiple dimensions.

For a two-dimensional array, enumerate both dimensions and access a[i][j]. UNNEST flattens the values, so one output counter does not by itself preserve both coordinates. PostgreSQL multidimensional arrays must have matching extents within their rectangular representation; they are not arbitrary nested ragged lists. Reject unsupported dimensions at the boundary instead of flattening them accidentally.

Choose a list contract or a coordinate contract

If the application wants ordinary one-based lists, enforce that contract in the table and its ingestion path. A declaration such as integer[] does not restrict every value to one dimension with lower bound one. Check the dimension and lower bound, while making an explicit decision about empty arrays and SQL null arrays.

-- Author: Sandeep Belgavi. Empty lists allowed, null arrays rejected.
CREATE TABLE synthetic_vector (
  vector_id text PRIMARY KEY,
  samples integer[] NOT NULL,
  CHECK (
    cardinality(samples)=0 OR
    (array_ndims(samples)=1 AND array_lower(samples,1)=1)
  )
);

The NOT NULL constraint applies to the array value, not every element. If null elements are forbidden too, add a separate policy and test it. Do not assume a CHECK expression rejects every unknown result: SQL check constraints accept true or unknown and reject false. Combining shape checks with an explicit NOT NULL constraint makes the intended cases easier to reason about.

For a coordinate contract, preserve lower bounds and dimensional metadata through serialization. A client receiving only an ordered list of values may not retain those coordinates. Send explicit coordinate-value records or a separate shape object. A representation change should be an intentional conversion with documented behavior, not a side effect of whichever driver happens to be used.

Equality and joins can include shape information

Two arrays with the same visible element sequence can differ in dimensional metadata, including their subscript ranges. PostgreSQL's array comparison behavior takes shape information into account after comparing element contents. A database equality check can therefore disagree with an application comparison that converted both arrays into plain lists first.

Decide whether identity means the same ordered values or the same coordinate-bearing array. Normalize to a chosen representation before hashing, caching or deduplicating if the application uses value-list identity. Preserve shape when coordinates are meaningful. Mixing those meanings creates confusing cache misses or merges records that should remain distinct.

For many workloads, a child table with vector_id, subscript and value is simpler. It gives each coordinate an explicit relational key, supports constraints on individual rows and avoids hidden shape assumptions at client boundaries. Arrays remain useful for compact values and array operations, but convenience at ingestion should not dictate an unsuitable update or query model.

Verify empty, null and multidimensional boundaries

The companion SQL fixture asserts the actual bounds, demonstrates the ordinal mismatch and verifies the corrected subscript-value mapping. It separately checks an empty array and a SQL null array. These are independent cases: zero elements, one null element and a missing array must not be conflated in aggregate or validation logic.

Add a negative-lower-bound fixture and a two-dimensional fixture before claiming the ingestion path handles arbitrary arrays. Verify that the one-based-list table accepts an ordinary list and an empty list while refusing the zero-based vector and unsupported dimensions. Test the application driver's round trip if coordinate preservation matters; SQL-only tests cannot establish how a driver maps arrays into a host-language collection.

The operational fix is small once the contract is clear. Use ordinality to number emitted rows, generate_subscripts to retain stored coordinates, and explicit constraints when the application only accepts ordinary lists. The important test is not whether a query returns the expected number of rows. It is whether each value still belongs to the coordinate the application intended.

Run the example yourself

The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources checked 2026-11-24. Original explanation and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.