Skip to content

Instantly share code, notes, and snippets.

@imfht
Forked from hest/gist:8798884
Created July 27, 2017 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imfht/341468d410155b5be35c66acbb103d7f to your computer and use it in GitHub Desktop.
Save imfht/341468d410155b5be35c66acbb103d7f to your computer and use it in GitHub Desktop.
Fast SQLAlchemy counting (avoid query.count() subquery)
def get_count(q):
count_q = q.statement.with_only_columns([func.count()]).order_by(None)
count = q.session.execute(count_q).scalar()
return count
q = session.query(TestModel).filter(...).order_by(...)
# Slow: SELECT COUNT(*) FROM (SELECT ... FROM TestModel WHERE ...) ...
print q.count()
# Fast: SELECT COUNT(*) FROM TestModel WHERE ...
print get_count(q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment