count(*)小優化

oracle_mao發表於2012-10-12


 在程式處理分頁時,有時需要使用count(*)查詢,而如果表很大的時候,用此方法無疑瓶頸所在,今天發現了一個解決辦法就是如果這個表有唯一列的話(比如主鍵),那我們可以使用主鍵,強制走索引來縮短查詢時間。
主鍵:id
索引:SYS_C0029630

SQL> select /*+ index(tt SYS_C0029630) */count(id) from tt;

 COUNT(ID)
----------
     75651


Execution Plan
----------------------------------------------------------
Plan hash value: 3525147495

-------------------------------------------------------------------------
| Id  | Operation        | Name         | Rows  | Cost (%CPU)| Time     |
-------------------------------------------------------------------------
|   0 | SELECT STATEMENT |              |     1 |   213   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE  |              |     1 |            |          |
|   2 |   INDEX FULL SCAN| SYS_C0029630 | 88573 |   213   (0)| 00:00:01 |
-------------------------------------------------------------------------

Note
-----
   - dynamic sampling used for this statement (level=2)


Statistics
----------------------------------------------------------
          4  recursive calls
          0  db block gets
        287  consistent gets
          0  physical reads
          0  redo size
        425  bytes sent via SQL*Net to client
        419  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed

SQL> desc tt;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                                        NOT NULL NUMBER(38)
 NAME                                               VARCHAR2(2)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24500180/viewspace-746289/,如需轉載,請註明出處,否則將追究法律責任。

相關文章