0

I've got the following table:

userId|imageId|
------|-------|
     1|      1|
     1|      2|
     1|      3|

and in a special validator I want to make sure that those imageIds I'm given (let's say, 2 and 3) exist in this table and belong to a user with userId = 1;

How do I do that in Postgres?

My PostgreSQL is 12.3.

0

1 Answer 1

1

Fetch count of records that matched:

select count(imageId) from table_name where userId=1 and imageId in (2, 3);

Check if count matches the length of given imageId list and return true or false based on that:

if query.first()[0] >= len(imageIdList):
     return True
return False
Sign up to request clarification or add additional context in comments.

2 Comments

yeah basically in my case I can do something like: select uii."imageId" from user_images_image uii where uii."userId" = 1 and uii."imageId" in (1, 5, 4); but it will return 1, that's to say it will return those ids that do exist, indeed then I could compare the result to the initial list of ids and based on the result of this comparison return true or false in my validator but is there a less verbose way to do that? Ideally, I would like to return something if all of the specified ids are in the DB and return nothing if at least one of them is missing. Is there a way to achieve that?
You could do that by comparing the number of records that matched and number of imageId's that were given. See my updated answer.

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.