So here’s what the table looks like
--------
| field1 |
|========|
| 1.2 |
| 1.7 |
| - |
| - |
| 1.3 |
- the dashes are actually blank fields
My current SQL statement does a simple “ORDER BY field1” which puts the blank ones on top, however I want to get the numbers on top, and put the empty ones at the bottom.
EDIT:
My order by code looks like this:
'Get the sort requirement as per the requirement
strSql = strSql & " ORDER BY [RequestType], [Rank], [ADRNo]"
So i want it to order by requesttype, rank, and then ADRNo. But i want the null values to come last for all three fields. So I posted one field in my orignal question, but I am really working with 3.
Logic
The iif(field1 is null, 1, 0) constructs a virtual column with 1 for all null values. so you have
and then the sort of this virtual column takes care of putting the numbers below the nulls.
Multiple columns
If you have multiple columns that could have nulls you’d need an additional calculated column for each column. Something like
now you have 2 options.
1.you can sort each field with the null at the end. so...order by iif(field1 is null, 1, 0), field1, iif(field2 is null, 1, 0), field2would give you
note that in field2 there is a null (row 2) before 3 because the sort for field1 (2) overrides the null sort logic (s2) for field2. the second null (row 5) in field2 comes after 3 (row 5) because of our null specific sort logic for s2.
2.you can choose to have all nulls in field2 at the end, before sorting on field1. your code would then be…...order by iif(field1 is null, 1, 0), iif(field2 is null, 1, 0), field1, field2which gives you
Note
(Ref: Tom Gullen’s comment in question) This takes care of putting only nulls at the end (empty strings, or strings with spaces will still be in the natural sort order)
Options
So.. in your case you’d be using either
or