暂无图片
如何收集统计信息不影响数据库?
最近更新:2022-03-11 14:21:05

如何收集统计信息不影响数据库?

大多数情况下,表的统计信息不准导致了优化器对于执行计划的错误计算,因此需要对表的统计信息进行更正,以便让优化器重新选择准确的执行计划。

但是在生产情况下,随意的收集统计信息,则会给数据库带来隐患: 1、对重新收集统计信息的表,对应的一些SQL可能需要重新硬解析生成执行计划。 2、对于重新收集统计信息的表的部分SQL来说,可能会出现收集完统计信息了,但是执行计划更差的情况。 3、在业务高峰期收集统计信息,会需要额外的资源开销,影响数据库的性能。

在进行SQL优化时,通过查看执行计划,表的统计信息以及表的具体情况,去分析是否是由于统计信息不准导致执行计划有问题,当确定了是统计信息的问题时,不能盲目的去收集统计信息,需要进一步验证“重新收集统计信息可以提升SQL性能”。

因此在针对“重新收集统计信息可以提升SQL性能”时,主要介绍一下如何去重新收集统计信息而不影响数据库中正在运行的SQL。

在Oracle中,统计信息的收集,都是存储在对应的数据字典里,因此正常收集完统计信息,就会被对应的SQL去用来生成执行计划。但是,Oracle也提供了一种收集完统计信息却不会被记录在数据字典里,因此也不会被对应的SQL使用,只有在需要使用这些统计信息的时候,通过设置一些参数,才可以正常的使用这些统计信息。

Oracle中可以利用DBMS_STATS里的Pending Statistics去操作可以控制新收集的统计信息不会被存储到数据字典。

The package gather statistics and stores it in the dictionary by default. User's can store these statistics in the system's private area instead of the dictionary by turning the PUBLISH option to FALSE using the SET*PREFS procedures. The default value for PUBLISH is TRUE.The statistics stored in private area are not used by Cost Based Optimizer unless parameter optimizer_use_pending_statistics is set to TRUE. The default value of this parameter is FALSE and this boolean parameter can be set at the session/system level. Users can verify the impact of the new statistics on query plans by using the pending statistics on a session.

Pending statistics provide a mechanism to verify the impact of the new statistics on query plans before making them available for general use. There are two scenarios to verify the query plans:

Export the pending statistics (use the EXPORT_PENDING_STATS Procedure) to a test system, then run the query workload and check the performance or plans.

Set optimizer_use_pending_statistics to TRUE in a session on the system where pending statistics have been gathered, run the workload, and check the performance or plans.

Once the performance or query plans have been verified, the pending statistics can be published (run the PUBLISH_PENDING_STATS Procedure) if the performance is acceptable or delete (run the DELETE_PENDING_STATS Procedure) if not.

大致的意思:可以使用这种方法,针对统计信息正确与否,对执行计划影响的验证。

接下来用一个测试来验证。

1、创建测试表

SQL> drop table demo purge;
Table dropped.
......