Skip to content

How to use ifnull or coalesce in order by? #4137

Answered by weiznich
g-fb asked this question in Q&A
Discussion options

You must be logged in to vote

There are several answers to the question depending on the database system you are using and how you want to solve the actual problem.

For postgres diesel offers functions for the NULLS FIRST/LAST sorting options: https://docs.diesel.rs/2.2.x/diesel/expression_methods/trait.PgSortExpressionMethods.html#method.nulls_last. That would neatly solve your problem.

Other backends do not support the same syntax, but you can solve this by using ifnull or coalesce as you already mentioned.
Diesel does not provide out of the box support for these functions, but you can easily define your own version of them via the define_sql_function! macro. After that you can just use these functions in your order…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@g-fb
Comment options

Answer selected by g-fb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants