I\'m using SQLAlchemy with a MySQL database and I\'d like to count the rows in a table (roughly 300k). The SQLAlchemy count function takes about 50 times as long to run as w
The reason is that SQLAlchemy's count() is counting the results of a subquery which is still doing the full amount of work to retrieve the rows you are counting. This behavior is agnostic of the underlying database; it isn't a problem with MySQL.
The SQLAlchemy docs explain how to issue a count without a subquery by importing func from sqlalchemy.
session.query(func.count(User.id)).scalar()
>>>SELECT count(users.id) AS count_1 \nFROM users')