1. 程式人生 > >Oracle 12c Result Cache詳解

Oracle 12c Result Cache詳解

Oracle 12c 以SH使用者登入系統,執行一個簡單的查詢:

注意在執行計劃中出現了:RESULT CACHE

SQL> SELECT COUNT(*)
  2  FROM sales
  3  WHERE AMOUNT_SOLD =
  4    ( SELECT MIN(AMOUNT_SOLD) FROM sales
  5    );

  COUNT(*)
----------
        38

已用時間:  00: 00: 02.34

執行計劃
----------------------------------------------------------
Plan hash value: 353223879

-----------------------------------------------------------------------------------------------------------------------
| Id  | Operation                | Name                       | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
-----------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT         |                            |     1 |     5 |  1043   (3)| 00:00:01 |       |       |
|   1 |  RESULT CACHE            | 638dzksdy77tj25m4rq4mvdmdx |       |       |            |          |       |       |
|   2 |   SORT AGGREGATE         |                            |     1 |     5 |            |          |       |       |
|   3 |    PARTITION RANGE ALL   |                            |   256 |  1280 |   523   (3)| 00:00:01 |     1 |    28 |
|*  4 |     TABLE ACCESS FULL    | SALES                      |   256 |  1280 |   523   (3)| 00:00:01 |     1 |    28 |
|   5 |      SORT AGGREGATE      |                            |     1 |     5 |            |          |       |       |
|   6 |       PARTITION RANGE ALL|                            |   918K|  4486K|   521   (3)| 00:00:01 |     1 |    28 |
|   7 |        TABLE ACCESS FULL | SALES                      |   918K|  4486K|   521   (3)| 00:00:01 |     1 |    28 |
-----------------------------------------------------------------------------------------------------------------------

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

   4 - filter("AMOUNT_SOLD"= (SELECT MIN("AMOUNT_SOLD") FROM "SALES" "SALES"))

Result Cache Information (identified by operation id):
------------------------------------------------------

   1 - column-count=1; type=AUTO; dependencies=(SH.SALES); attributes=(single-row); name="SELECT COUNT(*)
FROM sales
WHERE AMOUNT_SOLD =
  ( SELECT MIN(AMOUNT_SOLD) FROM sales
  )"


Note
-----
   - SQL plan baseline "SQL_PLAN_cstmbjapmzq3wb8285edf" used for this statement


統計資訊
----------------------------------------------------------
       3201  recursive calls
        132  db block gets
       8857  consistent gets
       1851  physical reads
      13044  redo size
        550  bytes sent via SQL*Net to client
        607  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
        370  sorts (memory)
          0  sorts (disk)
          1  rows processed

以SYS使用者連線到PDB後,檢視關於Result Cache的初始化引數設定:

SQL> show parameter result;

NAME                                 TYPE                   VALUE
------------------------------------ ---------------------- ------------------------------
client_result_cache_lag              big integer            3000
client_result_cache_size             big integer            0
result_cache_max_result              integer                5
result_cache_max_size                big integer            12384K
result_cache_mode                    string                 AUTO
result_cache_remote_expiration       integer                0

可以看到 result_cache_mode預設值為:AUTO

結果集快取(Result Cache)是共享全域性區域(SGA)或客戶端應用程式記憶體中的一個記憶體區域,用於儲存資料庫查詢或查詢塊的結果以便重用。快取的行在SQL語句和會話之間共享,除非它們變得過時。

可以分為:

  • Server Result Cache:伺服器結果快取是共享池內的記憶體池。這個記憶體池由SQL查詢結果快取(儲存SQL查詢的結果)和PL/SQL函式結果快取(儲存PL/SQL函式返回的值)組成。
  • Client Result Cache:Oracle Call Interface(OCI)客戶機結果快取是客戶機程序內的一個記憶體區域,用於快取OCI應用程式的SQL查詢結果集。此客戶端快取存在於每個客戶端程序中,並由程序內的所有會話共享。Oracle建議對只讀或讀取多表的查詢進行客戶端結果快取。 

客戶端結果快取與駐留在SGA中的伺服器結果快取不同。當啟用客戶端結果快取時,可以將查詢結果集快取在客戶端、伺服器或兩者上。即使伺服器結果快取被禁用,也可以啟用客戶端快取。

伺服器端 Result Cache是如何工作的?

當查詢執行時,資料庫搜尋快取記憶體,以確定結果是否存在於結果快取中。如果結果存在,則資料庫從記憶體中檢索結果,而不是執行查詢。如果沒有快取結果,則資料庫執行查詢,將結果作為輸出返回,並將結果儲存在結果快取中。

當用戶重複執行查詢和函式時,資料庫從快取中檢索行,從而減少響應時間。當依賴資料庫物件中的資料被修改時,快取結果變得無效。

在HR使用者下,執行下面的查詢語句:

注意,使用了 /*+ RESULT_CACHE */ Hints提示,通過檢視執行計劃,可以看到,執行計劃中產生了Result Cache。

Result Cache的ID為:36cy5bwyvd4bs1srpnt3yg1420。

SQL> SELECT /*+ RESULT_CACHE */ department_id, AVG(salary)
  2    FROM hr.employees
  3   GROUP BY department_id;

DEPARTMENT_ID AVG(SALARY)
------------- -----------
          100  8601.33333
           30        4150
                     7000
           20        9500
           70       10000
           90  19333.3333
          110       10154
           50  3475.55556
           40        6500
           80  8955.88235
           10        4400
           60        5760

已選擇 12 行。

已用時間:  00: 00: 00.54

執行計劃
----------------------------------------------------------
Plan hash value: 1192169904

--------------------------------------------------------------------------------------------------
| Id  | Operation           | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |                            |    11 |    77 |     4  (25)| 00:00:01 |
|   1 |  RESULT CACHE       | 36cy5bwyvd4bs1srpnt3yg1420 |       |       |            |          |
|   2 |   HASH GROUP BY     |                            |    11 |    77 |     4  (25)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMPLOYEES                  |   107 |   749 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------------------------------

Result Cache Information (identified by operation id):
------------------------------------------------------

   1 - column-count=2; dependencies=(HR.EMPLOYEES); name="SELECT /*+ RESULT_CACHE */ department_id, AVG(salary)
  FROM hr.employees
 GROUP BY department_id"



統計資訊
----------------------------------------------------------
        138  recursive calls
         12  db block gets
        300  consistent gets
          3  physical reads
       1152  redo size
        877  bytes sent via SQL*Net to client
        608  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
         12  sorts (memory)
          0  sorts (disk)
         12  rows processed

進而執行查詢:

SQL> SELECT id, type, creation_timestamp, block_count,
  2         column_count, pin_count, row_count
  3    FROM V$RESULT_CACHE_OBJECTS
  4   WHERE cache_id ='36cy5bwyvd4bs1srpnt3yg1420';

        ID TYPE                 CREATION_TIMES BLOCK_COUNT COLUMN_COUNT  PIN_COUNT  ROW_COUNT
---------- -------------------- -------------- ----------- ------------ ---------- ----------
       194 Result               01-10月-18               1            2          0         12

已用時間:  00: 00: 00.27

執行另外一個查詢:RESULT_CACHE Hint Specified in a WITH View

SQL> WITH summary AS
  2  ( SELECT /*+ RESULT_CACHE */ department_id, avg(salary) avg_sal
  3      FROM hr.employees
  4     GROUP BY department_id )
  5  SELECT d.*, avg_sal
  6    FROM hr.departments d, summary s
  7   WHERE d.department_id = s.department_id;

DEPARTMENT_ID DEPARTMENT_NAME                                              MANAGER_ID LOCATION_ID    AVG_SAL
------------- ------------------------------------------------------------ ---------- ----------- ----------
           10 Administration                                                      200        1700       4400
           20 Marketing                                                           201        1800       9500
           30 Purchasing                                                          114        1700       4150
           40 Human Resources                                                     203        2400       6500
           50 Shipping                                                            121        1500 3475.55556
           60 IT                                                                  103        1400       5760
           70 Public Relations                                                    204        2700      10000
           80 Sales                                                               145        2500 8955.88235
           90 Executive                                                           100        1700 19333.3333
          100 Finance                                                             108        1700 8601.33333
          110 Accounting                                                          205        1700      10154

已選擇 11 行。

已用時間:  00: 00: 00.29

執行計劃
----------------------------------------------------------
Plan hash value: 523547400

-----------------------------------------------------------------------------------------------------------
| Id  | Operation                    | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |                            |    11 |   517 |     7  (29)| 00:00:01 |
|   1 |  MERGE JOIN                  |                            |    11 |   517 |     7  (29)| 00:00:01 |
|   2 |   TABLE ACCESS BY INDEX ROWID| DEPARTMENTS                |    27 |   567 |     2   (0)| 00:00:01 |
|   3 |    INDEX FULL SCAN           | DEPT_ID_PK                 |    27 |       |     1   (0)| 00:00:01 |
|*  4 |   SORT JOIN                  |                            |    11 |   286 |     5  (40)| 00:00:01 |
|   5 |    VIEW                      |                            |    11 |   286 |     4  (25)| 00:00:01 |
|   6 |     RESULT CACHE             | 86qrwagbnhbkpbk0d2nfkjygkp |       |       |            |       |
|   7 |      HASH GROUP BY           |                            |    11 |    77 |     4  (25)| 00:00:01 |
|   8 |       TABLE ACCESS FULL      | EMPLOYEES                  |   107 |   749 |     3   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------------------

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

   4 - access("D"."DEPARTMENT_ID"="S"."DEPARTMENT_ID")
       filter("D"."DEPARTMENT_ID"="S"."DEPARTMENT_ID")

Result Cache Information (identified by operation id):
------------------------------------------------------

   6 - column-count=2; dependencies=(HR.EMPLOYEES); name="SELECT /*+ RESULT_CACHE */ department_id, avg(salary) avg_sal
    FROM hr.employees
   GROUP BY department_id "



統計資訊
----------------------------------------------------------
        120  recursive calls
          4  db block gets
        210  consistent gets
          2  physical reads
        588  redo size
       1277  bytes sent via SQL*Net to client
        608  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          8  sorts (memory)
          0  sorts (disk)
         11  rows processed

在這個示例中,如執行計劃的步驟6所示,直接從快取中檢索摘要檢視結果。name列中的值是結果的快取ID。

如果不需要Result Cache時,也可以使用Hints提示,請對比下面的示例:

(SH模式下,查詢Sales表)

SQL> SELECT /*+ NO_RESULT_CACHE */ prod_id, SUM(amount_sold)
  2    FROM sales
  3   GROUP BY prod_id
  4   ORDER BY prod_id;

已選擇 72 行。

已用時間:  00: 00: 00.30

執行計劃
----------------------------------------------------------
Plan hash value: 4109827725

----------------------------------------------------------------------------------------------
| Id  | Operation            | Name  | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |       |    72 |   648 |   556   (9)| 00:00:01 |       |       |
|   1 |  SORT GROUP BY       |       |    72 |   648 |   556   (9)| 00:00:01 |       |       |
|   2 |   PARTITION RANGE ALL|       |   918K|  8075K|   521   (3)| 00:00:01 |     1 |    28 |
|   3 |    TABLE ACCESS FULL | SALES |   918K|  8075K|   521   (3)| 00:00:01 |     1 |    28 |
----------------------------------------------------------------------------------------------

Note
-----
   - SQL plan baseline "SQL_PLAN_28c8zs51tg4h5ebe69af4" used for this statement


統計資訊
----------------------------------------------------------
         66  recursive calls
         81  db block gets
       1768  consistent gets
          1  physical reads
       8936  redo size
       2280  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          6  SQL*Net roundtrips to/from client
          5  sorts (memory)
          0  sorts (disk)
         72  rows processed

SQL> SELECT /*+ RESULT_CACHE */ prod_id, SUM(amount_sold)
  2    FROM sales
  3   GROUP BY prod_id
  4   ORDER BY prod_id;

已選擇 72 行。

已用時間:  00: 00: 00.22

執行計劃
----------------------------------------------------------
Plan hash value: 4109827725

--------------------------------------------------------------------------------------------------------------------
| Id  | Operation             | Name                       | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
--------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |                            |    72 |   648 |   556   (9)| 00:00:01 |    |          |
|   1 |  RESULT CACHE         | 1vf2p8s2503gdgx1wcrs8pvr49 |       |       |            |          |    |          |
|   2 |   SORT GROUP BY       |                            |    72 |   648 |   556   (9)| 00:00:01 |    |          |
|   3 |    PARTITION RANGE ALL|                            |   918K|  8075K|   521   (3)| 00:00:01 |  1 |       28 |
|   4 |     TABLE ACCESS FULL | SALES                      |   918K|  8075K|   521   (3)| 00:00:01 |  1 |       28 |
--------------------------------------------------------------------------------------------------------------------

Result Cache Information (identified by operation id):
------------------------------------------------------

   1 - column-count=2; dependencies=(SH.SALES); name="SELECT /*+ RESULT_CACHE */ prod_id, SUM(amount_sold)
  FROM sales
 GROUP BY prod_id
 ORDER BY prod_id"



統計資訊
----------------------------------------------------------
          6  recursive calls
         36  db block gets
       1686  consistent gets
          0  physical reads
        588  redo size
       2280  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          6  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
         72  rows processed

SQL>

對比上述兩個查詢的執行計劃,可以發現,第一個查詢沒有 Result Cache,而第二個查詢存在 Result Cache。

客戶端快取是如何工作的?

客戶端快取的結果儲存在最外層的查詢結果,這是“列定義的應用程式。子查詢和查詢塊是cached槽。

下面的流程圖展示客戶端與資料庫的登入會話。這個過程有一個客戶端,客戶端快取的結果表示在多應用共享會話執行時在客戶端的過程。如果一個應用程式的會話資訊的查詢,然後檢索的行從資料庫和在客戶端快取的結果。如果其他應用程式會話執行相同的查詢,那麼它們的檢索結果也是從客戶端快取獲得的。

The client result cache transparently keeps the result set consistent with session state or database changes that affect it. When a transaction changes the data or metadata of database objects used to build the cached result, the database sends an invalidation to the OCI client on its next round trip to the server.

與伺服器端Result Cache相關的初始化引數如下:

Server Result Cache Initialization Parameters

Parameter Description

RESULT_CACHE_MAX_SIZE

Specifies the memory allocated to the server result cache. To disable the server result cache, set this parameter to 0.

RESULT_CACHE_MAX_RESULT

Specifies the maximum amount of server result cache memory (in percent) that can be used for a single result. Valid values are between 1 and 100. The default value is 5%. You can set this parameter at the system or session level.

RESULT_CACHE_REMOTE_EXPIRATION

Specifies the expiration time (in minutes) for a result in the server result cache that depends on remote database objects. The default value is 0, which specifies that results using remote objects will not be cached. If a non-zero value is set for this parameter, DML on the remote database does not invalidate the server result cache.

另外,預設情況下,當Oracle啟動時,Oracle會在Shared Pool中為Server Result Cache分配一定的記憶體空間。這個Server Result Cache記憶體的大小取決於Shared Pool的大小和選擇的記憶體管理模式(自動共享SGA管理還是手動SGA管理)。

  • Automatic shared memory management

    If you are managing the size of the shared pool using the SGA_TARGET initialization parameter, Oracle Database allocates 0.50% of the value of the SGA_TARGET parameter to the result cache.

  • Manual shared memory management

    If you are managing the size of the shared pool using the SHARED_POOL_SIZE initialization parameter, then Oracle Database allocates 1% of the shared pool size to the result cache.

注意:Oracle Database will not allocate more than 75% of the shared pool to the server result cache.

通過執行:EXECUTE DBMS_RESULT_CACHE.MEMORY_REPORT,可以檢視Result Cache報告,

SQL> SET SERVEROUTPUT ON;
SQL> EXECUTE DBMS_RESULT_CACHE.MEMORY_REPORT;
R e s u l t   C a c h e   M e m o r y   R e p o r t
[Parameters]
Block Size          = 1K bytes
Maximum Cache Size  = 12384K bytes (12384 blocks)
Maximum Result Size = 619K bytes (619 blocks)
[Memory]
Total Memory = 12152 bytes [0.001% of the Shared Pool]
... Fixed Memory = 12152 bytes [0.001% of the Shared Pool]
... Dynamic Memory = 0 bytes [0.000% of the Shared Pool]

PL/SQL 過程已成功完成。

已用時間:  00: 00: 00.38
SQL>

通過執行過程:EXEC DBMS_RESULT_CACHE.FLUSH 可以清楚Server Result Cache。

SQL> SELECT id, type, creation_timestamp, block_count,
  2  column_count, pin_count, row_count
  3  FROM V$RESULT_CACHE_OBJECTS
  4  WHERE cache_id ='36cy5bwyvd4bs1srpnt3yg1420';

        ID TYPE                 CREATION_TIMES BLOCK_COUNT COLUMN_COUNT  PIN_COUNT  ROW_COUNT
---------- -------------------- -------------- ----------- ------------ ---------- ----------
       194 Result               01-10月-18               1            2          0         12

已用時間:  00: 00: 00.40

SQL> EXEC DBMS_RESULT_CACHE.FLUSH;

PL/SQL 過程已成功完成。

已用時間:  00: 00: 00.04
SQL> SELECT id, type, creation_timestamp, block_count,
  2  column_count, pin_count, row_count
  3  FROM V$RESULT_CACHE_OBJECTS
  4  WHERE cache_id ='36cy5bwyvd4bs1srpnt3yg1420';

未選定行

已用時間:  00: 00: 00.01

與客戶端Result Cache相關的初始化引數如下:

Client Result Cache Initialization Parameters

Parameter Description

CLIENT_RESULT_CACHE_SIZE

Specifies the maximum size of the client result cache for each client process. To enable the client result cache, set the size to 32768 bytes or greater. A lesser value, including the default of 0, disables the client result cache.

Note: If the CLIENT_RESULT_CACHE_SIZE setting disables the client cache, then a client node cannot enable it. If the CLIENT_RESULT_CACHE_SIZE setting enables the client cache, however, then a client node can override the setting. For example, a client node can disable client result caching or increase the size of its cache.

CLIENT_RESULT_CACHE_LAG

Specifies the amount of lag time (in milliseconds) for the client result cache. The default value is 3000 (3 seconds). If the OCI application does not perform any database calls for a period of time, then this setting forces the next statement execution call to check for validations.

If the OCI application accesses the database infrequently, then setting this parameter to a low value results in more round trips from the OCI client to the database to keep the client result cache synchronized with the database.

COMPATIBLE

Specifies the release with which Oracle Database must maintain compatibility. For the client result cache to be enabled, this parameter must be set to 11.0.0.0 or higher. For client caching on views, this parameter must be set to 11.2.0.0.0 or higher.

An optional client configuration file overrides client result cache initialization parameters set in the server parameter file.

Note: The client result cache lag can only be set with the CLIENT_RESULT_CACHE_LAG initialization parameter.

設定 Result Cache 模式

結果快取模式是一個數據庫設定,用於確定哪些查詢有資格在伺服器和客戶端結果快取中儲存結果集。如果查詢符合快取條件,則應用程式檢查結果快取以確定查詢結果集是否存在於快取中。如果存在,則直接從結果快取中檢索結果。否則,資料庫執行查詢並將結果作為輸出返回,並將其儲存在結果快取中。Oracle建議對只讀或讀取主要資料庫物件的查詢進行結果快取。

當啟用結果快取時,資料庫還快取呼叫非確定性PL/SQL函式的查詢。當快取呼叫這些函式的SELECT語句時,結果快取跟蹤PL/SQL函式和資料庫物件的資料依賴性。但是,如果函式使用未被跟蹤的資料(例如序列、SYSDATE、SYS_CONTEXT和包變數),則對呼叫該函式的查詢使用結果快取會產生過時的結果。在這方面,結果快取的行為與快取PL/SQL函式相同。因此,在選擇啟用結果快取時,始終要考慮資料的準確性和效能。

設定 result cache 模式:

  • 通過設定 RESULT_CACHE_MODE 初始化引數來設定 

    可以在資料庫例項級別 instance (ALTER SYSTEM),會話級別 session (ALTER SESSION), 或者在資料庫引數檔案中設定。

    Values for the RESULT_CACHE_MODE Parameter

Value Description

MANUAL

Query results can only be stored in the result cache by using a query hint or table annotation. This is the default and recommended value.

FORCE

All results are stored in the result cache. If a query result is not in the cache, then the database executes the query and stores the result in the cache. Subsequent executions of the same SQL statement, including the result cache hint, retrieve data from the cache. Sessions uses these results if possible. To exclude query results from the cache, the /*+ NO_RESULT_CACHE */ query hint must be used.

Note: FORCE mode is not recommended because the database and clients will attempt to cache all queries, which may create significant performance and latching overhead. Moreover, because queries that call non-deterministic PL/SQL functions are also cached, enabling the result cache in such a broad-based manner may cause material changes to the results.

思考問題

假設在同一個Session會話中執行下面的兩條查詢,觀察下面兩條SQL查詢的執行計劃,看看能發現什麼?

SQL查詢一:

SELECT *
  FROM ( SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
           FROM hr.employees 
          GROUP BY department_id, manager_id ) view1
 WHERE department_id = 30;

執行結果:

SQL> SELECT *
  2    FROM ( SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
  3             FROM hr.employees
  4            GROUP BY department_id, manager_id ) view1
  5   WHERE department_id = 30;

DEPARTMENT_ID MANAGER_ID      COUNT
------------- ---------- ----------
           30        100          1
           30        114          5

已用時間:  00: 00: 00.09

執行計劃
----------------------------------------------------------
Plan hash value: 2700420355

---------------------------------------------------------------------------------------------------
| Id  | Operation            | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |                            |   107 |  4173 |     4  (25)| 00:00:01 |
|*  1 |  VIEW                |                            |   107 |  4173 |     4  (25)| 00:00:01 |
|   2 |   RESULT CACHE       | 5a7n6czum41gcas673839j2b5y |       |       |            |          |
|   3 |    HASH GROUP BY     |                            |   107 |   749 |     4  (25)| 00:00:01 |
|   4 |     TABLE ACCESS FULL| EMPLOYEES                  |   107 |   749 |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

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

   1 - filter("DEPARTMENT_ID"=30)

Result Cache Information (identified by operation id):
------------------------------------------------------

   2 - column-count=3; dependencies=(HR.EMPLOYEES); name="SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
           FROM hr.employees
          GROUP BY department_"



統計資訊
----------------------------------------------------------
         19  recursive calls
          4  db block gets
         20  consistent gets
          0  physical reads
        588  redo size
        761  bytes sent via SQL*Net to client
        608  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          2  rows processed

SQL查詢二:

WITH view2 AS
( SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
    FROM hr.employees 
   GROUP BY department_id, manager_id ) 
SELECT *
  FROM view2 
 WHERE count BETWEEN 1 and 5;

執行結果:

SQL> WITH view2 AS
  2  ( SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
  3      FROM hr.employees
  4     GROUP BY department_id, manager_id )
  5  SELECT *
  6    FROM view2
  7   WHERE count BETWEEN 1 and 5;

DEPARTMENT_ID MANAGER_ID      COUNT
------------- ---------- ----------
           40        101          1
           60        103          4
           70        101          1
           80        149          5
                     149          1
          110        205          1
           50        100          5
           90        100          2
           10        101          1
           90                     1
           30        100          1
           60        102          1
          100        101          1
           20        100          1
           20        201          1
          110        101          1
          100        108          5
           30        114          5
           80        100          5

已選擇 19 行。

已用時間:  00: 00: 00.09

執行計劃
----------------------------------------------------------
Plan hash value: 2700420355

---------------------------------------------------------------------------------------------------
| Id  | Operation            | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |                            |   107 |  4173 |     4  (25)| 00:00:01 |
|*  1 |  VIEW                |                            |   107 |  4173 |     4  (25)| 00:00:01 |
|   2 |   RESULT CACHE       | 5a7n6czum41gcas673839j2b5y |       |       |            |          |
|   3 |    HASH GROUP BY     |                            |   107 |   749 |     4  (25)| 00:00:01 |
|   4 |     TABLE ACCESS FULL| EMPLOYEES                  |   107 |   749 |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

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

   1 - filter("COUNT">=1 AND "COUNT"<=5)

Result Cache Information (identified by operation id):
------------------------------------------------------

   2 - column-count=3; dependencies=(HR.EMPLOYEES); name="SELECT /*+ RESULT_CACHE */ department_id, manager_id, count(*) count
    FROM hr.employees
   GROUP BY department_id, manager_id"



統計資訊
----------------------------------------------------------
         10  recursive calls
          4  db block gets
          4  consistent gets
          0  physical reads
        588  redo size
       1160  bytes sent via SQL*Net to client
        619  bytes received via SQL*Net from client
          3  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
         19  rows processed

因為在SQL查詢二中使用了 Result Cache的 hints提示,在SQL查詢二中使用了SQL查詢一快取的結果。