Search code snippets, questions, articles...

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 


#To get all records

#To get first record
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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(
    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(
    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?