2

我的查询运行缓慢。我正在评估我的索引并重建它们,但是有人可以告诉我 MyField 上的索引是否会在此查询中使用吗?

SELECT  ISNULL(MyField , 'No Data') 
FROM    MyTable

我的想法是:

  • 当 SQL 测试 IF、WHERE 或 CASE 中的字段时,它使用可用的索引。
  • MyField 将被测试。
  • 因此,SQL 应该可以使用索引来测试 MyField。

我的问题是:

  • 空值是否被索引?
  • 如果没有 IF、WHERE、CASE 等,SQL 是否使用索引?
  • 如果我使用 CASE rathar 而不是 ISNULL 会有所不同吗?

谢谢你。

斯科特

4

3 回答 3

3

仅供参考,如果您谈论的是“Where”子句,答案会有所不同。如果你这样做:

SELECT  ISNULL(MyField , 'No Data') 
FROM    MyTable
WHERE MyField ='myvalue'

SQL Server 将执行索引 SEEK(这是您应该始终追求的目标),但如果您这样做:

SELECT  ISNULL(MyField , 'No Data') 
FROM    MyTable
WHERE isNull(myColumn, 'no data') is not null  --I know this check doesn't make sense, but it's just for the sake of illustration. Imagine another function instead of isNull like substring or getdate...

sql server 将使用索引 SCAN

此外,如果 SQL Server 正在使用索引,您应该问自己它对索引执行的操作是查找还是扫描。

于 2012-02-10T09:55:49.713 回答
1

这是我对您的问题的想法:

<< 是否对空值进行了索引?

Null 值与其他值一样被索引。

<< 如果没有 IF、WHERE、CASE 等,SQL 是否使用索引?

实际上,是的,因为有些方法与 IF 或 CASE 语句具有相同的含义。

<< 如果我使用 CASE rathar 而不是 ISNULL 会有什么不同吗?

都是一样的,只是显示方式不同。

HTH。

于 2012-02-10T05:56:30.017 回答
1

是的,如果该字段上存在索引,则将使用索引。ISNULL 不相关。

您可以按如下方式自行测试(打开查询执行计划以查看它使用的索引:

BEGIN TRAN

--Create test table and add some dummy data
CREATE TABLE MyTable(MyField VARCHAR(20))
INSERT INTO MyTable SELECT 'test1'
INSERT INTO MyTable SELECT 'test2'
INSERT INTO MyTable SELECT NULL
INSERT INTO MyTable SELECT 'test3'

-- Run query with ISNULL (note that a Table Scan is done)
SELECT  ISNULL(MyField , 'No Data') FROM MyTable
-- Run query without ISNULL (note that a Table Scan is done)
SELECT  MyField FROM MyTable

-- Now create an index and compare the execution plans for the same queries
CREATE NONCLUSTERED INDEX IX_MyTable_MyField ON MyTable (MyField) 

-- Run query with ISNULL (note that an Index Scan is done)
SELECT  ISNULL(MyField , 'No Data') FROM MyTable
-- Run query without ISNULL (note that an Index Scan is done)
SELECT  MyField FROM MyTable

ROLLBACK

索引扫描比 Table 扫描快得多,因此创建索引后的查询会执行得更好。

于 2012-02-10T05:58:10.770 回答