简体   繁体   中英

"SELECT column_name FROM table_name" unexpected result

I'm using the sample AdventureWorksLT database on Azure SQLdb. I get the following result when I query SELECT * FROM [SalesLT].[Customer] , which is expected.

在此处输入图片说明

But when I query SELECT CustomerID FROM [SalesLT].[Customer] , or SELECT TOP 7 CustomerID FROM [SalesLT].[Customer] , I was expecting the CustomerID column results to be already in a sorted way just like in the first screenshot, But instead I get this unexpected unsorted result like below.

在此处输入图片说明

What is the reason behind this unexpected behaviour?

There is no unexpected behavior.

SQL tables represent unordered sets. A result set is unordered , unless you explicitly have an ORDER BY in the outermost query.

Add an ORDER BY to get the results you want:

SELECT TOP 7 CustomerID
FROM [SalesLT].[Customer]
ORDER BY CustomerID;

If you do not have an ORDER BY and the results happen to look like they are ordered, that is just a coincidence. If you want to guarantee the ordering, you need ORDER BY .

If there's unexpected behavior it's because of the false assumption there is an underlying physical ordering of the rows. There isn't one. SQL is an interpreted language. When a SELECT statement is executed without ORDER BY the interpreter decides which rows to return. Many times the rows are returned in the desired order but it cannot be relied upon because the interpreter makes NO GUARANTEES about the row ordering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM