Skip to content
Advertisement

SQLAlchemy order_by ASC using nulls_last raises ProgrammingError (Google Spanner DB)

I’m trying to be able to dynamically sort a query by a given column name and have nulls be placed at the end of the list. It works fine when using desc ordering, but raises a ProgrammingError when trying to use nulls_last with asc order. It appears this error is being raised as the result of an InvalidArgument error (see Traces below).

Dependencies

  • sqlalchemy = “~1.4.37”
  • sqlalchemy-spanner = “~1.2.0”

We’re using Google Cloud Spanner for our database.

Original Query

Generating Method

JavaScript

Translated Query

When called with sort_by="my_column" and order_by="desc"

JavaScript

The above works fine. So as long as I want to order by descending, I’m good. Unfortunately, that’s not the requirement.

When called with sort_by="my_column" and order_by="asc"

JavaScript

it looks great, but it raises:

JavaScript

The error is raised in the last line of the query method during query.all()

Traces

JavaScript
JavaScript

Advertisement

Answer

Google Cloud Spanner databases using the standard GoogleSQL dialect always sort NULL first when the sort order is ascending, and NULL last when the sort order is descending. The SQL dialect allows you to specify ASC NULLS FIRST and DESC NULLS LAST, as those correspond with the default, but not to actually change the sort order.

A workaround for this would be to use a COALESCE(my_column, <large-value>) expression in your ORDER BY clause. The feasibility of this workaround depends a little on the data type of the column that you are sorting. If it is for example an INT64 column, you could just use the max value for INT64. Be aware though that such a workaround can make your query less efficient, as the ORDER BY clause will not be able to use any index that you might have defined on the column.

Advertisement