How the result set is sorted without the order by statement

We know that the order by clause in SQL is used to control the order of records in the returned result set. So when our sql does not provide an order by clause, what sort of records are returned. Cluster index? primary key? This was what I thought was the answer until I seriously googled the question.

The answer is that there is no order, and the results are not necessarily the same each time.

A dude on stackoverflow answered this question

https://stackoverflow.com/questions/20050341/when-no-order-by-is-specified-what-order-does-a-query-choose-for-your-record

To add to his own answer, he cites a post by Conor Cunningham, architect of the sql server core group. The general idea of ​​this post is this. Everyone thinks that the recordsets returned by SQL statements are in order. The usual reason is that for the same SQL, the database often uses the same query plan for querying, so the result returned each time looks like identical. But this is not fixed, and we cannot foresee what query plan the database will use. Conor Cunningham did an experiment on his own machine. A table has only one cluster index. Insert 20k data into the table, execute a select statement, and the database performs a scan on the cluster index. Insert another 20k data into the table, execute the same sql again, this time, the database executes a parallel query plan, multiple threads perform cluster index scan concurrently, and merge the records that meet the conditions, which results in the returned data The order of the sets is not fixed. From this simple example we have determined that without the order by clause, we should not expect the result set to be ordered.

Students who are interested in the details can read Conor Cunningham's original post

https://blogs.msdn.microsoft.com/conor_cunningham_msft/2008/08/27/no-seatbelt-expecting-order-without-order-by/

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326844046&siteId=291194637