调优基本(优化手段之一:索引,其目的是减少logical reads的次数):

SQL Server Profiler 追踪,观察 CPU 、Duration ,快速定位慢查询。

显示实际执行计划,观察 Estimated Number of Rows,

SET STATISTICS IO ON,观察 Scan count #, logical reads #(可利用非聚集索引过滤等), physical reads #。

还有 set statistics profile on,从下往上读。

快速定位影响性能图标,可根据执行计划视图:左边箭头较粗的和下面百分比率较大的图标,

避免 Table Scan(无聚集索引)、Index Scan、

Bookmark Lookup(由于索引列无包含查找字段或条件字段,可建立包含或复合非聚集索引,或利用非聚集索引的交叉和连接)、

Filter(SQL中使用函数)、Sort(SQL中使用Order by)。

SQL Server 基础

 Estmated Data Size = (Estmated Number of Rows * Estmated Row Size) /(1024*1024) M(单位)

 

select productname,count(projectnumber) from project where id>100 group by productname having len(productname)>5 order by productname

 

上面SQL查询语句,将按以下顺序执行

  1. from project
  2. on (这里没有用,对联接有效)
  3. 外部行(这里没有用,对外联接有效)
  4. where id>100
  5. group by productname
  6. having len(productname)>5
  7. select productname,count(projectnumber), 如 select 里面有以下三个,则按下面顺序执行
    1. OVER
    2. DISTINCT
    3. TOP
  8. order by productname //select ... 中的列别名只能在这起作用

而执行计划根据执行顺序由右至左,从上到下输出图标:

SQL SERVER EXPRESS 2005,不按上面顺序执行的

SQL Server 基础

SQL SERVER EXPRESS 2008 R2

SQL Server 基础

order...select         having                   len .......  convert ....... count                group by                          where ... from

 

  9. Table Scan( 在小表数据中较优于索引) / Index Seek or Scan / Clustered Index Seek or Scan:

    Estimated Number of Rows 的值大,Scan 优于 Seek,反之 Seek 优于 Scan

  10. Bookmarks Lookup: 分 Key Lookup (有聚集索引) 和 RID Lookup(无聚集索引,即堆表),其中 select * 容易导致发生 Bookmark Lookup,从而增加逻辑读次数。

  11. 非聚集索引的最大键列数为16,索引键最大大小为900字节,但其中Include里的非键索引列,列数则可以为1023。

  12. select a,b from tb where c=1 and d=2,通常这样建立非聚集索引: CREATE NONCLUSTERED INDEX IX_CD_INC_AB ON dbo.tb(c,d) INCLUDE(a,b)

  13. 发生RID Lookup 时,则该表需要建立聚集索引。

  14. 要注意的是随数据量的变化,同一SQL语句的执行计划可能会不一样的,前提是有索引供选择。

  15. 8K - one page; 1M - 128 pages; one extent - 8 pages; 1M - 16 extents

    一个表有多少页:如 表大小为 2M, 则 (2*1024*1024)/8000(估计值) = 262 pages,one page 可储存 8000 字节。

    SQL Server 基础

  16. 索引碎片,可以通过sys.dm_db_index_physical_stats查看,用 ALTER INDEX ALL on Tablename REBUILD 或 ALTER INDEX ALL on Tablename REORGANIZE 整理,

    而 REORGANIZE 只能在online模式,但 REBUILD 可以选择 online 或 offline。

  17. DDL语句(数据定义语言):create tabel drop table alert table ... ; DML语句(数据操作语言):insert into update delete ...

  18. 如果仅用复合聚集索引的非起始列作为查询条件的话,这个索引是不起任何作用的。

 

相关文章:

  • 2022-12-23
  • 2022-02-04
  • 2022-01-30
  • 2021-11-28
  • 2021-12-10
  • 2021-08-10
  • 2021-09-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2021-11-28
  • 2021-05-03
相关资源
相似解决方案