Sum PostgreSQL arrays in place [1,2,3] + [2,3,4] = [3,5,7]
✓ Published0🌍 Public
Aandrewxhill
Last edited Jan 23, 2012
Created on Jan 23, 2012
This example shows how to sum PostgreSQL integer arrays element-wise, so `{1,2,3,2,1}` plus `{7,2,3,2,1}` yields `{8,4,6,4,2}`. The code defines a custom PL/pgSQL function `AXH_Vector_Sum(int[], int[])` that iterates over the shorter array, adding each element to the corresponding position in the longer array, and returns the result. It also creates a PostgreSQL aggregate `vector_sum` using this function as its state transition, with an initial condition of `'{0}'`. A sample `SELECT` statement demonstrates the function directly on two integer arrays.
AI-generated description