2

I am trying to find out if there is any nicer way I can check if a table of users contains a group of names instead of checking them one at a time

This is what I am using to currently check the User table one at a time which gives me True or False if the user exists in the table:

ret = session.query(exists().where(Users.name == 'Jack')).scalar()  

So is there a way to do this:

ret = session.query(exists().where(Users.name == 'Jack', 'Bob', 'Sandy')).scalar()

Rather than this:

ret1 = session.query(exists().where(Users.name == 'Jack')).scalar()  
ret2 = session.query(exists().where(Users.name == 'Bob')).scalar()  
ret3 = session.query(exists().where(Users.name == 'Sandy')).scalar()  
1
  • 1
    Use in_. Commented Aug 22, 2016 at 21:44

1 Answer 1

2

You are correct to use the exists() expression, but combine it with a subquery that leverages the in_() expression.

q = session.query(Users).filter(Users.name.in_(['Jack', 'Bob', 'Sandy']))
# Below will return True or False
at_least_one_user_exists = session.query(q.exists()).scalar()

This translates to the following SQL:

SELECT EXISTS (
    SELECT 1 FROM users WHERE users.name IN ('Jack', 'Bob', 'Sandy')
) AS anon_1

...only the SQLAlchemy described above query will return True or False

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! this made a lot of sense! One more question, is there a way for exists to return true or false based off if all users existed?
@zet "all" instead of "any" requires a drastically different query. See this question.

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.