Postgres array_length() function
Determine the length of an array
The Postgres array_length()
function is used to determine the length of an array along a specified dimension.
It's particularly useful when working with multi-dimensional arrays or when you need to perform operations based on the size of an array. Examples include data analysis where you might need to filter rows based on the number of elements in an array column. Another use case might be application development where you need to validate the size of array inputs since Postgres doesn't natively have a fixed-size array data type.
Function signature
The array_length()
function has the following signature:
anyarray
: The input array to measure.int
: The array dimension to measure (1-based index).
Example usage
Consider a products
table with a categories
column that contains arrays of product categories. We can use array_length()
to find out how many categories each product belongs to.
This query returns the product name, the array of categories it is listed in, and the count of categories for each product.
Advanced examples
Filter rows based on array length
You can use array_length()
in a WHERE
clause to filter rows based on the size of an array.
This query selects all orders that contain more than two items.
Use with multi-dimensional arrays
array_length()
can be used with multi-dimensional arrays by specifying the dimension to measure.
This query returns the number of rows and columns in a 2D array. There is no third dimension in this case, so array_length(data, 3)
returns NULL.
Use in a CHECK constraint
You can use array_length()
in a CHECK
constraint to enforce a condition based on the size of an array column. For example, consider a table that stores the starting lineup of basketball teams as an array.
This constraint ensures that the starting_lineup
array column always contains exactly five elements.
Additional considerations
Null handling
array_length()
returns NULL if the input array is NULL or if the specified dimension does not exist. Always handle potential NULL values in your queries to avoid unexpected results.
Indexing
Note that Postgres array dimensions are indexed starting from 1, not 0. If you specify a dimension less than 1, array_length()
returns NULL.
Performance implications
array_length()
is generally efficient, but be cautious when using it in WHERE
clauses on large tables. Consider creating a function index on the array length if you frequently filter based on this condition.
Alternative functions
cardinality()
- Returns the total number of elements in an array, or NULL if the array is NULL. It's equivalent toarray_length(anyarray, 1)
for one-dimensional arrays.array_dims()
- Returns a text representation of the array's dimensions.array_upper()
andarray_lower()
- Return the upper and lower bounds of the specified array dimension.