Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any functional difference between array_upper and array_length?

The postgres docs on these 2 array functions are pretty weak.

I've tried both functions a few different ways and they seem to return the same results.

SELECT array_length(array[[1, 2], [3, 4], [5, 6]], 1);
SELECT array_upper(array[[1, 2], [3, 4], [5, 6]], 1);

SELECT array_length(array[[1, 2], [3, 4], [5, 6]], 2);
SELECT array_upper(array[[1, 2], [3, 4], [5, 6]], 2);
like image 885
Thomas Pniewski Avatar asked Jul 23 '19 20:07

Thomas Pniewski


People also ask

How do I Unnest an array in PostgreSQL?

Unnest Multi-Dimension Array in PostgreSQL Example: Unnest method using 2-D array as an integer. The below code snippet will expand the integer array into 6 rows. SELECT unnest('[2:4][2:3]={{21,22},{23,24},{25,26}}'::integer[]); Output: In the result set, each array element becomes a row.

What is array length in PostgreSQL?

PostgreSQL ARRAY_LENGTH() function This function is used to return the length of the requested array dimension.

What is cardinality in PostgreSQL?

cardinality() is a system function returning the total number of individual elements in an array. cardinality() was added in PostgreSQL 8.4.


1 Answers

Yes, there is a difference. PostgreSQL array subscripts start at one by default but they don't have to:

By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n].
[...]
Subscripted assignment allows creation of arrays that do not use one-based subscripts. For example one might assign to myarray[-2:7] to create an array with subscript values from -2 to 7.
[...]
By default, the lower bound index value of an array's dimensions is set to one. To represent arrays with other lower bounds, the array subscript ranges can be specified explicitly before writing the array contents.

In general, you need to use array_lower and array_upper instead of assuming that the array will start at 1 and end at array_length(a, n).

like image 131
mu is too short Avatar answered Oct 16 '22 18:10

mu is too short