Sort nulls last in fetch (order: descending)


#1

I am looking to make a fetch on some objects, sorted in descending order on some date field with nulls pushed to the bottom of the fetch result. If I call:

c3Grid(SomeType.fetch({
    order: "descending(someDateField)"
}))

Null values appear first, while

c3Grid(SomeType.fetch({
    order: "ascending(someDateField)"
}))

will do what I want. Is there a way to change this behavior so that null values are treated as the lowest value rather than the highest value in an ordered fetch result?


#2

something like this seems to work for me:

c3Grid(SomeType.fetch({
    order: "descending(exists(someDateField) ? someDateField : dateTime('1970-01-01'))"
}))

#3

Nailed it!

Happy cake day :slight_smile:


#4

A cleaner solution to this is to use the 2nd argument to the descending function:

SomeType.fetch({order: "descending(someDateField, true)"})

I can’t seem to find any real documentation on it, but its name would be something like sortNullsLast :slight_smile: