Possible to use SQL to sort by date but put null dates at the back of the results set?

前端 未结 4 812
萌比男神i
萌比男神i 2021-01-31 01:53

I have a bunch of tasks in a MySQL database, and one of the fields is \"deadline date\". Not every task has to have to a deadline date.

I\'d like to use SQL to sort the

4条回答
  •  Happy的楠姐
    2021-01-31 02:16

    The easiest way is using the minus operator with DESC.

    SELECT * FROM request ORDER BY -date DESC

    In MySQL, NULL values are considered lower in order than any non-NULL value, so sorting in ascending (ASC) order NULLs are listed first, and if descending (DESC) they are listed last.

    When a - (minus) sign is added before the column name, NULL become -NULL.

    Since -NULL == NULL, adding DESC make all the rows sort by date in ascending order followed by NULLs at last.

提交回复
热议问题