Get the row count from a query

130 views
Skip to first unread message

Jason Hoppes

unread,
Jun 3, 2022, 1:45:39 PM6/3/22
to sqlalchemy
I would like to generate the following SQL using the ORM. I am testing for no rows returning:

select count(*) from users where id = 9999

I found session.query(User.id_).count() however that does not have a where clause. How would this be performed in the ORM with a where clause?

Thanks,

Jason

Jason Hoppes

unread,
Jun 3, 2022, 2:45:49 PM6/3/22
to sqlalchemy
I believe I finally found a solution:

 select(func.count(User.id_)).where(User.id_ == id)

Thank you for taking the time to look.

Sergey V.

unread,
Jun 4, 2022, 7:08:25 AM6/4/22
to sqlalchemy
An alternative would be

session.query(User).filter(User.id_ == id).count()

Jason Hoppes

unread,
Jun 6, 2022, 8:43:34 AM6/6/22
to sqlalchemy
Thank you Sergey.
Reply all
Reply to author
Forward
0 new messages