knex icon indicating copy to clipboard operation
knex copied to clipboard

orderBy nulls argument not correctly applied

Open rockrepIGN opened this issue 2 years ago • 1 comments

Environment

Knex version: 1.0.7 Database + version: Postgres 12.7 OS: OS X, RDS

Bug

  1. Explain what kind of behaviour you are getting and how you think it should do

From the docs:

orderBy — .orderBy(column|columns, [direction], [nulls])
Adds an order by clause to the query. column can be string, or list mixed with string and object. nulls specify where the nulls values are put (can be 'first' or 'last').

Problem: Using .orderBy('score', 'desc', 'first') or .orderBy('score', 'desc', 'last') does not perform the query the same way as .orderByRaw('score desc nulls first') or .orderByRaw('score desc nulls last). Different results are obtained by the former than the later.

e.g. select * from table order by (score is null) desc is not equivalent to select * from table order by score desc nulls last

The later, orderByRaw, provides the correct behavior for my use-case.

rockrepIGN avatar Apr 20 '22 22:04 rockrepIGN

Hey @rockrepIGN! I also recently came across this bug, agree that is would be great to get fixed. A workaround I currently do it you can chain two ORDER BY commands to get what you want. Example:

// This produces: ORDER BY (score IS NULL) DESC, score DESC
// which will do descending order of score with nulls at the beginning
.orderBy('score', 'desc', 'first').orderBy('score', 'desc')

code-ape avatar Jun 20 '22 23:06 code-ape