tags:

views:

34

answers:

4

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?

A: 
SELECT * 
FROM `People` 
ORDER BY case when `LastName` is null then 1 else 0 end, 
    `LastName`
RedFilter
+3  A: 
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... :)

Tom H.
The CASE statement is redundant. You can just use `LastName IS NULL` instead.
Hammerite
I don't believe that is ANSI compliant. While the question does say MySQL, and the abbreviated syntax may work in MySQL I'd rather type a few extra characters and remain ANSI compliant.
Tom H.
+1  A: 
  SELECT *, LastName IS NULL AS nullity 
    FROM `People` 
ORDER BY nullity ASC, `LastName` ASC
NullUserException
A: 

this should do it for you

select *, if(isnull(name), 1, 0) as is_name_null 
from names 
order by is_name_null asc, name asc
ovais.tariq