1

I have to sort orders on my date field send_date, but NULL send_dates always on the end.

I have tried this, but this isn't working:

Order::orderBy(\DB::raw('ISNULL(send_date), send_date'), 'asc')
->orderBy('send_date', 'desc') 

How can I sort on send_date, with NULL dates always on the end?

Salman A
  • 262,204
  • 82
  • 430
  • 521
angelique000
  • 899
  • 3
  • 10
  • 28

3 Answers3

1

Just use the -minus sign beforet the Column name.

Order::orderByRaw("-start_date",'DESC'); 

It will order Sort the null values at the end.

Hope this helps.

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
1

You can do :

Order::orderBy(\DB::raw("COALESCE(d, '9999-12-31')", 'ASC');

This works because if the date is NULL it's considered to be 9999-12-31 which according to the docs is the largest possible date

Note: This only works if you sort ASC but if you sort DESC NULLs are at the end anyway.

Check the fiddle

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Sorry, it doesn't work, because when I filter DESC, the nullable dates have to be also on the end – angelique000 May 14 '18 at 08:00
  • If you sort by DESC the nulls go to the end anyway. – apokryfos May 14 '18 at 08:01
  • http://sqlfiddle.com/#!9/952214/9 the nullable doesn't go to the end... – angelique000 May 14 '18 at 08:03
  • There's no magic value that will send NULLs always at the end regardless of sort direction. You can use this code when sorting `ASC` and `orderBy(d, 'DESC')` when sorting by `DESC`. – apokryfos May 14 '18 at 08:06
  • http://sqlfiddle.com/#!9/952214/13 will work in both cases but as you can see it's ridiculously complicated and cannot be done using eloquent at all (it can be done using the query builder though) – apokryfos May 14 '18 at 08:11
  • Is it possible to create a new "order_column"; in mysql: if (send_date = null order_column = 1) ? – angelique000 May 14 '18 at 08:13
  • Here's the problem. If you `ORDER BY ... DESC` what you will get is **the reverse** of what you get if you `ORDER BY ... ASC` there's no magic value that always ends up in the bottom when doing both ASC and DESC ordering as far as I know. – apokryfos May 14 '18 at 08:17
0
Order::orderBy("start_date",'DESC');

i think it will help

Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26
  • No it doesn't work, because: sometimes I have to order my column on send_date asc, and sometimes send_date desc, but ALWAYS the nullable send_date have to be on the end... – angelique000 May 14 '18 at 07:53