PostgreSQL – ARRAY_LENGTH Function

The array_length function is used to determine the length (number of elements) of a one-dimensional array in PostgreSQL. This function takes two arguments – the array and the dimension for which you want to find the length.

Here’s the syntax of the array_length function:

array_length(array_expression, dimension)

Where:

array_expression is the array for which you want to determine the length.

dimension is an integer indicating the dimension for which you want to find the length. For a one-dimensional array, this value should typically be 1.

Here’s an example usage of the array_length function:

SELECT array_length('{10, 20, 30, 40}', 1) AS array_length;

The output would be:

array_length 
-------------- 
4 
(1 row)

In this example, the function array_length returns 4 because the provided array has four elements.

You can also use the array_length function in a more complex query. For instance, if you have a table called orders with an product_ids array column, you can find the lengths of those arrays for each order:

SELECT order_id, array_length(product_ids, 1) AS product_count FROM orders;

This query would retrieve the order IDs along with the number of products in each order.

Similar Posts