When we sort data, we need to take into account the NULL values. I’d like to share something I’ve learned through a practical example while building a Python application.
The SQL
For example, to build this SQL Statement:
|
|
The Python Equivalent
Write the SQLAlchemy statement in the following way:
|
|
A few comments:
coalesce
function takes the first value if provided otherwise, it takes the second.nullslast
function ensure the null values don’t appear first, which is the default logic in SQL
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Photo by RDNE Stock project