John
John

Reputation: 21927

SQLAlchemy max function

Using SQLAlchemy how do you run a max query?

For example

SELECT max(id) FROM some_table

Upvotes: 66

Views: 73440

Answers (5)

snakecharmerb
snakecharmerb

Reputation: 55669

Using SQLAlchemy 2.0-style syntax, the ORM code would be

from sqlalchemy import func, select

with Session() as s:
    result = session.scalar(select(func.max(Table.column)))

and the core version:

with engine.connect() as conn:
    result = conn.scalar(select(func.max(users.c.id))) 

In both cases the use of scalar gives us the result as an integer directly, rather than having to extract from a wrapper object.

Upvotes: 3

Sergey Orshanskiy
Sergey Orshanskiy

Reputation: 209

If you want, for example:

Select max(table_column) from some_table where other_field=10

You can do

from sqlalchemy import func
session.query(func.max(table_column)).filter_by(other_field=10)

Upvotes: 20

ford
ford

Reputation: 11826

For anyone coming here from google 4 years later, func is now in sqlalchemy.sql.expression.

Example:

from sqlalchemy.sql.expression import func

session.query(func.max(Table.column))

Upvotes: 93

Vlad Bezden
Vlad Bezden

Reputation: 89587

from sqlalchemy import func
max_id = session.query(func.max(Table.column)).scalar()

Upvotes: 25

John
John

Reputation: 21927

from sqlalchemy import func 

session.query(func.max(Table.column)) 

Upvotes: 60

Related Questions