When SQL Server is sorted, it encounters a null value.

Source: Internet
Author: User
This is a frequently asked question. Especially if the customer used Oracle before, when using SQL Server, there will be
The question is that SQL Server and Oracle behave differently in processing null values.
In Oracle, the null value is considered to be an infinite value.
This is a frequently asked question. Especially if the customer used Oracle before, then he is using SQL
When processing the null value, SQL Server and Oracle behave differently.

In Oracle, null values are considered to be infinite values. Therefore, if they are listed in ascending order, they are listed at the end.

In SQL Server, the opposite is true. null values are considered to be an infinitely small value. Therefore, if they are sorted in ascending order, they are ranked first.

For example

Select [ID]
From [demo]. [DBO]. [orders] Order by ID

The following results are displayed:

Is there any way to make the default mechanism of SQL Server the same as that of Oracle? The answer is: no

But we can try some workarounds, such as writing code like below.

Select [ID]

From [demo]. [DBO]. [orders] Order by case when ID is null then 1
Else 0 end

In this way, you can see the following results

If this column has an index, you can see the following execution plan

However, there is still another solution. You can set the default value of this column to a large value. That is to say, if you cannot provide the value of this column, by default, a large digital generation is used.
. If it is int type, the number can be 2147483647. In this case, it is not necessary to judge when sorting.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.