SqlServer - Ordering result set with null values after non-null values


Order by with null values in sql server is a tricky. Normally it puts the result set like: NULL, NULL, 1,2,3...etc

If your want the result set like: 1,2,3,NULL, NULL,......etc there is not direct method for this. You have to use the below script to get the required output.


declare @MaxId int
select @MaxId = max(code) + 1 FROM TableA

SELECT code
FROM TableA
ORDER by isnull(code, @MaxId)