0

I would like to select rows in a table in which a certain number of items in an array column meet a comparison condition (>= n). Is this possible without using unnest?

1 Answer 1

1

unnest() is a natural way to count filtered elements in an array. However, you can hide this in an sql function like this:

create or replace function number_of_elements(arr int[], val int)
returns bigint language sql
as $$
    select count(*)
    from unnest(arr) e
    where e > val;
$$;

with test(id, arr) as (
    values 
        (1, array[1,2,3,4]),
        (2, array[3,4,5,6]))
select id, arr, number_of_elements(arr, 3)
from test;

 id |    arr    | number_of_elements 
----+-----------+--------------------
  1 | {1,2,3,4} |                  1
  2 | {3,4,5,6} |                  3
(2 rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.