Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005: Order with NULL values at the end [duplicate]

Possible Duplicate:
Case Order by using Null

I'm looking to get a list of records ordered by an "ordernum" field. The ordernum field is an int field. This field starts as NULL until set by a user. I would like the NULL entries to appear at the end of the list.

I am building a query as follows:

select *, case when (ordernum is null) then [largestInt] else ordernum end as newordernum
from tableName
order by newordernum

I know I could enter the value for the largest possible int for [largestInt], but I would like to replace [largestInt] with a variable. Is this possible?

like image 802
dangowans Avatar asked Jul 04 '12 18:07

dangowans


People also ask

How do I sort the last NULL in SQL Server?

If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.

What happens to NULL in ORDER BY?

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.

What is ORDER BY select NULL?

SQL ORDER BY Clause Handling NULLS This means that if you specify a column in the ORDER BY clause that has null values in ascending order the NULL values will appear first in the result set. Conversely, if you specify descending order, they will appear last in the result set.

What is ORDER BY 0 in SQL?

The order statement generates a 'virtual field' that contains NULL or 0 based on the case condition. The ORDER BY is applied based on that virtual field. The zero value in the order by precedes the NULL value. That's all, it's a way to set NULLs of the field1 at the end of the order list.


1 Answers

I found a way to order NULL values on the bottom.

http://sqlblog.com/blogs/denis_gobo/archive/2007/10/19/3048.aspx

It meets my needs quite nicely. My query is now:

select *
from tableName
order by case when ordernum is null then 1 else 0 end, ordernum
like image 102
dangowans Avatar answered Oct 20 '22 16:10

dangowans