[20181130]hash冲突导致查询缓慢.txt

[20181130]hash冲突导致查询缓慢.txt

--//昨天看了链接https://jonathanlewis.wordpress.com/2018/11/26/shrink-space-2/,演示了Shrink Space导致
--//执行语句缓慢的情况,我自己重复测试,实际上这样发生的概率还是很低的,我个人认为,至于Shrink Space是否好坏,
--//我个人还是根据实际的情况来确定.

1.环境:
SCOTT@book> @ ver1

PORT_STRING                    VERSION        BANNER
------------------------------ -------------- --------------------------------------------------------------------------------
x86_64/Linux 2.4.xx            11.2.0.4.0     Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production

SCOTT@book> rename  emp to empxxx;
Table renamed.

--//作者测试的表名与scoot用户下冲突,我先修改原系统的表名.

2.建立测试脚本:
create table emp(
        dept_no         not null,
        sal,
        emp_no          not null,
        padding,
        constraint e_pk primary key(emp_no)
)
as
with generator as (
        select  null
        from    dual
        connect by
                level <= 1e4 -- > comment to avoid wordpress format issue
)
select
        mod(rownum,6),
        rownum,
        rownum,
        rpad('x',60)
from
        generator       v1,
        generator       v2
where
        rownum <= 2e4 -- > comment to avoid wordpress format issue
;
 
 
insert into emp values(432, 20001, 20001, rpad('x',60));
delete /*+ full(emp) */ from emp where emp_no <= 1000;      -- > comment to avoid wordpress format issue
--//注:执行时要删除后面的注解.不然报错.作者应该把分号放在最后才能正常执行ok.
commit;
 
begin
        dbms_stats.gather_table_stats(
                ownname          => user,
                tabname          => 'EMP',
                method_opt       => 'for all columns size 1'
        );
end;
/

3.测试:
SCOTT@book> alter session set statistics_level = all;
Session altered.

select
        /*+ gather_plan_statistics pre-shrink */
        count(*)
from    (
        select  /*+ no_merge */
                outer.*
        from
                emp outer
        where
                outer.sal > (
                        select  /*+ no_unnest */
                                avg(inner.sal)
                        from
                                emp inner
                        where
                                inner.dept_no = outer.dept_no
                )
        )
;


  COUNT(*)
----------
      9998

SCOTT@book> @ dpc '' ''
PLAN_TABLE_OUTPUT
-------------------------------------
SQL_ID  9bkx1f5cpcv14, child number 1
-------------------------------------
select         /*+ gather_plan_statistics pre-shrink */
count(*) from    (         select  /*+ no_merge */
outer.*         from                 emp outer         where
     outer.sal > (                         select  /*+ no_unnest */
                            avg(inner.sal)                         from
                                emp inner                         where
                                inner.dept_no = outer.dept_no
      )         )

Plan hash value: 322796046

------------------------------------------------------------------------------------------------------------------------
| Id  | Operation             | Name | Starts | E-Rows |E-Bytes| Cost (%CPU)| E-Time   | A-Rows |   A-Time   | Buffers |
------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |      |      1 |        |       |   569 (100)|          |      1 |00:00:00.04 |    1912 |
|   1 |  SORT AGGREGATE       |      |      1 |      1 |       |            |          |      1 |00:00:00.04 |    1912 |
|   2 |   VIEW                |      |      1 |    143 |       |   569   (1)| 00:00:07 |   9998 |00:00:00.04 |    1912 |
|*  3 |    FILTER             |      |      1 |        |       |            |          |   9998 |00:00:00.03 |    1912 |
|   4 |     TABLE ACCESS FULL | EMP  |      1 |  20001 |   156K|    71   (0)| 00:00:01 |  20001 |00:00:00.01 |     239 |
|   5 |     SORT AGGREGATE    |      |      7 |      1 |     8 |            |          |      7 |00:00:00.02 |    1673 |
|*  6 |      TABLE ACCESS FULL| EMP  |      7 |   2857 | 22856 |    71   (0)| 00:00:01 |  20001 |00:00:00.01 |    1673 |
------------------------------------------------------------------------------------------------------------------------

Query Block Name / Object Alias (identified by operation id):
-------------------------------------------------------------

   1 - SEL$1
   2 - SEL$2 / from$_subquery$_001@SEL$1
   3 - SEL$2
   4 - SEL$2 / OUTER@SEL$2
   5 - SEL$3
   6 - SEL$3 / INNER@SEL$3

Predicate Information (identified by operation id):
---------------------------------------------------

   3 - filter("OUTER"."SAL">)
   6 - filter("INNER"."DEPT_NO"=:B1)

--//你可以发现内层循环扫描emp表7次.因为有7个部门.也就是oracle缓存了执行过.虽然最后1个记录是dept_no=432存在冲突,仅仅1条,
--//影响不大.

4.测试Shrink Space后:
SCOTT@book> alter table emp enable row movement;
Table altered.

SCOTT@book> alter table emp shrink space compact;
Table altered.

SCOTT@book> select * from emp where rownum<=4;
   DEPT_NO        SAL     EMP_NO PADDING
---------- ---------- ---------- ---------
       432      20001      20001 x
         4      19978      19978 x
         5      19979      19979 x
         0      19980      19980 x

--//这样dept_no=432被移动到前面.

select
        /*+ gather_plan_statistics post-shrink  */
        count(*)
from    (
        select  /*+ no_merge */
                outer.*
        from emp outer
        where outer.sal >
                (
                        select /*+ no_unnest */ avg(inner.sal)
                        from emp inner
                        where inner.dept_no = outer.dept_no
                )
        )
;

  COUNT(*)
----------
      9498

SCOTT@book> @ dpc '' ''
PLAN_TABLE_OUTPUT
-------------------------------------
SQL_ID  gx7xb7rhfd2zf, child number 0
-------------------------------------
select         /*+ gather_plan_statistics post-shrink  */
count(*) from    (         select  /*+ no_merge */
outer.*         from emp outer         where outer.sal >
 (                         select /*+ no_unnest */ avg(inner.sal)
                  from emp inner                         where
inner.dept_no = outer.dept_no                 )         )

Plan hash value: 322796046

------------------------------------------------------------------------------------------------------------------------
| Id  | Operation             | Name | Starts | E-Rows |E-Bytes| Cost (%CPU)| E-Time   | A-Rows |   A-Time   | Buffers |
------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |      |      1 |        |       |   569 (100)|          |      1 |00:00:03.43 |     783K|
|   1 |  SORT AGGREGATE       |      |      1 |      1 |       |            |          |      1 |00:00:03.43 |     783K|
|   2 |   VIEW                |      |      1 |    143 |       |   569   (1)| 00:00:07 |   9498 |00:00:03.43 |     783K|
|*  3 |    FILTER             |      |      1 |        |       |            |          |   9498 |00:00:03.43 |     783K|
|   4 |     TABLE ACCESS FULL | EMP  |      1 |  20001 |   156K|    71   (0)| 00:00:01 |  19001 |00:00:00.01 |     247 |
|   5 |     SORT AGGREGATE    |      |   3172 |      1 |     8 |            |          |   3172 |00:00:03.42 |     783K|
|*  6 |      TABLE ACCESS FULL| EMP  |   3172 |   2857 | 22856 |    71   (0)| 00:00:01 |     10M|00:00:02.71 |     783K|
------------------------------------------------------------------------------------------------------------------------

Query Block Name / Object Alias (identified by operation id):
-------------------------------------------------------------

   1 - SEL$1
   2 - SEL$2 / from$_subquery$_001@SEL$1
   3 - SEL$2
   4 - SEL$2 / OUTER@SEL$2
   5 - SEL$3
   6 - SEL$3 / INNER@SEL$3

Predicate Information (identified by operation id):
---------------------------------------------------

   3 - filter("OUTER"."SAL">)
   6 - filter("INNER"."DEPT_NO"=:B1)

--//注:我的测试机器比较快,没有作者测试的9秒,仅仅接近4秒完成,不过还是看出比原来执行慢.注意看id=6,循环执行次数是3172.
--//也就是dept_no=432与dept_no=0,1,2,3,4,5存在hash冲突,这样每次执行内层循环dept_no=:B1是都要重复调用.

SCOTT@book> select dept_no,count(*) from emp group by dept_no order by 1;
   DEPT_NO   COUNT(*)
---------- ----------
         0       3167
         1       3167
         2       3167
         3       3166
         4       3166
         5       3167
       432          1
7 rows selected.

--//假设与dept_no=1出现hash冲突.
--//dept_no=432 循环1次
--//dept_no=0   循环1次
--//dept_no=1   循环3167次
--//dept_no=2   循环1次
--//dept_no=3   循环1次
--//dept_no=4   循环1次
--//dept_no=5   循环1次

--//这样累加: 1+1+3167+1+1+1+1 = 3173 ,不对相差1.我做了一些细节,证明hash冲突是dept_no=4.

5.其它有趣的测试:
--//执行如下,只要dept_no in 里面包括4,432查询就很慢(至少查询3个部门).就会有点慢.
--//也就是证明hash冲突的是dept_no=4.

select
        /*+ gather_plan_statistics post-shrink  */
        count(*)
from    (
        select  /*+ no_merge */
                outer.*
        from emp outer
        where outer.sal >
                (
                        select /*+ no_unnest */ avg(inner.sal)
                        from emp inner
                        where inner.dept_no = outer.dept_no
                )
        ) where dept_no in (432,4,5)
;

--//如果你执行如下,你会发现执行很快:
select
        /*+ gather_plan_statistics post-shrink  */
        count(*)
from    (
        select  /*+ no_merge */
                outer.*
        from emp outer
        where outer.sal >
                (
                        select /*+ no_unnest */ avg(inner.sal)
                        from emp inner
                        where inner.dept_no = outer.dept_no
                )
        ) where dept_no in (432,4)
;


SCOTT@book> @ dpc '' ''
PLAN_TABLE_OUTPUT
-------------------------------------
SQL_ID  9v9984wd6k9t5, child number 0
-------------------------------------
select         /*+ gather_plan_statistics post-shrink  */
count(*) from    (         select  /*+ no_merge */
outer.*         from emp outer         where outer.sal >
 (                         select /*+ no_unnest */ avg(inner.sal)
                  from emp inner                         where
inner.dept_no = outer.dept_no                 )         ) where dept_no
in (432,4)

Plan hash value: 322796046

------------------------------------------------------------------------------------------------------------------------
| Id  | Operation             | Name | Starts | E-Rows |E-Bytes| Cost (%CPU)| E-Time   | A-Rows |   A-Time   | Buffers |
------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |      |      1 |        |       |   214 (100)|          |      1 |00:00:00.01 |     741 |
|   1 |  SORT AGGREGATE       |      |      1 |      1 |       |            |          |      1 |00:00:00.01 |     741 |
|   2 |   VIEW                |      |      1 |    143 |       |   214   (1)| 00:00:03 |   1583 |00:00:00.01 |     741 |
|*  3 |    FILTER             |      |      1 |        |       |            |          |   1583 |00:00:00.01 |     741 |
|*  4 |     TABLE ACCESS FULL | EMP  |      1 |   5715 | 45720 |    71   (0)| 00:00:01 |   3167 |00:00:00.01 |     247 |
|   5 |     SORT AGGREGATE    |      |      2 |      1 |     8 |            |          |      2 |00:00:00.01 |     494 |
|*  6 |      TABLE ACCESS FULL| EMP  |      2 |   2857 | 22856 |    71   (0)| 00:00:01 |   3167 |00:00:00.01 |     494 |
------------------------------------------------------------------------------------------------------------------------

--//循环仅仅2次.这是因为参考链接:
http://blog.itpub.net/267265/viewspace-2155927/
https://blogs.oracle.com/oraclemagazine/on-caching-and-evangelizing-sql

-//摘要如下:

When you're using a scalar subquery, Oracle Database will set up a small in-memory hash table for the subquery and its
results each time it runs the query. So, when you run the previous query, Oracle Database sets up in memory a hash table
that looks like this:

Oracle Database will use this hash table to remember the scalar subquery and the inputs to it—just :DEPTNO in this case
—and the output from it. At the beginning of every query execution, this cache is empty, but suppose you run the query
and the first PROJECTS row you retrieve has a DEPTNO value of 10. Oracle Database will assign the number 10 to a hash
value between 1 and 255 (the size of the hash table cache in Oracle Database 10g and Oracle Database 11g currently) and
will look in that hash table slot to see if the answer exists. In this case, it will not, so Oracle Database must run
the scalar subquery with the input of 10 to get the answer. If that answer (count) is 42, the hash table may look
something like this:

//注:补充说明我测试10.2.0.5,buckets=512而不是255.有机会测试11.2.0.4的情况.

Select count(*) from emp where emp.deptno = :deptno
:deptno     Count(*)

You'll have saved the DEPTNO value of 10 and the answer (count) of 42 in some slot—probably not the first or last slot,
but whatever slot the hash value 10 is assigned to. Now suppose the second row you get back from the PROJECTS table
includes a DEPTNO value of 20. Oracle Database will again look in the hash table after assigning the value 20, and it
will discover "no result in the cache yet." So it will run the scalar subquery, get the result, and put it into the hash
table cache. Now the cache may look like this:

Select count(*) from emp where emp.deptno = :deptno
:deptno     Count(*)
Select count(*) from emp where emp.deptno = :deptno
:deptno     Count(*)
…     …
10     42

Now suppose the query returns a third row and it again includes a DEPTNO value of 10. This time, Oracle Database will
see DEPTNO = 10, find that it already has that value in the hash table cache, and will simply return 42 from the cache
instead of executing the scalar subquery. In fact, it will never have to run that scalar subquery for the DEPTNO values
of 10 or 20 again for that query—it will already have the answer.

What happens if the number of unique DEPTNO values exceeds the size of the hash table? What if there are more than 255
values? Or, more generally, if more than one DEPTNO value is assigned to the same slot in the hash table, what happens
in a hash collision?

The answer is the same for all these questions and is rather simple: Oracle Database will not be able to cache the
second or nth value to that slot in the hash table. For example, what if the third row returned by the query contains
the DEPTNO = 30 value? Further, suppose that DEPTNO = 30 is to be assigned to exactly the same hash table slot as DEPTNO
= 10. The database won't be able to effectively cache DEPTNO = 30 in this case—the value will never make it into the
hash table. It will, however, be "partially cached." Oracle Database still has the hash table with all the previous
executions, but it also keeps the last scalar subquery result it had "next to" the hash table. That is, if the fourth
row also includes a DEPTNO = 30 value, Oracle Database will discover that the result is not in the hash table but is
"next to" the hash table, because the last time it ran the scalar subquery, it was run with an input of 30. On the other
hand, if the fourth row includes a DEPTNO = 40 value, Oracle Database will run the scalar subquery with the DEPTNO = 40
value (because it hasn't seen that value yet during this query execution) and overwrite the DEPTNO = 30 result. The next
time Oracle Database sees DEPTNO = 30 in the result set, it'll have to run that scalar subquery again.

--//答案在这一段落中,如果查询结果临近它会从前面的查询获得结果,而不用进入循环.我仅仅查询dept_no in (432,4),这样后面全部是
--//dept_no=4返回,这样可以从临近的查询获得结果.实际上你看作者的表设计就知道答案:
SCOTT@book> select * from emp where rownum<=10;
   DEPT_NO        SAL     EMP_NO PADDING
---------- ---------- ---------- --------
       432      20001      20001 x
         4      19978      19978 x
         5      19979      19979 x
         0      19980      19980 x
         1      19981      19981 x
         2      19982      19982 x
         3      19983      19983 x
         4      19984      19984 x
         5      19985      19985 x
         0      19986      19986 x
10 rows selected.
--//dept_no记录不是聚集在一起的.

总结:
--//实际上这个例子我记忆在作者<基于成本的优化>的书中提到过.当时想作者如何知道那个数存在冲突.感觉作者很厉害.
--//另外写一篇blog猜测那些hash存在冲突的.



posted @ 2018-11-30 11:07  lfree  阅读(432)  评论(0编辑  收藏  举报