Other SQL Clauses
SQLAlchemy ORM also exposes support for other clauses in SQL, such as ORDER BY, GROUP BY, LIMIT, and OFFSET. All of these are supported by this connector:
ORDER BY
The following example sorts by a specified column using the session object's query() method:rs = session.query(Contacts).order_by(Contacts.AnnualRevenue) for instance in rs: print("Id: ", instance.Id) print("Id: ", instance.Id) print("CustomerName: ", instance.CustomerName) print("---------")
You can also use the session object's execute() method perform an ORDER BY. For example:
rs = session.execute(Contacts_table.select().order_by(Contacts_table.c.AnnualRevenue)) for instance in rs:
GROUP BY
The following example uses the session object's query() method to group records with a specified column:rs = session.query(func.count(Contacts.Id).label("CustomCount"), Contacts.Id).group_by(Contacts.Id) for instance in rs: print("Count: ", instance.CustomCount) print("Id: ", instance.Id) print("---------")
You can also use the session object's execute() method to perform a GROUP BY:
rs = session.execute(Contacts_table.select().with_only_columns([func.count(Contacts_table.c.Id).label("CustomCount"), Contacts_table.c.Id]).group_by(Contacts_table.c.Id)) for instance in rs:
LIMIT and OFFSET
The following example uses the session object's query() method to skip the first 100 records and fetch the following 25:rs = session.query(Contacts).limit(25).offset(100) for instance in rs: print("Id: ", instance.Id) print("Id: ", instance.Id) print("CustomerName: ", instance.CustomerName) print("---------")
You can also use the session object's execute() method to set a LIMIT or OFFSET:
rs = session.execute(Contacts_table.select().limit(25).offset(100)) for instance in rs: