I want a "group by and count" command in sqlalchemy. How can I do this?
Asked
Active
Viewed 2e+01k times
172
-
1Seems to be a duplicate of http://stackoverflow.com/questions/370174/sqlalchemy-with-count-groupby-and-orderby-using-the-orm – Arnkrishn Jun 27 '09 at 05:19
3 Answers
247
The documentation on counting says that for group_by
queries it is better to use func.count()
:
from sqlalchemy import func
session.query(Table.column,
func.count(Table.column)).group_by(Table.column).all()
-
31and here's the full statement for those using `Table.query` property instead of `session.query()`: `Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()` – Jakub Kukul Mar 26 '18 at 23:33
-
2@jkukul This should be an answer on its own - I always wondered how to get around this limitation when doing subqueries and wanted to use group_by and count..! – chris-sc Jul 05 '18 at 12:03
-
1The edits to this answer render the first sentence kind of meaningless. "Better" than *what*? – Mark Amery Nov 09 '18 at 13:38
65
If you are using Table.query
property:
from sqlalchemy import func
Table.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 func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Jakub Kukul
- 12,032
- 3
- 54
- 53
-
1fantastic. Question. how can i do this? `count(column_name) as total_count` – Rolly May 20 '21 at 22:32
-
37
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.

fccoelho
- 6,012
- 10
- 55
- 67
-
Thanks for the question, while thinking about it I found an answer to a related question of mine. ;-) – fccoelho Mar 11 '11 at 17:11