"SELECT TOP" 查询的意外 SQL 行为

Unexpected SQL Behaviour with "SELECT TOP" Query

我正在使用 Microsoft SQL Server 2019,当我执行时:

SELECT TOP 10 *
FROM  WideWorldImporters.Sales.Invoices

SELECT TOP 10 CustomerID
FROM  WideWorldImporters.Sales.Invoices

给出结果:

这是不正确的,因为它们不是第一个查询显示的 "top 10" 客户 ID。

完整截图:

编辑: 我上面预期的行为与 SQL Sever 2014 中实际发生的行为相符。我怀疑他们更改了 SQL Server 2019 中的底层实现,尽管它仍然满足记录的行为。

您没有 ORDER BY,因此将返回排序不确定的前 10 个结果。此顺序可以从一次执行更改为下一次执行。

SQL 中的表表示 无序 集合。如果您想要使用 TOP 的特定行,您需要有一个 ORDER BY.

评论太长了。

在 SQL 中,table 条记录是 无序的 。因此,像您这样的查询:

SELECT TOP 10 * FROM  WideWorldImporters.Sales.Invoices

... 会产生不一致的结果,因为它缺少 ORDER BY 子句。您需要告诉您的 RDBMS 应该使用哪一列来对记录进行排序,以便可以定义应该返回哪些 TOP 记录。例如,类似于:

SELECT TOP 10 * FROM  WideWorldImporters.Sales.Invoices ORDER BY InvoiceID DESC

没有ORDER BY 的TOP 是不可预测的。 Microsoft 对此进行了记录。来自 Microsoft docs:

When you use TOP with the ORDER BY clause, the result set is limited to the first N number of ordered rows. Otherwise, TOP returns the first N number of rows in an undefined order.

...

In a SELECT statement, always use an ORDER BY clause with the TOP clause. Because, it's the only way to predictably indicate which rows are affected by TOP.

另见 how does SELECT TOP works when no order by is specified?

这个结果完全正常,因为您的查询没有指定顺序。前 10 returns 前 10 个结果。

如果你不指定任何排序子句,结果将根据SQL引擎之前的操作返回,这可能并不总是相同的,而且肯定不是你期望的结果是。