Reprinted from: https://www.cnblogs.com/Brambling/p/7046148.html
The reproduced content is as follows:
I recently encountered a SQL Server sorting problem, which I had never understood before, and then encountered it this time.
Only found the problem of SQL Server sorting, in the specified sorting column, the null value will be ranked first by default, because the null value defaults to the minimum value in SQL Server .
Later, I asked the almighty Baidu and found the following relatively simple processing method.
First create a table and insert some test data.
create table UserInfo( UserInfoID int not null identity(1,1) primary key, User_No int null, User_Names nvarchar(16) null ) insert into UserInfo(User_No,User_Names) select '104','name three' union all select '103','name two' union all select '108','name seven' union all select '105','name four' union all select '106','name five' union all select '102', 'name one' union all select '107','name six' union all select '109','name eight' insert into UserInfo(User_Names) select 'Name Nine' union all select 'name ten' select * from UserInfo
The results are as follows:
Let's sort them directly to see the effect.
select UserInfoID,User_No,User_Names from UserInfo order by User_NO asc
The result is as follows:
You can see that the columns with the specified sort order are listed first, and the ones whose value is null are listed first.
Here is the solution .
select UserInfoID,User_No,User_Names from UserInfo order by case when User_NO is null then 1 else 0 end asc,User_NO asc
The result is as follows:
The above is the solution. It is not only to put the value of the specified sorting column in the last row, but also to sort according to the value of the specified column. Is it very simple?