0

In this question I got the idea of using array_position

CREATE Temp TABLE foo (
    id    integer PRIMARY KEY,
      name  text[] NOT NULL);
INSERT INTO foo (id, name) VALUES
    (1, array[NULL,'c7b74ea7a0ee2924ca6f2fb4f90ac378',NULL]);
INSERT INTO foo (id, name) VALUES 
    (2, array[NULL,NULL,NULL,NULL,NULL,'4bf4b5c141a361e4eac28b405b31baeb',NULL,'4bf4b5c141a361e4eac28b405b31baeb',NULL]); 

select array_position(d.name,(array_agg( x.v) FILTER (WHERE x.v IS NOT NULL))[1])
from foo d
  cross join lateral unnest(d.name) as x(v)
group by d.name;

returns the correct answer:

| "array_position"|
|:---------------:|
|      2          |
|      6          |

Is there a better function to use for this?

1 Answer 1

1
SELECT id, array_position(name, (array_remove(name, NULL))[1])
FROM foo;

https://dbfiddle.uk/WBUAD_vU

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.