Pad arrays with NULL to maximum length for custom aggregate function - no array_fill function

236 Views Asked by At

This is almost same question as Pad arrays with NULL to maximum length for custom aggregate function. the only problem with the answer provided is that function array_fill doesn't exist in Postgres 8.2.

How can I make it useable given the version I have?

2

There are 2 best solutions below

2
Ezequiel Tolnay On BEST ANSWER

This should work:

CREATE TEMP TABLE t AS (SELECT arr::text[] FROM UNNEST('{"{1}","{}","{a,b,c}"}'::text[]) arr);
SELECT COALESCE(NULLIF(arr || nulls[1:max-(1+array_upper(arr, 1)-array_lower(arr, 1))], '{}'), nulls[1:max])
FROM t,
  (SELECT ARRAY(SELECT NULL::text FROM generate_series(1, 100)) AS nulls) a,
  (SELECT 1 + max(array_upper(arr, 1)-array_lower(arr, 1)) AS max FROM t) m
1
Abelisto On
do $$
declare
  arr int[] := array[1,2,3];
begin
  raise info '%', arr;
  arr[1] := coalesce(arr[1]); -- Set lower bound if array is null
  arr[10] := coalesce(arr[10]); -- Set upper bound
  raise info '%', arr;
end $$;

Output:

INFO:  {1,2,3}
INFO:  {1,2,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL}

Not a complete answer, but it is easy to convert it to the function.

Disclaimer: Tested on PostgreSQL 9.5