Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to sort by column in ascending order, and show NULL at the end instead of the beginning?

Tags:

sql

mysql

I know how to sort a result set:

SELECT * FROM `People` ORDER BY `LastName` ASC

However, the results that have an empty LastName show at the beginning. How do I sort in ascending order, and show the NULL results at the end instead of the beginning?

like image 657
Andrew Avatar asked Aug 18 '10 16:08

Andrew


People also ask

How do I show the last NULL value in SQL?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

When data is sorted in descending order are NULL values listed first or last?

SQLite. In contrast to PostgreSQL and Oracle, SQLite treats NULLs as very small values and puts them first in an ascending sort and last in a descending sort. Starting with SQLite version 3.30. 0, this behavior can also be easily changed using the NULLS FIRST / NULLS LAST option.

How do you use NULLs last?

If the null ordering is not specified then the handling of the null values is: - NULLS LAST if the sort is ASC - NULLS FIRST if the sort is DESC - If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with ...


2 Answers

SELECT
    *
FROM
    People
ORDER BY
    CASE WHEN LastName IS NULL THEN 1 ELSE 0 END,
    LastName

You could also simply use

SELECT
    *
FROM
    People
ORDER BY
    COALESCE(LastName, 'ZZZZZ')

Technically, the second version would fail if a person actually had a LastName in your DB of "ZZZZZZ".

NOTE: I'm sure it's just because you're giving an example, but I hope you're not using SELECT * in actual production code... :)

like image 165
Tom H Avatar answered Sep 20 '22 04:09

Tom H


  SELECT *, LastName IS NULL AS nullity 
    FROM `People` 
ORDER BY nullity ASC, `LastName` ASC
like image 27
NullUserException Avatar answered Sep 19 '22 04:09

NullUserException