Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT Ordering columns with Null Values

My question is similar to this one: How to display a table order by code (like 01, 02… then null columns)?, but for SQL Server.

In short, I have a SELECT statement, that returns the following:

ColumnA ColumnB
X       NULL
Y       1
Z       2

..where the ordering is done by ColumnB.

How can we force the (columnB = NULL) type of rows to the bottom? ie, the expected result is this:

ColumnA ColumnB
Y       1
Z       2
X       NULL

Thank you SOF community.

like image 308
FMFF Avatar asked Mar 30 '11 21:03

FMFF


People also ask

How do you handle NULL values in order?

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?

SELECT NULL is a hack to shut up the error while not enforcing any particular order. In this case we don't need to enforce any order, so the fastest option is to use SELECT NULL . The optimizer sees through this trick, so it has no runtime cost (this claim is easily verified by looking at the execution plan).

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

Ordering. When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL.


2 Answers

You can also use isnull:

select * from thetable order by isnull(columnb, 99999)

isnull will replace null with the value you provide to it, so in this case, if the column is null, it will replace it with 99999. You can set the value to some big number so it will be at the bottom of the order.

like image 69
Endy Tjahjono Avatar answered Nov 08 '22 11:11

Endy Tjahjono


...or in order to avoid value clashing...

SELECT 
   ColumnA, 
   ColumnB
FROM YourTable
ORDER BY 
   CASE WHEN ColumnB IS NULL THEN 1 ELSE 0 END ASC,
   ColumnB
like image 36
Dan Avatar answered Nov 08 '22 09:11

Dan