In sqlalchemy, is there a way to sort so that empty cells are at the end regardless of the sort order?
2 answers
On databases that support NULLS LAST
you can sort NULL
at the end by doing
SELECT * FROM table1 ORDER BY mycol ASC NULLS LAST;
You need to convert ''
to NULL
so you can do this (which I recommend doing anyway), either in data or as part of a query:
SELECT * FROM table1 ORDER BY (CASE mycol WHEN '' THEN NULL ELSE mycol END) ASC NULLS LAST;
Alternatively, a more portable approach
SELECT * FROM table1 ORDER BY (CASE WHEN mycol IS NULL OR mycol = '' THEN 1 ELSE 0 END) ASC, mycol;
To write this to SQLAlchemy:
.order_by(case([(or_(tabel1.mycol.is_(None), table1.mycol == ""), 1)],
else_=0), table1.mycol)
+2
source to share
SQLAlchemy has a modifier NULLS LAST
for expressions ORDER BY
:
sqlalchemy.sql.expression.nullslast(column)
See http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.nullslast
+1
source to share