python

Get highest id or value record from a column SqlAlchemy Query

To get the raw based on the biggest value from a table column, you can use func.max() method of SQLAlchemy. It takes the column name of the table as a parameter.

from sqlalchemy import func 

session.query(func.max(table_name.column_name))

#To get all records
session.query(func.max(table_name.column_name)).all()

#To get first record
session.query(func.max(table_name.column_name)).first()

In the code snippet, we are importing func method from SQLAlchemy. Now you can use this method to get the highest value record. We are using func.max() method inside SQLAlchemy query to get the records.

from sqlalchemy import func

def highest_records():
    result = session.query(func.max(students.id)).all()
    return result

results = highest_records()
In this code snippet, we have a table model students which contains a column named id and we want to get the records which has highest value in id column.
from sqlalchemy import func

def first_highest_id_record():
    result = session.query(func.max(products.id)).first()
    return result

results = first_highest_id_record()
We are getting the first record from the products table which has the highest value from the id column.
Was this helpful?