SQL Server NULL values and "Order By" order
I have a few tables that contain a column called "Order", which is used to sort by when retrieving the data. The purpose is to keep the data in a certain order when displayed to the end user.
| Black Linen | NULL |
| Navy Blue Linen | NULL |
| Dark Green Linen | NULL |
| Burgundy Linen | NULL |
| Ivory Vellum | NULL |
| Grey Felt | NULL |
| Natural Linen | NULL |
| White Coated Two Sides | 1 |
| White Cast Coated One Side | 2 |
| White SemiGloss Coated One Side | 3 |
| White Smooth | 4 |
| White Linen | 5 |
The problem is that SQL Server puts null values above non-null values when doing an "order by". To reverse this behavior, this was the most elegant and efficient solution that I found:
Select FooValue From foos Order by (Case When [Order] Is Null Then 1 Else 0 End), [Order]
I found information about the original problem here, and the solution was from Tim in the comments. Thanks!

Ska said,
Wrote on August 8, 2008 @ 10:43 am
Thanks a lot for this Jason.
Andra P žurnāls - web izstrāde, pārlūku jaunumi, pamācības, programmas » SQL kārtošana un NULL vērtības said,
Wrote on October 14, 2008 @ 11:43 am
[...] Risinājuma oriģināls. [...]
Gints said,
Wrote on October 15, 2008 @ 8:25 am
SQL standard has NULLS FIRST / NULLS LAST syntax for that. Hopefully next version of SQL Server will implement that