SQL Server中LIKE %search_string% 走索引查找(Index Seek)浅析

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介: 原文:SQL Server中LIKE %search_string% 走索引查找(Index Seek)浅析  在SQL Server的SQL优化过程中,如果遇到WHERE条件中包含LIKE '%search_string%'是一件非常头痛的事情。
原文: SQL Server中LIKE %search_string% 走索引查找(Index Seek)浅析

 

在SQL Server的SQL优化过程中,如果遇到WHERE条件中包含LIKE '%search_string%'是一件非常头痛的事情。这种情况下,一般要修改业务逻辑或改写SQL才能解决SQL执行计划走索引扫描或全表扫描的问题。最近在优化SQL语句的时候,遇到了一个很有意思的问题。某些使用LIKE '%' + @search_string + '%'(或者 LIKE @search_string)这样写法的SQL语句的执行计划居然走索引查找(Index Seek)。下面这篇文章来分析一下这个奇怪的现象。

 

首先,我们来看看WHERE查询条件中使用LIKE的几种情况,这些是我们对LIKE的一些常规认识:

 

1: LIKE 'condition%'

   

    执行计划会走索引查找(Index Seek or Clustered Index Seek)。

   

2:  LIKE '%condition'

 

    执行计划会走索引扫描(Index Scan or Clustered Index Scan)或全表扫描(Table Scan)

 

3:  LIKE '%condition%'

   

    执行计划会走索引扫描(Index Scan or Clustered Index Scan)或全表扫描(Table Scan)

 

4: LIKE 'condition1%condition%';

 

    执行计划会走索引查找(Index Seek)

 

下面我们以AdventureWorks2014示例数据库为测试环境(测试环境为SQL Server 2014 SP2),测试上面四种情况,如下所示:

 

clip_image001

 

 

clip_image002

 

 

clip_image003

 

clip_image004

 

 

其实复杂的情况下,LIKE 'search_string%'也有走索引扫描(Index Scan)的情况,上面情况并不是唯一、绝对的。如下所示

 

在表Person.Person的 rowguid字段上创建有唯一索引AK_Person_rowguid

 

 

clip_image005

 

 

那么我们来看看上面所说的这个特殊案例(这里使用一个现成的案例,懒得构造案例了),如何让LIKE %search_string%走索引查找(Index Seek),这个技巧就是使用变量,如下SQL对比所示:

 

如下所示,表[dbo].[GEN_CUSTOMER]在字段CUSTOMER_CD有聚集索引。

 

 

clip_image006

 

 

可以看到CUSTOMER_CD LIKE '%' + @CUSTOMER_CD + '%'这样的SQL写法(或者CUSTOMER_CD LIKE @CUSTOMER_CD也可以), 执行计划就走聚集索引查找(Clustered Index Seek)了, 而条件中直接使用CUSTOMER_CD LIKE '%00630%' 反而走聚集索引扫描(Clustered Index Scan),另外可以看到实际执行的Cost开销比为4% VS 96% ,初一看,还真的以为第一个执行计划比第二个执行的代价要小很多。但是从IO开销,以及CPU time、elapsed time对比来看,两者几乎没有什么差异。在这个案例中,并不是走索引查找(Index Seek)就真的开销代价小很多。

 

 

clip_image007

 

 

考虑到这里数据量较小,我使用网上的一个脚本,在AdventureWorks2014数据库构造了一个10000000的大表,然后顺便做了一些测试对比

 

CREATE TABLE dbo.TestLIKESearches
(
     ID1         INT
    ,ID2         INT
    ,AString     VARCHAR(100)
    ,Value       INT
    ,PRIMARY KEY (ID1, ID2)
);
 
WITH Tally (n) AS
(
SELECT TOP 10000000 ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM sys.all_columns a CROSS JOIN sys.all_columns b
)
INSERT INTO dbo.TestLIKESearches
    (ID1, ID2, AString, Value)
SELECT 1+n/500, n%500
    ,CASE WHEN n%500 > 299 THEN
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1) +
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1) +
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1) +
            RIGHT(1000+n%1000, 3) +
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1) +
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1) +
            SUBSTRING('abcdefghijklmnopqrstuvwxyz', 1+ABS(CHECKSUM(NEWID()))%26, 1)
          END
    ,1+ABS(CHECKSUM(NEWID()))%100
FROM Tally;
 
 
CREATE INDEX IX_TestLIKESearches_N1 ON dbo.TestLIKESearches(AString);

 

如下测试所示,在一个大表上面,LIKE @search_string这种SQL写法,IO开销确实要小一些,CPU Time也要小一些。个人多次测试都是这种结果。也就是说对于数据量较大的表,这种SQL写法性能确实要好一些。

 

clip_image008

 

clip_image009

 

 

现在回到最开始那个SQL语句,个人对执行计划有些疑惑,查看执行计划,你会看到优化器对CUSTOMER_CD LIKE '%' + @CUSTOMER_CD + '%' 进行了转换。如下截图或通过执行计划的XML,你会发现上面转换为使用三个内部函数LikeRangeStart, LikeRangeEnd,  LikeRangeInfo.

 

clip_image010

 

<OutputList>
                    <ColumnReference Column="Expr1007" />
                    <ColumnReference Column="Expr1008" />
                    <ColumnReference Column="Expr1009" />
                  </OutputList>
                  <ComputeScalar>
                    <DefinedValues>
                      <DefinedValue>
                        <ColumnReference Column="Expr1007" />
                        <ScalarOperator ScalarString="LikeRangeStart((N'%'+[@CUSTOMER_CD])+N'%')">
                          <Identifier>
                            <ColumnReference Column="ConstExpr1004">
                              <ScalarOperator>
                                <Intrinsic FunctionName="LikeRangeStart">
                                  <ScalarOperator>
                                    <Arithmetic Operation="ADD">
                                      <ScalarOperator>
                                        <Arithmetic Operation="ADD">
                                          <ScalarOperator>
                                            <Const ConstValue="N'%'" />
                                          </ScalarOperator>
                                          <ScalarOperator>
                                            <Identifier>
                                              <ColumnReference Column="@CUSTOMER_CD" />
                                            </Identifier>
                                          </ScalarOperator>
                                        </Arithmetic>
                                      </ScalarOperator>
                                      <ScalarOperator>
                                        <Const ConstValue="N'%'" />
                                      </ScalarOperator>
                                    </Arithmetic>
                                  </ScalarOperator>
                                  <ScalarOperator>
                                    <Const ConstValue="" />
                                  </ScalarOperator>
                                </Intrinsic>
                              </ScalarOperator>
                            </ColumnReference>
                          </Identifier>
                        </ScalarOperator>
                      </DefinedValue>
                      <DefinedValue>
                        <ColumnReference Column="Expr1008" />
                        <ScalarOperator ScalarString="LikeRangeEnd((N'%'+[@CUSTOMER_CD])+N'%')">
                          <Identifier>
                            <ColumnReference Column="ConstExpr1005">
                              <ScalarOperator>
                                <Intrinsic FunctionName="LikeRangeEnd">
                                  <ScalarOperator>
                                    <Arithmetic Operation="ADD">
                                      <ScalarOperator>
                                        <Arithmetic Operation="ADD">
                                          <ScalarOperator>
                                            <Const ConstValue="N'%'" />
                                          </ScalarOperator>
                                          <ScalarOperator>
                                            <Identifier>
                                              <ColumnReference Column="@CUSTOMER_CD" />
                                            </Identifier>
                                          </ScalarOperator>
                                        </Arithmetic>
                                      </ScalarOperator>
                                      <ScalarOperator>
                                        <Const ConstValue="N'%'" />
                                      </ScalarOperator>
                                    </Arithmetic>
                                  </ScalarOperator>
                                  <ScalarOperator>
                                    <Const ConstValue="" />
                                  </ScalarOperator>
                                </Intrinsic>
                              </ScalarOperator>
                            </ColumnReference>
                          </Identifier>
                        </ScalarOperator>
                      </DefinedValue>
                      <DefinedValue>
                        <ColumnReference Column="Expr1009" />
                        <ScalarOperator ScalarString="LikeRangeInfo((N'%'+[@CUSTOMER_CD])+N'%')">
                          <Identifier>
                            <ColumnReference Column="ConstExpr1006">
                              <ScalarOperator>
                                <Intrinsic FunctionName="LikeRangeInfo">
                                  <ScalarOperator>
                                    <Arithmetic Operation="ADD">
                                      <ScalarOperator>
                                        <Arithmetic Operation="ADD">
                                          <ScalarOperator>
                                            <Const ConstValue="N'%'" />
                                          </ScalarOperator>
                                          <ScalarOperator>
                                            <Identifier>
                                              <ColumnReference Column="@CUSTOMER_CD" />
                                            </Identifier>
                                          </ScalarOperator>
                                        </Arithmetic>
                                      </ScalarOperator>
                                      <ScalarOperator>
                                        <Const ConstValue="N'%'" />
                                      </ScalarOperator>
                                    </Arithmetic>
                                  </ScalarOperator>
                                  <ScalarOperator>
                                    <Const ConstValue="" />
                                  </ScalarOperator>
                                </Intrinsic>
                              </ScalarOperator>
                            </ColumnReference>
                          </Identifier>
                        </ScalarOperator>
                      </DefinedValue>
                    </DefinedValues>

 

 

另外,你会发现Nested Loops & Compute Scalar 等步骤的Cost都为0.后面在Dynamic Seeks and Hidden Implicit Conversions这篇博客里面看到了一个新名词Dynamic Seeks。文字提到因为成本估算为0,所以,你看到的执行计划的Cost又是不准确的,具体描述如下:

 

The plan now contains an extra Constant Scan,  a Compute Scalar and a Nested Loops Join.  These operators are interesting because they have zero cost estimates: no CPU, no I/O, nothing.  That’s because they are purely architectural: a workaround for the fact that SQL Server cannot currently perform a dynamic seek within the Index Seek operator itself.  To avoid affecting plan choices, this extra machinery is costed at zero.

The Constant Scan produces a single in-memory row with no columns.  The Compute Scalar defines expressions to describe the covering seek range (using the runtime value of the @Like variable).  Finally, the Nested Loops Join drives the seek using the computed range information as correlated values.

The upper tooltip shows that the Compute Scalar uses three internal functions, LikeRangeStart, LikeRangeEnd, and LikeRangeInfo.  The first two functions describe the range as an open interval.  The third function returns a set of flags encoded in an integer, that are used internally to define certain seek properties for the Storage Engine.  The lower tooltip shows the seek on the open interval described by the result of LikeRangeStart and LikeRangeEnd, and the application of the residual predicate ‘LIKE @Like’.

 

 

 不管你返回的记录有多少,执行计划Nested Loops & Compute Scalar 等步骤的Cost都为0,如下测试所示,返回1000条记录,它的成本估算依然为0 ,显然这样是不够精确的。深层次的原因就不太清楚了。执行计划Cost不可靠的案例很多。

 

SET STATISTICS IO ON;
 
SET STATISTICS TIME ON;
 
DECLARE @CUSTOMER_CD NVARCHAR(10);
 
SET @CUSTOMER_CD=N'%44%'
 
 
 
SELECT * FROM  [dbo].[GEN_CUSTOMER] WHERE CUSTOMER_CD LIKE @CUSTOMER_CD

 

 

 

另外,其实还一点没有搞清楚的时候在什么条件下出现Index Seek的情况。有些情况下,使用变量的方式,依然是索引扫描

 

 

clip_image011

 

 

不过我在测试过程,发现有一个原因是书签查找(Bookmark Lookup:键查找(Key Lookup)或RID查找 (RID Lookup))开销过大会导致索引扫描。如下测试对比所示:

 

CREATE NONCLUSTERED INDEX [IX_xriteWhite_N1] ON.[dbo].[xriteWhite] ([Item_NO]) INCLUDE ([Iden],[WI_CE],[CIE],[Operate_Time])

 

 

clip_image012

 

 

 

 

 

 

参考资料:

 

http://sqlblog.com/blogs/paul_white/archive/2012/01/18/dynamic-seeks-and-hidden-implicit-conversions.aspx

https://blogs.msdn.microsoft.com/varund/2009/11/30/index-usage-by-like-operator-query-tuning/

https://sqlperformance.com/2017/02/sql-indexes/seek-leading-wildcard-sql-server

https://stackoverflow.com/questions/1388059/sql-server-index-columns-used-in-like

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
11天前
|
SQL
启动mysq异常The server quit without updating PID file [FAILED]sql/data/***.pi根本解决方案
启动mysq异常The server quit without updating PID file [FAILED]sql/data/***.pi根本解决方案
15 0
|
1天前
|
SQL 算法 数据库
【SQL server】玩转SQL server数据库:第三章 关系数据库标准语言SQL(二)数据查询
【SQL server】玩转SQL server数据库:第三章 关系数据库标准语言SQL(二)数据查询
26 6
|
1天前
|
SQL 人工智能 算法
【SQL server】玩转SQL server数据库:第二章 关系数据库
【SQL server】玩转SQL server数据库:第二章 关系数据库
31 10
|
1天前
|
SQL 存储 数据挖掘
数据库数据恢复—RAID5上层Sql Server数据库数据恢复案例
服务器数据恢复环境: 一台安装windows server操作系统的服务器。一组由8块硬盘组建的RAID5,划分LUN供这台服务器使用。 在windows服务器内装有SqlServer数据库。存储空间LUN划分了两个逻辑分区。 服务器故障&初检: 由于未知原因,Sql Server数据库文件丢失,丢失数据涉及到3个库,表的数量有3000左右。数据库文件丢失原因还没有查清楚,也不能确定数据存储位置。 数据库文件丢失后服务器仍处于开机状态,所幸没有大量数据写入。 将raid5中所有磁盘编号后取出,经过硬件工程师检测,没有发现明显的硬件故障。以只读方式将所有磁盘进行扇区级的全盘镜像,镜像完成后将所
数据库数据恢复—RAID5上层Sql Server数据库数据恢复案例
|
5天前
|
SQL 安全 Java
SQL server 2017安装教程
SQL server 2017安装教程
12 1
|
18天前
|
SQL 存储 Python
Microsoft SQL Server 编写汉字转拼音函数
Microsoft SQL Server 编写汉字转拼音函数
|
29天前
|
SQL 存储 数据库
数据安全无忧,SQL Server 2014数据库定时备份解密
数据安全无忧,SQL Server 2014数据库定时备份解密
|
29天前
|
SQL 数据库 数据安全/隐私保护
Sql Server数据库Sa密码如何修改
Sql Server数据库Sa密码如何修改
|
2月前
|
SQL 算法 数据库
【数据库SQL server】关系数据库标准语言SQL之数据查询
【数据库SQL server】关系数据库标准语言SQL之数据查询
94 0
|
2月前
|
SQL 算法 数据库
【数据库SQL server】关系数据库标准语言SQL之视图
【数据库SQL server】关系数据库标准语言SQL之视图
72 0