管理Managing SQL Profiles

huzhichengforce發表於2015-03-06
About SQL Profiles(sqlprofile 介紹)
A SQL profile is a database object that contains auxiliary statistics specific to a SQL statement. Conceptually, a SQL profile is to a SQL statement what object-level statistics are to a table or index. SQL profiles are created when a DBA invokes SQL Tuning Advisor (see "About SQL Tuning Advisor").
SQL profile 是一個資料庫物件用來對一個sql 明確統計資訊。從概念上來說,SQL profile 是針對一個sql指明 所使用表的物件級別的統計資訊。當DBA 在調優的時候會用到sql profile
22.1.1 Purpose of SQL Profiles
SQL Profiles 的目標

When profiling a SQL statement, SQL Tuning Advisor uses a specific set of bind values as input, and then compares the optimizer estimate with values obtained by executing fragments of the statement on a data sample. When significant variances are found, SQL Tuning Advisor bundles corrective actions together in a SQL profile, and then recommends its acceptance.

The corrected statistics in a SQL profile can improve optimizer cardinality estimates, which in turn leads the optimizer to select better plans. SQL profiles provide the following benefits over other techniques for improving plans:

當在分析一個sql 語句的時候,sql優化建議器使用一個傳入的明確值,然後比較 優化器通過在資料樣本里面計算的出來的值

Unlike hints and stored outlines, SQL profiles do not tie the optimizer to a specific plan or subplan. SQL profiles fix incorrect estimates while giving the optimizer the flexibility to pick the best plan in different situations.

與使用hints 和stored outlines 不同的是 sql profile  不繫結一個明確的plan 或者subplan給優化器,sql profile  修正一個不正確的估值給優化器在不用的情況下選擇最好的執行計劃。

Unlike hints, no changes to application source code are necessary when using SQL profiles. The use of SQL profiles by the database is transparent to the user. 

與hints 不同 ,在使用sql profile  的時候不需要修改程式原始碼。sql profile  的使用對使用者來說是透明的。


22.1.2 Concepts for SQL Profiles


A SQL profile is a collection of auxiliary statistics on a query, including all tables and columns referenced in the query. The profile stores this information in the data dictionary. The optimizer uses this information at optimization time to determine the correct plan.

sql profile 是在執行sql 查詢的時候提供的輔助統計資訊,包括在sql  查詢中使用到的表的所有的列的資訊。 sql profile  將這些資訊儲存在資料字典中。

Note:

The SQL profile contains supplemental statistics for the entire statement, not individual plans. The profile does not itself determine a specific plan.
注意:
sql   profile 為整個語句提供了額外的統計資訊。不單獨針對某個計劃,profile 不會自己決定一個明確的計劃

A SQL profile contains, among other statistics, a set of cardinality adjustments. The cardinality measure is based on sampling the WHERE clause rather than on statistical projection. A profile uses parts of the query to determine whether the estimated cardinalities are close to the actual cardinalities and, if a mismatch exists, uses the corrected cardinalities. For example, if a SQL profile exists for SELECT * FROM t WHERE x=5 AND y=10, then the profile stores the actual number of rows returned.

When choosing plans, the optimizer has the following sources of information:

The environment, which contains the database configuration, bind variable values, optimizer statistics, data set, and so on

sql profile 包含其他統計,基數調整,這個基數,確保了他是基於where 條件而不是統計投影。一個profile 使用一部分查詢決定計算的基數和真實的基數相近, 如果存在誤差,使用正確的基數。例如如果一個sql SELECT * FROM t WHERE x=5 AND y=10 

sql profile 會儲存返回行的數量 在選擇執行計劃,優化器的時候會基於上訴資訊:

包括資料庫配置,繫結變數,優化統計器,資料集 等等。

The supplemental statistics in the SQL profile


Figure 22-1 shows the relationship between a SQL statement and the SQL profile for this statement. The optimizer uses the SQL profile and the environment to generate an execution plan. In this example, the plan is in the SQL plan baseline for the statement.

圖22-1 列出了profile 和sql 語句之間的關係,優化器使用sql profile 和環境產生一個執行計劃,在下例中執行計劃存放在執行計劃基線裡面。


either the optimizer environment or SQL profile change, then the optimizer can create a new plan. As tables grow, or as indexes are created or dropped, the plan for a SQL profile can change. The profile continues to be relevant even if the data distribution or access path of the corresponding statement changes. In general, you do not need to refresh SQL profiles.

Over time, profile content can become outdated. In this case, performance of the SQL statement may degrade. The statement may appear as high-load or top SQL. In this case, the Automatic SQL Tuning task again captures the statement as high-load SQL. You can implement a new SQL profile for the statement.

優化器環境或者sqlprofile 發生了變化 優化器能夠重新建立一個執行計劃。 隨著表的增長,或者所有的建立或者刪除, sqlprofile 裡的執行計劃會發生改變, 當資料分佈發生變化或者對於的語句訪問路徑發生變化,sqlprofile 仍然繼續提供相關服務, 一般來說你並不需要重新建立sql profile。

隨著時間推移,profile 會變的過時 這種情況下 使用了sqlprofile 的sql 語句效能會下降。sql 語句很可能成為一個高負載或者top sql。

在這種情況下,sql 自動調優任務會再次捕獲這個高負載sql 你需要重新建立一個sql profile

Internally, a SQL profile is implemented using hints that address different types of problems. These hints do not specify any particular plan. Rather, the hints correct errors in the optimizer estimation algorithm that lead to suboptimal plans. For example, a profile may use theTABLE_STATS hint to set object statistics for tables when the statistics are missing or stale.

本質上,sqlprofile 是使用hint 解決的不同情況下的問題。

22.1.2.1 SQL Profile Recommendations,那些hint 不會指明特定的執行計劃,然而那些hints 會修正優化器裡面因錯誤評估而產生的執行計劃。 比如說在統計資訊缺失或者陳舊,profile 就會是用到table_stat hint 為表設定統計資訊。

As explained in "SQL Profiling", SQL Tuning Advisor invokes Automatic Tuning Optimizer to generate SQL profile recommendations. Recommendations to implement SQL profiles occur in a finding, which appears in a separate section of the SQL Tuning Advisor report.

就像在sqlprofile 裡面解釋的 sql 優化建議器會自動產生sqlprofile 建議。 在發現一個新的sqlprofile 變更的時候會會提示你建立sqlprofile。 這些都會在sql 調優建議報告裡面體現出來。

When you implement (or accept) a SQL profile, the database creates the profile and stores it persistently in the data dictionary. However, the SQL profile information is not exposed through regular dictionary views.

當你在實施一個sqlproffile 操作的時候,資料建立profile 並儲存固定在資料字典裡面。但是sqlprofile 資訊不會在資料字典中顯示出來。

Example 22-1 SQL Profile Recommendation (SQL PROFILE 建議)


In this example, the database found a better plan for a SELECT statement that uses several expensive joins. The database recommends running DBMS_SQLTUNE.ACCEPT_SQL_PROFILE to implement the profile, which enables the statement to run 98.53% faster.

在下面的舉例中,資料庫發現對於使用消耗比較大的joins 的語句有更好的執行計劃。 資料庫建議執行DBMS_SQLTUNE.ACCEPT_SQL_PROFILE 來實施profile 這將會提高98% 的效率

-------------------------------------------------------------------------------
FINDINGS SECTION (2 findings)
-------------------------------------------------------------------------------
 
1- SQL Profile Finding (see explain plans section below)
--------------------------------------------------------
  A potentially better execution plan was found for this statement. Choose
  one of the following SQL profiles to implement.
 
  Recommendation (estimated benefit: 99.45%)
  ------------------------------------------
  - Consider accepting the recommended SQL profile.
    execute dbms_sqltune.accept_sql_profile(task_name => 'my_task',
            object_id => 3, task_owner => 'SH', replace => TRUE);
 
  Validation results
  ------------------
  The SQL profile was tested by executing both its plan and the original plan
  and measuring their respective execution statistics. A plan may have been
  only partially executed if the other could be run to completion in less time.
 
                           Original Plan  With SQL Profile  % Improved
                           -------------  ----------------  ----------
  Completion Status:             PARTIAL          COMPLETE
  Elapsed Time(us):            15467783            226902      98.53 %
  CPU Time(us):                15336668            226965      98.52 %
  User I/O Time(us):                  0                 0
  Buffer Gets:                  3375243             18227      99.45 %
  Disk Reads:                         0                 0
  Direct Writes:                      0                 0
  Rows Processed:                     0               109
  Fetches:                            0               109
  Executions:                         0                 1
 
  Notes
  -----
  1. The SQL profile plan was first executed to warm the buffer cache.
  2. Statistics for the SQL profile plan were averaged over next 3 executions.

Sometimes SQL Tuning Advisor may recommend implementing a profile that uses the Automatic Degree of Parallelism (Auto DOP) feature. A parallel query profile is only recommended when the original plan is serial and when parallel execution can significantly reduce the elapsed time for a long-running query.

有時sql優化建議器可能會建議你在profile使用Automatic Degree of Parallelism 功能。

When it recommends a profile that uses Auto DOP, SQL Tuning Advisor gives details about the performance overhead of using parallel execution for the SQL statement in the report. For parallel execution recommendations, SQL Tuning Advisor may provide two SQL profile recommendations, one using serial execution and one using parallel.

當在profile 使用了Auto DOP,sql 優化建議器會針對使用了Auto DOP功能的sql 提供詳細的效能負載。

The following example shows a parallel query recommendation. In this example, a degree of parallelism of 7 improves response time significantly at the cost of increasing resource consumption by almost 25%. You must decide whether the reduction in database throughput is worth the increase in response time.

在一個並行度為7的語句中資源消耗提高了將近25%,你需要考慮清楚在消耗資源和響應時間上做出選擇。

下面的例子 展示了一個並行查詢建議,在例中

  Recommendation (estimated benefit: 99.99%)
  ------------------------------------------
  - Consider accepting the recommended SQL profile to use parallel execution
    for this statement.
    execute dbms_sqltune.accept_sql_profile(task_name => 'gfk_task',
            object_id => 3, task_owner => 'SH', replace => TRUE,
            profile_type => DBMS_SQLTUNE.PX_PROFILE);
 
  Executing this query parallel with DOP 7 will improve its response time
  82.22% over the SQL profile plan. However, there is some cost in enabling
  parallel execution. It will increase the statement's resource consumption by
  an estimated 24.43% which may result in a reduction of system throughput.
  Also, because these resources are consumed over a much smaller duration, the
  response time of concurrent statements might be negatively impacted if
  sufficient hardware capacity is not available.
 
  The following data shows some sampled statistics for this SQL from the past
  week and projected weekly values when parallel execution is enabled.
 
                                 Past week sampled statistics for this SQL
                                 -----------------------------------------
  Number of executions                                                   0
  Percent of total activity                                            .29
  Percent of samples with #Active Sessions > 2*CPU                       0
  Weekly DB time (in sec)                                            76.51
 
                              Projected statistics with Parallel Execution
                              --------------------------------------------
  Weekly DB time (in sec)                                            95.21



22.1.2.2 SQL Profiles and SQL Plan Baselines
sql plrofile  和 sql plan 基線 

You can use SQL profiles with or without SQL plan management. No strict relationship exists between the SQL profile and the plan baseline. If a statement has multiple plans in a SQL plan baseline, then a SQL profile is useful because it enables the optimizer to choose the lowest-cost plan in the baseline.

在使用sqlprofile 的 時候 你可以使用也可以不使用那個sql plan 來管理。

sql profile 和plan  baseline  之間關係沒有嚴格上的要求。,如果一個語句在 sql plan 的基線裡面有多個執行計劃, 那麼sql profile  就比較有效 ,因為他會選者消耗最小的執行計劃基線。

22.1.3 User Interfaces for SQL Profiles(sql profile的使用者介面

Oracle Enterprise Manager Cloud Control (Cloud Control) usually handles SQL profiles as part of automatic SQL tuning.

On the command line, you can manage SQL profiles with the DBMS_SQLTUNE package. To use the APIs, you must have the ADMINISTER SQL MANAGEMENT OBJECT privilege.

1、OEM 能夠將sql profile 當作自動sql 調優裡面的一項任務。

2、在命令列你可以通過 DBMS_SQLTUNE 包來管理sql profile  要使用 APIS 你必須擁有ADMINISTER SQL MANAGEMENT OBJECT 的許可權

22.1.4 Basic Tasks for SQL Profiles(sql  profile 基本實施)

This section explains the basic tasks involved in managing SQL profiles. Figure 22-2 shows the basic workflow for implementing, altering, and dropping SQL profiles.

這節介紹了在管理sql profile 中的基本任務。 圖22-2  展示了 實施,修改,刪除sql profile  的基本流程。

Figure 22-2 Managing SQL Profiles


Typically, you manage SQL profiles in the following sequence:

通常你管理sql profi 需要以下四步:

    1. 

Implement a recommended SQL profile.

"Implementing a SQL Profile" describes this task.

實施sql profile


    2. 

Obtain information about SQL profiles stored in the database.

"Listing SQL Profiles" describes this task.

獲取資料庫中sql  profile 存放的資訊 

    3. 

Optionally, modify the implemented SQL profile.

"Altering a SQL Profile" describes this task.

對存在的sqlprofile 進行修改

    4. 

Drop the implemented SQL profile when it is no longer needed.

"Dropping a SQL Profile" describes this task.

刪除一個不再需要的sql profile

To tune SQL statements on another database, you can transport both a SQL tuning set and a SQL profile to a separate database. "Transporting a SQL Profile" describes this task.
你可以遷移sql tuning set  和sql profile  到另外一個資料庫中。


22.2 Implementing a SQL Profile(實施 sql profile)

Implementing (also known as accepting) a SQL profile means storing it persistently in the database. A profile must be implemented before the optimizer can use it as input when generating plans.

實施一個sqlprofile 意味著將它固定在資料中 profile 必須在計劃產生之前實施。

22.2.1 About SQL Profile Implementation

As a rule of thumb, implement a SQL profile recommended by SQL Tuning Advisor. If the database recommends both an index and a SQL profile, then either use both or use the SQL profile only. If you create an index, then the optimizer may need the profile to pick the new index.

根據經驗,通過 sql 優化建議實施的sqlprofile 如果資料庫對索引和sqlprofile 都使用,那麼兩個都將生效,或者值使用sql profile。

如果你建立了一個索引,優化器可能需要profile 選擇新的索引。

In some situations, SQL Tuning Advisor may find an improved serial plan in addition to an even better parallel plan. In this case, the advisor recommends both a standard and a parallel SQL profile, enabling you to choose between the best serial and best parallel plan for the statement. Implement a parallel plan only if the increase in response time is worth the decrease in throughput.

在某些情況下,除了更好的並行計劃,sql 優化顧問會找出改進的序列計劃。對於此,優化顧問針對表準的和並行的都可接受,使得你能夠為sql 語句選擇最好的序列或者最好的並行計劃

To implement a SQL profile, execute the DBMS_SQLTUNE.ACCEPT_SQL_PROFILE procedure. Some important parameters are as follows:

通過執行 DBMS_SQLTUNE.ACCEPT_SQL_PROFILE 過程來實施sql profile 其中有一些重要的引數需要設定:

profile_type

Set this parameter to REGULAR_PROFILE for a SQL profile without a change to parallel execution, or PX_PROFLE for a SQL profile with a change to parallel execution.

  將profile_type  設定為REGULAR_PROFILE  時 sql profile 將不會變化為 並行執行。 設定為PX_PROFLE  時sql profile 變化為 並行執行。

force_match

This parameter controls statement matching. Typically, an accepted SQL profile is associated with the SQL statement through a SQL signature that is generated using a hash function. This hash function changes the SQL statement to upper case and removes all extra whites spaces before generating the signature. Thus, the same SQL profile works for all SQL statements in which the only difference is case and white spaces.

force_match  引數控制語句匹配。典型的,一個sql 通過hash 演算法產生一個hash 值和sql profile 關聯。這個hash函式將sql語句轉化為大寫,並且在給語句標記錢將先前所有的whites spaces 刪除。 這樣相同的sql profile  為所有的 大小寫不同和white spaces. 的語句提供 服務。

By setting force_match to true, the SQL profile additionally targets all SQL statements that have the same text after the literal values in the WHERE clause have been replaced by bind variables. This setting may be useful for applications that use only literal values because it enables SQL with text differing only in its literal values to share a SQL profile. If both literal values and bind variables are in the SQL text, or if force_match is set to false (default), then the literal values in the WHERE clause are not replaced by bind variables.

將 force_match 設定為true  sql profile 將所有where 條件相同使用了繫結變數的sql 語句都起作用。設定為 false (預設) where 條件後面的將視為不同。



22.2.2 Implementing a SQL Profile

This section shows how to use the ACCEPT_SQL_PROFILE procedure to implement a SQL profile.

Assumptions

This tutorial assumes the following:

    - 

The SQL Tuning Advisor task STA_SPECIFIC_EMP_TASK includes a recommendation to create a SQL profile.

    - 

The name of the SQL profile is my_sql_profile.

    - 

The PL/SQL block accepts a profile that uses parallel execution (profile_type).

    - 

The profile uses force matching.

To implement a SQL profile: 

    - 

Connect SQL*Plus to the database with the appropriate privileges, and then execute the ACCEPT_SQL_PROFILE function.

For example, execute the following PL/SQL:

DECLARE
  my_sqlprofile_name VARCHAR2(30);
BEGIN
  my_sqlprofile_name := DBMS_SQLTUNE.ACCEPT_SQL_PROFILE ( 
    task_name    => 'STA_SPECIFIC_EMP_TASK'
,   name         => 'my_sql_profile'
,   profile_type => DBMS_SQLTUNE.PX_PROFILE
,   force_match  => true 
);
END;
/

						
22.3 Listing SQL Profiles

The data dictionary view DBA_SQL_PROFILES stores SQL profiles persistently in the database. The statistics are in an Oracle internal format, so you cannot query profiles directly. However, you can list profiles.

To list SQL profiles: 

        - 

Connect SQL*Plus to the database with the appropriate privileges, and then query the DBA_SQL_PROFILES view.

For example, execute the following query:

COLUMN category FORMAT a10
COLUMN sql_text FORMAT a20

SELECT NAME, SQL_TEXT, CATEGORY, STATUS
FROM   DBA_SQL_PROFILES;

Sample output appears below:

NAME                           SQL_TEXT             CATEGORY   STATUS
------------------------------ -------------------- ---------- --------
SYS_SQLPROF_01285f6d18eb0000   select promo_name, c DEFAULT    ENABLED
                               ount(*) c from promo
                               tions p, sales s whe
                               re s.promo_id = p.pr
                               omo_id and p.promo_c
                               ategory = 'internet'
                                group by p.promo_na
                               me order by c desc


								
22.4 Altering a SQL Profile

You can alter attributes of an existing SQL profile using the attribute_name parameter of the ALTER_SQL_PROFILE procedure.

The CATEGORY attribute determines which sessions can apply a profile. View the CATEGORY attribute by queryingDBA_SQL_PROFILES.CATEGORY. By default, all profiles are in the DEFAULT category, which means that all sessions in which theSQLTUNE_CATEGORY initialization parameter is set to DEFAULT can use the profile.

By altering the category of a SQL profile, you determine which sessions are affected by profile creation. For example, by setting the category toDEV, only sessions in which the SQLTUNE_CATEGORY initialization parameter is set to DEV can use the profile. Other sessions do not have access to the SQL profile and execution plans for SQL statements are not impacted by the SQL profile. This technique enables you to test a profile in a restricted environment before making it available to other sessions.

The example in this section assumes that you want to change the category of the SQL profile so it is used only by sessions with the SQL profile category set to TEST, run the SQL statement, and then change the profile category back to DEFAULT.

To alter a SQL profile: 

            1. 

Connect SQL*Plus to the database with the appropriate privileges, and then use the ALTER_SQL_PROFILE procedure to set theattribute_name.

For example, execute the following code to set the attribute CATEGORY to TEST:

VARIABLE pname my_sql_profile
BEGIN DBMS_SQLTUNE.ALTER_SQL_PROFILE ( 
   name            =>  :pname
,  attribute_name  =>  'CATEGORY'
,  value           =>  'TEST'      
);
END;
            2. 

Change the initialization parameter setting in the current database session.

For example, execute the following SQL:

ALTER SESSION SET SQLTUNE_CATEGORY = 'TEST';
            3. 

Test the profiled SQL statement.

            4. 

Use the ALTER_SQL_PROFILE procedure to set the attribute_name.

For example, execute the following code to set the attribute CATEGORY to DEFAULT:

VARIABLE pname my_sql_profile
BEGIN 
  DBMS_SQLTUNE.ALTER_SQL_PROFILE ( 
     name            =>  :pname
,    attribute_name  =>  'CATEGORY'
,    value           =>  'DEFAULT'   
);
END;
22.5 Dropping a SQL Profile

You can drop a SQL profile with the DROP_SQL_PROFILE procedure.

Assumptions

This section assumes the following:

            - 

You want to drop my_sql_profile.

            - 

You want to ignore errors raised if the name does not exist.

To drop a SQL profile: 

            - 

Connect SQL*Plus to the database with the appropriate privileges, call the DBMS_SQLTUNE.DROP_SQL_PROFILE procedure.

The following example drops the profile named my_sql_profile:

BEGIN
  DBMS_SQLTUNE.DROP_SQL_PROFILE ( 
    name => 'my_sql_profile' 
);
END;
/
										
22.6 Transporting a SQL Profile

You can transport SQL profiles. This operation involves exporting the SQL profile from the SYS schema in one database to a staging table, and then importing the SQL profile from the staging table into another database. You can transport a SQL profile to any Oracle database created in the same release or later.

Table 22-1 shows the main procedures and functions for managing SQL profiles.

Table 22-1 APIs for Transporting SQL Profiles

Procedure or Function Description

CREATE_STGTAB_SQLPROF

Creates the staging table used for copying SQL profiles from one system to another.

PACK_STGTAB_SQLPROF

Moves profile data out of the SYS schema into the staging table.

UNPACK_STGTAB_SQLPROF

Uses the profile data stored in the staging table to create profiles on this system.

The following graphic shows the basic workflow of transporting SQL profiles:


Description of the illustration tgsql_vm_066.png 
			

Assumptions

This tutorial assumes the following:

                - 

You want to transport my_profile from a production database to a test database.

                - 

You want to create the staging table in the dba1 schema.

To transport a SQL profile: 

                1. 

Connect SQL*Plus to the database with the appropriate privileges, and then use the CREATE_STGTAB_SQLPROF procedure to create a staging table to hold the SQL profiles.

The following example creates my_staging_table in the dba1 schema:

BEGIN
  DBMS_SQLTUNE.CREATE_STGTAB_SQLPROF ( 
    table_name  => 'my_staging_table'
,   schema_name => 'dba1' 
);
END;
/
                2. 

Use the PACK_STGTAB_SQLPROF procedure to export SQL profiles into the staging table.

The following example populates dba1.my_staging_table with the SQL profile my_profile:

BEGIN
  DBMS_SQLTUNE.PACK_STGTAB_SQLPROF (  
    profile_name         => 'my_profile'
,   staging_table_name   => 'my_staging_table'
,   staging_schema_owner => 'dba1' 
);
END;
/ 
                3. 

Move the staging table to the database where you plan to unpack the SQL profiles.

Move the table using your utility of choice. For example, use Oracle Data Pump or a database link.

                4. 

On the database where you plan to import the SQL profiles, use UNPACK_STGTAB_SQLPROF to unpack SQL profiles from the staging table.

The following example shows how to unpack SQL profiles in the staging table:

BEGIN
  DBMS_SQLTUNE.UNPACK_STGTAB_SQLPROF(
     replace            => true
,    staging_table_name => 'my_staging_table'
);
END;
/

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

相關文章