Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting COUNT from sqlalchemy

I have:

res = db.engine.execute('select count(id) from sometable')

The returned object is sqlalchemy.engine.result.ResultProxy.

How do I get count value from res?

Res is not accessed by index but I have figured this out as:

count=None
for i in res:
    count = res[0]
    break

There must be an easier way right? What is it? I didn't discover it yet. Note: The db is a postgres db.

like image 724
Aayush Karki Avatar asked Jun 22 '17 03:06

Aayush Karki


People also ask

What does query all () return?

all() will return all records which match our query as a list of objects.

What does SQLAlchemy query return?

It returns exactly one result or raise an exception. It applies one or more ORDER BY criterion to the query and returns the newly resulting Query. It performs a bulk update query and updates rows matched by this query in the database.

What is subquery in SQLAlchemy?

The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

How do I select a column in SQLAlchemy?

SQLAlchemy Core The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.


2 Answers

While the other answers work, SQLAlchemy provides a shortcut for scalar queries as ResultProxy.scalar():

count = db.engine.execute('select count(id) from sometable').scalar()

scalar() fetches the first column of the first row and closes the result set, or returns None if no row is present. There's also Query.scalar(), if using the Query API.

like image 102
Ilja Everilä Avatar answered Oct 10 '22 22:10

Ilja Everilä


The ResultProxy in SQLAlchemy (as documented here http://docs.sqlalchemy.org/en/latest/core/connections.html?highlight=execute#sqlalchemy.engine.ResultProxy) is an iterable of the columns returned from the database. For a count() query, simply access the first element to get the column, and then another index to get the first element (and only) element of that column.

result = db.engine.execute('select count(id) from sometable')
count = result[0][0]

If you happened to be using the ORM of SQLAlchemy, I would suggest using the Query.count() method on the appropriate model as shown here: http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=count#sqlalchemy.orm.query.Query.count

like image 23
foslock Avatar answered Oct 10 '22 21:10

foslock