search
HomeDatabaseMysql TutorialOracle学习之性能优化(四)收集统计信息

Oracle学习之性能优化(四)收集统计信息

Jun 07, 2016 pm 02:56 PM
oracleoptimizationinformationperformancecollectstatistics

emp表有如下数据。 SQLselectename,deptnofromemp;ENAMEDEPTNO----------------------------------------SMITH20ALLEN30WARD30JONES20MARTIN30BLAKE30CLARK10SCOTT20KING10TURNER30ADAMS20JAMES30FORD20MILLER1014rowsselected. 假设我们有如下简单的查询 se

 emp表有如下数据。

SQL> select ename,deptno from emp;

ENAME				   DEPTNO
------------------------------ ----------
SMITH				       20
ALLEN				       30
WARD				       30
JONES				       20
MARTIN				       30
BLAKE				       30
CLARK				       10
SCOTT				       20
KING				       10
TURNER				       30
ADAMS				       20
JAMES				       30
FORD				       20
MILLER				       10

14 rows selected.

假设我们有如下简单的查询

select ename,deptno from emp where ename='RICH' and deptno=10;

那么Oracle在执行查询的时候,是先比较ename字段呢?还是先比较deptno字段呢?

显然先比较deptno再比较ename字段的效率明显低于先比较ename,再比较deptno。 那Oracle究竟如何去判断呢?

我们先查询一张表

SQL> COL COLUMN_NAME FOR A30
SQL> SELECT column_name, num_distinct, density
  FROM dba_tab_columns
 WHERE owner = 'SCOTT' AND table_name = 'EMP';

COLUMN_NAME		       NUM_DISTINCT    DENSITY
------------------------------ ------------ ----------
EMPNO					 14 .071428571
ENAME					 14 .071428571
JOB					  5	    .2
MGR					  6 .166666667
HIREDATE				 13 .076923077
SAL					 12 .083333333
COMM					  4	   .25
DEPTNO					  3 .333333333

8 rows selected.

Oracle其实知道,你的表中存放数据的一些特征,上面语句显示的只是凤毛麟角。通过这些特征,Oracle优化器就能知道如何去查询,使得执行的效率最高。

以上这些信息,我们称之为对象的统计信息。那么如何收集统计信息呢?


一、 analyze 命令

使用analyze命令可以收集统计信息,如:

  • 收集或删除对象的统计信息

  • 验证对象的结构

  • 确定table 或cluster的migrated 和chained rows。

示例:

SQL> create user anal identified by anal ;

User created.

SQL> grant resource,connect to anal;

Grant succeeded.

SQL> grant select any dictionary to anal;

Grant succeeded.

SQL> conn anal/anal
Connected.
SQL> create table t1 as select * from dba_objects;
SQL> create table t2 as select * from dba_objects;
SQL> create table t3 as select * from dba_objects;
SQL> create table t4 as select * from  dba_objects;
SQL> create table t5 as select * from dba_objects;
SQL> create table t6 as select * from dba_objects;
SQL>  create unique index pk_t1_idx on t1(object_id);
SQL>  create unique index pk_t2_idx on t2(object_id);
SQL>  create unique index pk_t3_idx on t3(object_id);
SQL>  create unique index pk_t4_idx on t4(object_id);
SQL>  create unique index pk_t5_idx on t5(object_id);
SQL>  create unique index pk_t6_idx on t6(object_id);

我们先查看一下统计信息是否存在

查看表的统计信息

SQL> select table_name, num_rows, blocks, empty_blocks
      from user_tables
     where table_name in ('T1', 'T2', 'T3', 'T4', 'T5','T6');

查看字段统计信息

select table_name,
       column_name,
       num_distinct,
       low_value,
       high_value,
       density
  from user_tab_columns
 where table_name in ('T1', 'T2', 'T3', 'T4','T5','T6');

查看索引统计信息

SQL> col table_name for a30
SQL> col index_name for a30
SELECT table_name,
       index_name,
       blevel,
       leaf_blocks,
       distinct_keys,
       avg_leaf_blocks_per_key avg_leaf_blocks,
       avg_data_blocks_per_key avg_data_blocks,
       clustering_factor,
       num_rows
  FROM user_indexes

TABLE_NAME		       INDEX_NAME			  BLEVEL LEAF_BLOCKS DISTINCT_KEYS AVG_LEAF_BLOCKS AVG_DATA_BLOCKS CLUSTERING_FACTOR   NUM_ROWS
------------------------------ ------------------------------ ---------- ----------- ------------- --------------- --------------- ----------------- ----------
T6			       PK_T6_IDX			       1	 155	     74564		 1		 1		1174	  74564
T5			       PK_T5_IDX			       1	 155	     74563		 1		 1		1174	  74563
T4			       PK_T4_IDX			       1	 155	     74562		 1		 1		1174	  74562
T3			       PK_T3_IDX			       1	 155	     74561		 1		 1		1174	  74561
T2			       PK_T2_IDX			       1	 155	     74560		 1		 1		1174	  74560
T1			       PK_T1_IDX			       1	 155	     74559		 1		 1		1174	  74559

6 rows selected.

表没有任何统计数据,但是索引已经有统计信息,可见在建立表的时候会默认收集统计信息。

先将索引的统计信息删除

SQL> analyze table t1 delete statistics;
analyze table t2 delete statistics;
analyze table t3 delete statistics;
analyze table t4 delete statistics;
analyze table t5 delete statistics;
analyze table t6 delete statistics;

验证索引上是否还存在统计信息

SELECT table_name,
       index_name,
       blevel,
       leaf_blocks,
       distinct_keys,
       avg_leaf_blocks_per_key avg_leaf_blocks,
       avg_data_blocks_per_key avg_data_blocks,
       clustering_factor,
       num_rows
  FROM user_indexes

执行统计信息命令,并查看统计信息有无变化

analyze table t1 compute statistics for table;  

--针对表收集信息,查看user_tables

analyze table t2 compute statistics for all columns;  

--针对表字段收集信息,查看user_tab_columns

analyze table t3 compute statistics for all indexed columns;  

--收集索引字段信息

analyze table t4 compute statistics;        

--收集表,表字段,索引信息

analyze table t5 compute statistics for all indexes;          

--收集索引信息

analyze table t6 compute statistics for table for all indexes for all columns; 

--收集表,表字段,索引信息


二、DBMS_STATS包

  Oracle推荐使用DBMS_STATS这个包来收集统计信息。这个包的功能非常多。可以收集数据库级别、schema级别及表级别的统计信息。还可以对统计信息删除、锁定、导出、导入等。我们以最常用的表级别统计为例说明DBMS_STATS该如何使用。

 收集的统计信存储在dba_tab_statistics、dba_ind_statistics和dba_tab_col_statistics表中。

DBMS_STATS.GATHER_TABLE_STATS (
   ownname          VARCHAR2, 
   tabname          VARCHAR2, 
   partname         VARCHAR2 DEFAULT NULL,
   estimate_percent NUMBER   DEFAULT to_estimate_percent_type 
                                                (get_param('ESTIMATE_PERCENT')), 
   block_sample     BOOLEAN  DEFAULT FALSE,
   method_opt       VARCHAR2 DEFAULT get_param('METHOD_OPT'),
   degree           NUMBER   DEFAULT to_degree_type(get_param('DEGREE')),
   granularity      VARCHAR2 DEFAULT GET_PARAM('GRANULARITY'), 
   cascade          BOOLEAN  DEFAULT to_cascade_type(get_param('CASCADE')),
   stattab          VARCHAR2 DEFAULT NULL, 
   statid           VARCHAR2 DEFAULT NULL,
   statown          VARCHAR2 DEFAULT NULL,
   no_invalidate    BOOLEAN  DEFAULT  to_no_invalidate_type (
                                     get_param('NO_INVALIDATE')),
   stattype         VARCHAR2 DEFAULT 'DATA',
   force            BOOLEAN  DEFAULT FALSE);

参数说明如下:

wKiom1XTQfjjM5MQAAK5UvU0I1U436.jpg

wKiom1XTQgPC6wJhAAXhcpo1cG0620.jpg

wKioL1XTRBujG-h6AAYphtOucrs231.jpg

wKiom1XTQh6CXHdEAAJ-9MoVv0U797.jpg


示例:

  

SQL> col table_name for a30
SQL> SELECT table_name,
       num_rows,
       blocks,
       empty_blocks,
       avg_row_len
  FROM user_tab_statistics;

TABLE_NAME			 NUM_ROWS     BLOCKS EMPTY_BLOCKS AVG_ROW_LEN
------------------------------ ---------- ---------- ------------ -----------
T1				    74559	1088		0	   98
T2
T3
T4
T5
T6

6 rows selected.


删除统计信息

DBMS_STATS.DELETE_TABLE_STATS (
 ownname VARCHAR2,
 tabname VARCHAR2,
 partname VARCHAR2 DEFAULT NULL,
 stattab VARCHAR2 DEFAULT NULL,
 statid VARCHAR2 DEFAULT NULL,
 cascade_parts BOOLEAN DEFAULT TRUE,
 cascade_columns BOOLEAN DEFAULT TRUE,
 cascade_indexes BOOLEAN DEFAULT TRUE,
 statown VARCHAR2 DEFAULT NULL,
 no_invalidate BOOLEAN DEFAULT to_no_invalidate_type (
 get_param('NO_INVALIDATE')),
 force BOOLEAN DEFAULT FALSE);

锁定统计信息

DBMS_STATS.LOCK_TABLE_STATS (
 ownname VARCHAR2,
 tabname VARCHAR2);

锁定以后就不能再执行统计信息

SQL> exec dbms_stats.lock_table_stats(user,'T1');

PL/SQL procedure successfully completed.

SQL> exec dbms_stats.gather_table_stats(user,'t1',cascade=>true);
BEGIN dbms_stats.gather_table_stats(user,'t1',cascade=>true); END;

*
ERROR at line 1:
ORA-20005: object statistics are locked (stattype = ALL)
ORA-06512: at "SYS.DBMS_STATS", line 23829
ORA-06512: at "SYS.DBMS_STATS", line 23880
ORA-06512: at line 1

导出、导入统计信息

  1. 要导出统计信息首先要建立一个统计表

语法:

DBMS_STATS.CREATE_STAT_TABLE (
   ownname  VARCHAR2, 
   stattab  VARCHAR2,
   tblspace VARCHAR2 DEFAULT NULL);
SQL> exec DBMS_STATS.CREATE_STAT_TABLE (user,'STAT_TMP','SYSAUX');

PL/SQL procedure successfully completed.

2. 将表t1统计信息导出

DBMS_STATS.EXPORT_TABLE_STATS (
   ownname         VARCHAR2, 
   tabname         VARCHAR2, 
   partname        VARCHAR2 DEFAULT NULL,
   stattab         VARCHAR2, 
   statid          VARCHAR2 DEFAULT NULL,
   cascade         BOOLEAN  DEFAULT TRUE,
   statown         VARCHAR2 DEFAULT NULL,
   stat_category   VARCHAR2 DEFAULT DEFAULT_STAT_CATEGORY);
SQL> EXEC DBMS_STATS.EXPORT_TABLE_STATS (ownname=>USER,tabname=>'T1',stattab=>'STAT_TMP');

PL/SQL procedure successfully completed.

3. 导入统计信息

语法:

DBMS_STATS.IMPORT_TABLE_STATS (
   ownname         VARCHAR2, 
   tabname         VARCHAR2,
   partname        VARCHAR2 DEFAULT NULL,
   stattab         VARCHAR2, 
   statid          VARCHAR2 DEFAULT NULL,
   cascade         BOOLEAN  DEFAULT TRUE,
   statown         VARCHAR2 DEFAULT NULL,
   no_invalidate   BOOLEAN DEFAULT to_no_invalidate_type(
                                    get_param('NO_INVALIDATE')),
   force           BOOLEAN DEFAULT FALSE,
   stat_category   VARCHAR2 DEFAULT DEFAULT_STAT_CATEGORY);
SQL> exec dbms_stats.UNlock_table_stats(user,'T1');

PL/SQL procedure successfully completed.

SQL> exec dbms_stats.delete_table_stats(user,'T1');

PL/SQL procedure successfully completed.

SQL> EXEC DBMS_STATS.IMPORT_TABLE_STATS (ownname=>USER,tabname=>'T1',stattab=>'STAT_TMP');

PL/SQL procedure successfully completed.

SQL> SELECT table_name,
       num_rows,
       blocks,
       empty_blocks,
       avg_row_len
  FROM user_tab_statistics;  2    3    4    5    6  

TABLE_NAME			 NUM_ROWS     BLOCKS EMPTY_BLOCKS AVG_ROW_LEN
------------------------------ ---------- ---------- ------------ -----------
T1				    74559	1088		0	   98
T2
T3
T4
T5
T6
STAT_TMP

7 rows selected.


如果是分区表,新的分区来不及收集统计系统,可以使用其它的分区统计信息来生成新分区的统计信息

DBMS_STATS.COPY_TABLE_STATS (
   ownname          VARCHAR2, 
   tabname          VARCHAR2, 
   srcpartname      VARCHAR2,
   dstpartname      VARCHAR2, 
   scale_factor     VARCHAR2 DEFAULT 1,
   force            BOOLEAN DEFAULT FALSE);

如果表还没有统计信息,那么在执行sql语句时,Oracle会动态的采样表中的一部分数据,生成统计信息。

SQL> show parameter optimizer_dynamic_sampling ;

NAME				     TYPE			       VALUE
------------------------------------ --------------------------------- ------------------------------
optimizer_dynamic_sampling	     integer			       2
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment