0

Let's say there is a base:

CREATE TABLE test (
    ids integer[]
);

With data

INSERT INTO test VALUES ('{1, 2, 3, 4}');
INSERT INTO test VALUES ('{5}');

I would like to find the number of occurrences of an arbitrary array, say: '{5,1}' in the test database, in what way can this be done?

In my attempts, I could only find the total number of elements in the array, except for those found:

select sum(array_length(array(
    (select unnest(ids) except select unnest(array[5,1]))
), 1)) from test;

But, i need exactly the number of occurrences found from the transferred array. How i can find . that?

DbFiddle

2
  • If one row contained both 1 and 5, should that be counted once or twice? Commented Oct 24, 2019 at 16:16
  • @jjanes Only once. For example, in the example that's in the post, the answer should be: 2 Commented Oct 24, 2019 at 16:22

1 Answer 1

3

You possibly want this:

select count(*) from test, unnest(ids) as id where id =ANY('{5,1}');

Or to count each row from test at most once, then this:

select count(*) from test where ids && '{5,1}'

They both give '2' in your example, but they don't do the same thing in general.

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.