Is Order by sorted by a primary key not specified in SQL? sqlorder

Source: Internet
Author: User

Is Order by sorted by a primary key not specified in SQL? sqlorder

If Order by is not specified in SQL, is the sorting based on the primary key? The answer is not necessarily. For example:

Queries the AttendanceEmpRank table. The primary key is the AttendanceEmployeeRankId and the primary key is the clustered index.

Execute the following statement and find that the result of not specifying Order by in the first sentence is different from that in the second sentence.

Let's look at the execution plan. We can know that the first sentence uses the Date index, and the second sentence uses the primary key index.

Let's look at another set of SQL statements and query results:

The indexes used in the execution plan are also different:

Therefore, it is concluded that if Order by is not specified, sqlserver will obtain data based on the actual query method of the Execution Plan, and the execution plan will be based on many factors in the SQL (query column, where condition, order by, etc.) and use different indexes, the final results may be different.


If SQL server does not use the order by clause, what sort of results are returned by the query?

If the order by clause is not specified, the query results are in an uncertain order. It must be based on the primary key. The query optimizer generates an execution plan based on the actual situation. Sorting costs a lot, and the cost may not be small. If the order by clause is not explicitly specified, the query results are in an uncertain order.
If you want to return results in a certain order, you must specify the order by clause.

Is the data obtained by SQL statement select sorted by the primary key id by default?

This has nothing to do with your primary key. If it is a heap organization table, the sorting is only for the primary key index, and the primary key is not sorted in the data table, the data sequence depends on the block in which your data is stored.

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.