Blogroll

Search

SQL Order By with Nulls at the end.

April 27th, 2010 by Karl

I wanted to order a column alphabetically however NULLS show up first. I want the items will null, but i want them after the rest so i applied this like quick and dirty order by clause.

order by isnull(displayname,’zzzzzzz’)

it effectively puts nulls at the end. If you know a cleaner and just as pithy way I’d love to hear it.

Posted in SQL | 3 Comments »

3 Responses

  1. Eber Irigoyen Says:

    select…
    where … is not null
    order by…
    union all
    select …
    where … is null

  2. Jason Stangroome Says:

    order by
    case when displayname is null then 1 else 0 end,
    displayname
    – still works if displayname happens to begin with many Zs

  3. Tom Morris Says:

    Here’s what I’m using in a PostgreSQL-backed app:

    ORDER BY CASE WHEN whatever_column IS NULL THEN 1 ELSE 0 END, whatever_column

    Cleaner in the sense that if you have something called ‘Zzzzzzzzzzz’, it would sort properly.

    Not quite as pithy though.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.