How to write this in less possible code?

Yes… You need to validate input in my code to avoid bad surprise :slight_smile:

I like @blatyo pattern matching solution, as it includes sanity check, but the main point is to separate order_by in direction/order, so that You need only one Ecto.Query command.