I have a Flask application which uses Flask-SQLAlchemy to connect to a MySQL database.
I would like to be able to check whether a row is present in a table. How woul
Wrap a .exists()
query in another session.query()
with a scalar()
call at the end. SQLAlchemy will produce an optimized EXISTS
query that returns True
or False
.
exists = db.session.query(
db.session.query(User).filter_by(name='John Smith').exists()
).scalar()
SELECT EXISTS (SELECT 1
FROM user
WHERE user.name = ?) AS anon_1
While it's potentially more expensive due to the subquery, it's more clear about what's being queried. It may also be preferable over db.exists().where(...)
because it selects a constant instead of the full row.