Group by & count function in sqlalchemy Group by & count function in sqlalchemy python python

Group by & count function in sqlalchemy


The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import funcsession.query(Table.column, func.count(Table.column)).group_by(Table.column).all()


If you are using Table.query property:

from sqlalchemy import funcTable.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import funcsession.query(Table.column, func.count(Table.column)).group_by(Table.column).all()


You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.