Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In sqlalchemy, is there a way to sort so that empty cells are at the end irrespective or sort order?

I have a pretty standard setup and want to sort by a column:

someselect.order_by(asc(table1.mycol))

However, I want rows with '' or NULL for mycol to appear at the end of the results. Is there a way to do this?

like image 807
rohithpr Avatar asked Jun 05 '17 19:06

rohithpr


1 Answers

SQLAlchemy has a NULLS LAST modifier for ORDER BY expressions:

sqlalchemy.sql.expression.nullslast(column)

See http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.nullslast

You can use it like this:

from sqlalchemy import nullslast

# ...

someselect.order_by(nullslast(table1.mycol.asc())) 

There is also nullsfirst.

like image 131
wodow Avatar answered Nov 09 '22 22:11

wodow