2

I have a postgresql array a = [key1,key2,...] with primary keys and a table foo.

What's the best way to check if all the primary keys in a exist in the table foo?

To clarify: I am looking for a query that returns TRUE if and only if all the keys in the array a exist in the table foo.

Thanks!

2 Answers 2

1

You can count rows from the join of the table and unnested array:

select count(*) = array_length(array[1,2], 1)
from foo
join unnest(array[1,2]) id
using (id);
Sign up to request clarification or add additional context in comments.

Comments

0

Being vague in the question, I am going to assume you have the array in some kind of a programming language and you want to check it against the primary key column of the table.

Look at this example of using the contains @> operator (around the middle of the page).

Elaborate in the comments if that is not what you are looking for and please be as specific as you can.

2 Comments

That is unfortunately not what i meant. The array is a posgresql array.
I'm not entirely sure this doesn't work with PG arrays. While there is a cast required in the example because the storage type is VARCHAR, try @> with an array type and see.

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.