首页 > 开发 > 综合 > 正文

重建索引(rebuild index)与sort

2024-07-21 02:34:39
字体:
来源:转载
供稿:网友

  重建索引到底要不要排序?有人说要,因为创建索引时需要排序。有人说不要,因为重建索引的时候可以直接扫描旧的索引来重建成新的索引。让我们来看一下rebuild index到底需不需要排序。
  
  SQL> select name,statistic# from v$statname where name like '%sort%';
  
  NAME                               STATISTIC#
  ---------------------------------------------------------------- ----------
  sorts (memory)                          242
  sorts (disk)                           243
  sorts (rows)                           244
  
  看一下排序操作相关的 stat号
  
  再看一下rebuild index 的执行路径 SQL> eXPlain plan for alter index ind_test_id rebuild;
  
  Explained.
  
  SQL> @?/rdbms/admin/utlxpls
  
  PLAN_TABLE_OUTPUT
  -----------------------------------------------------------------------
   Id  Operation        Name     Rows  Bytes Cost 
  -----------------------------------------------------------------------
    0 ALTER INDEX STATEMENT         17837 71348   11
    1  INDEX BUILD NON UNIQUE IND_TEST_ID            
    2   SORT CREATE INDEX          17837 71348    
    3   INDEX FAST FULL SCAN IND_TEST_ID  17837 71348   11
  -----------------------------------------------------------------------
  执行下rebuild 看看
  
  SQL> select STATISTIC#,value from v$mystat where STATISTIC# in(242,243,244);
  STATISTIC#   VALUE
  ---------- ----------
      242    154
      243     0
      244    242
  
  
  SQL> alter index ind_test_id rebuild;
  
  Index altered.
  
  SQL> select STATISTIC#,value from v$mystat where STATISTIC# in(242,243,244);
  STATISTIC#   VALUE
  ---------- ----------
      242    155
      243     0
      244    242
  可以看出sort(memory)增加了一次
  
  为什么要排序呢?因为rebuild index的时候走的index ffs,而ffs搜索的顺序是根据 leaf block 的物理存储顺序相关而跟键值的逻辑顺序无关(在"index full scan vs fast index full scan"这篇文章中有具体介绍), 所以ffs的结果必须再做一次排序。
  
  此外在rebulid index online的时候走的是full table scan,这时候也是需要排序的,而且排序的次数会比较多, 在测试中发现每次做rebuild online产生4(10g中为13)次sort(memory),可能跟一些递规排序有关系。10g里面重建索引排序又有了一些改变,在10032事件的跟踪文件里面出现“Reopened sort”,目前暂时不知道是什么意思,希望有朋友能就这个问题进行探讨。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表