Return the number of dimensions (rank) of an array.
ARRAY_NDIMS(array)
## Overview Returns the number of dimensions (rank) of the input array. ARRAY_NDIMS is the canonical metadata function for distinguishing flat arrays from nested matrices and is typically used as a guard before running rank-sensitive logic such as ARRAY_LENGTH on a higher dimension. Typical uses include validating that an input array matches an expected shape, defending against ragged nesting in untrusted data, and emitting shape metadata alongside the payload for downstream consumers. ## Behavior - Returns an INT equal to the rank of the array. - A one-dimensional ARRAY<T> returns 1; an ARRAY<ARRAY<T>> returns 2; and so on recursively. - Inspects type metadata rather than content; the cost is constant regardless of array size. - Consistent with ARRAY_LENGTH and ARRAY_DIMS for the same input. ## Null and empty handling - NULL input array returns NULL. - Empty array returns the statically declared rank based on its element type (for example ARRAY<ARRAY<INT>>() returns 2 even if the outer array is empty). - NULL elements do not affect the rank. ## Compatibility - Matches the standard-compatible ARRAY_NDIMS convention. The engine's static typing guarantees that rank is always known at plan time for declared array columns.
| Name | Type | Description |
|---|---|---|
array | Specifies the input array whose rank is returned. |
-- Flat array has rank 1
SELECT ARRAY_NDIMS(ARRAY[1, 2, 3]); -- 1
-- 2D array has rank 2
SELECT ARRAY_NDIMS(ARRAY[[1, 2], [3, 4]]); -- 2
-- NULL array returns NULL
SELECT ARRAY_NDIMS(CAST(NULL AS ARRAY<INT>)); -- NULL
-- Empty array reports the statically declared rank
SELECT ARRAY_NDIMS(CAST(ARRAY() AS ARRAY<ARRAY<INT>>)); -- 2
-- Validate rank of a per-session metrics array before processing
SELECT session_id
FROM analytics.events.user_sessions
WHERE ARRAY_NDIMS(metrics_matrix) = 2;
-- Combine with ARRAY_LENGTH to log shape metadata
SELECT ARRAY_NDIMS(metrics_matrix) AS rank,
ARRAY_LENGTH(metrics_matrix, 1) AS rows
FROM analytics.events.user_sessions;