Skip to content

Instantly share code, notes, and snippets.

@nedludd0
nedludd0 / gist:a9f3fe9cf138c423befa50ba89d40c55
Last active February 5, 2021 11:29 — forked from hest/gist:8798884
Fast SQLAlchemy counting (avoid query.count() subquery)
# https://gist.github.com/hest/8798884
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 ...) ...