I have a column of Int Array. I want to add another column to the table, that always shows the number elements in that array for that row. It should update this value automatically. Is there a way to embedd a function as default value? If so, how would this function know where to pick its argument (the int array column/row number).
Share
In a normalized table you would not include this functionally dependent and redundant information as a separate column.
It is easy and fast enough to compute it on the fly:
Or:
array_length()has been introduced with PostgreSQL 8.4. Maybe an incentive to upgrade? 8.3 is going out of service soon.With Postgres 8.3 you can use:
But that’s inferior, because the array index can start with any number, if entered explicitly.
array_upper()would not tell the actual length then, you would have to subtractarray_lower()first. Also note, that in PostgreSQL arrays can always contain multiple dimensions, regardless of how many dimensions have been declared. I quote the manual here:(True for 8.3 and 9.1 alike.) That’s why I mentioned
array_dims()first, to give a complete picture.Details about array functions in the manual.
You may want to create a view to include that functionally dependent column: