0

In SQL Server Management Studio 2012, I run this query:

SELECT * FROM Contacts

This query successfully executes in approximately 44 seconds.

SELECT * FROM Contacts WHERE FirsttName = 'David"

This query successfully executes in approximately 0 seconds. So I guess my question is what is happening that causes these query times to be so different. From my admittedly naive perspective, I would think that in both cases all table rows would need to be surveyed to check if FirstName is equal to 'David', and that the condition should not have that large of an effect. In reality, I assumed that the query would take a little longer, because of the additional check.

Another example is:

SELECT * FROM Jobs

successfully executes in approximately 25 seconds.

SELECT * FROM Jobs WHERE JobName = "Sales"

successfully executes in approximately 0 seconds.

This is not a life-threatening/blocking/oh my god why can't I solve this problem issue. Just something that makes me wonder.

4

2 回答 2

2

这取决于很多因素。正如 Bobek 所提到的,经过时间的问题可能只是返回所有记录的时间。假设您只关注处理时间。

第一个问题是:您是否多次运行这些结果,并考虑到缓存效果?如果您运行第一个查询,表将被加载到内存中并保留在那里。对表的后续查询,包括第一次查询,第二次将会快得多。在计时时,你必须非常小心。

另一种可能性是索引的存在,尽管我怀疑FirstName. 索引大大减少了获取记录的时间。它只是去索引找到正确的记录,查找它们,然后返回结果。最后,您的查询必须获取页面上的数据,因为select *.

至于检查时间更长,这确实不是问题。处理一个页面的时间通常会比对记录的布尔运算要大得多。许多其他因素对性能的影响更大。

在您的情况下,我的猜测是您按照问题中的描述运行了查询,而性能差异是由于缓存效果造成的。

于 2013-06-21T20:36:03.073 回答
2

这是因为 where 语句过滤掉了您不想选择的行。这意味着如果您的 10000 行中只有一个具有 FirstName “David”,它只会拉出那一行而不是整个 10000。这有意义吗?

此外,该表使用索引和统计信息来快速搜索您要查找的数据,因此它很可能会比查看所有行更快地到达那里。

于 2013-06-21T20:29:27.643 回答