sqlalchemy exists for query

PythonSqlalchemyExists

Python Problem Overview


How do I check whether data in a query exists?

For example:

users_query = User.query.filter_by(email='[email protected]')

How I can check whether users with that email exist?

I can check this with

users_query.count()

but how to check it with exists?

Python Solutions


Solution 1 - Python

The following solution is a bit simpler:

from sqlalchemy.sql import exists

print session.query(exists().where(User.email == '...')).scalar()

Solution 2 - Python

The most acceptable and readable option for me is

session.query(<Exists instance>).scalar()

like

session.query(User.query.filter(User.id == 1).exists()).scalar()

which returns True or False.

Solution 3 - Python

There is no way that I know of to do this using the orm query api. But you can drop to a level lower and use exists from sqlalchemy.sql.expression:

from sqlalchemy.sql.expression import select, exists

users_exists_select = select((exists(users_query.statement),)) 
print engine.execute(users_exists_select).scalar()

Solution 4 - Python

2021 Answer for SqlAlchemy 1.4

Refrain from calling .query method and use the select statement directly chained with the .exists method as follows:

from sqlalchemy import select

stmt = select(User).where(User.email=="[email protected]").exists()

Source: https://docs.sqlalchemy.org/en/14/core/selectable.html?highlight=exists#sqlalchemy.sql.expression.exists

Solution 5 - Python

For SQL Server, I had to do this:

from sqlalchemy.sql.expression import literal

result = session.query(literal(True)).filter(
    session.query(User)
    .filter_by(email='...')
    .exists()
).scalar()
print(result is not None)

# Resulting query:
# SELECT 1
# WHERE EXISTS (SELECT 1 
# FROM User
# WHERE User.email = '...')

But it's much simpler without EXISTS:

result = (
    session.query(literal(True))
    .filter(User.email == '...')
    .first()
)
print(result is not None)

# Resulting query:
# SELECT TOP 1 1
# FROM User
# WHERE User.email = '...'

Solution 6 - Python

it can be done:

from sqlalchemy import select

user = session.scalars(
    select(User).where(User.email=="[email protected]")
).first()

if user:
    pass
else:
    pass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlestatView Question on Stackoverflow
Solution 1 - PythonCitoView Answer on Stackoverflow
Solution 2 - PythonEugene KovalevView Answer on Stackoverflow
Solution 3 - PythonGary van der MerweView Answer on Stackoverflow
Solution 4 - Pythonpcko1View Answer on Stackoverflow
Solution 5 - PythonMarredCheeseView Answer on Stackoverflow
Solution 6 - PythonDanniel LittleView Answer on Stackoverflow