Skip to content
Advertisement

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I’d like to know if it’s possible to generate a SELECT COUNT(*) FROM TABLE statement in SQLAlchemy without explicitly asking for it with execute(). If I use:

session.query(table).count()

then it generates something like:

which is significantly slower in MySQL with InnoDB. I am looking for a solution that doesn’t require the table to have a known primary key, as suggested in Get the number of rows in table using SQLAlchemy.

Advertisement

Answer

I managed to render the following SELECT with SQLAlchemy on both layers.

Usage from the SQL Expression layer

Usage from the ORM layer

You just subclass Query (you have probably anyway) and provide a specialized count() method, like this one.

Please note that order_by(None) resets the ordering of the query, which is irrelevant to the counting.

Using this method you can have a count(*) on any ORM Query, that will honor all the filter andjoin conditions already specified.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement