This is the presentation on ASH that I did with Graham Wood at RMOUG 2014 and that represents the final best effort to capture essential and advanced ASH content as started in a presentation Uri Shaft and I gave at a small conference in Denmark sometime in 2012 perhaps. The presentation is also available publicly through the RMOUG website, so I felt at liberty to post it myself here. If it disappears it would likely be because I have been asked to remove it by Oracle.
A presentation about new features and enhancements related to indexes and indexing in Oracle 12c.
See also the related post: http://db-oriented.com/2015/07/03/indexes-and-indexing-in-oracle-12c
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0Yury Velikanov
The document provides instructions for setting up a two-node Oracle 12c RAC environment within Oracle VirtualBox on a Windows laptop. The main steps include:
1. Configuring VirtualBox with a host-only network and installing Oracle Linux 6 on the first virtual machine.
2. Creating shared virtual disks for the ASM storage and installing Oracle Grid Infrastructure.
3. Cloning the first virtual machine to create the second node, and installing the Oracle 12c database software.
This allows users to test an Oracle 12c RAC sandbox environment locally without requiring additional physical hardware.
This document discusses several methods for moving data in and out of Oracle databases, including:
- Using directory objects and SQL*Loader to load data from external files
- Exporting and importing data between databases using Oracle Data Pump utilities like expdp and impdp
- Creating external tables to query data files in a platform-independent manner and move data without importing
It provides overviews and examples of how to use each method, focusing on SQL*Loader, Data Pump, and external tables. It also covers related topics like performance optimization and monitoring Data Pump jobs.
This document discusses managing undo data in Oracle databases. It defines undo data as copies of original data captured during transactions to support rollback, read consistency, and recovery. It describes how undo data is stored in undo segments within an undo tablespace and contrasts undo with redo data. The document provides guidance on monitoring undo usage, configuring undo retention time, guaranteeing undo availability, and using the Undo Advisor to size undo tablespaces appropriately.
This document discusses how Oracle manages data concurrency using locks. It describes how Oracle applies row-level locks by default to allow for high concurrency. It also discusses how to identify and resolve locking conflicts, including dealing with deadlocks which Oracle automatically detects and resolves by terminating one of the transactions.
This document discusses managing undo data in Oracle databases. It defines undo data as a copy of original data captured for every transaction that changes data. Undo data is stored in undo segments located in an undo tablespace and is used to support rollback operations, read-consistent queries, and Flashback features. It describes how to configure and guarantee undo retention, monitor undo data usage, and use the Undo Advisor to calculate optimal undo tablespace sizing.
How oracle 12c flexes its muscles against oracle 11g r2 finalAjith Narayanan
The document summarizes the new high availability features introduced in Oracle 12c, including Flex Cluster and Flex ASM. A Flex Cluster allows for hub and leaf nodes, where leaf nodes do not require direct access to shared storage. Flex ASM runs Automatic Storage Management (ASM) on fewer nodes, allows for larger disk groups, and isolates ASM traffic to improve performance. The new features provide more flexibility, scalability and ease of management for high availability.
El documento compara las arquitecturas de Oracle Database 11g y 12c. La principal diferencia es que 12c introduce el concepto de Container Database (CDB) y Pluggable Database (PDB), lo que permite agrupar múltiples bases de datos en una sola instancia. También describe las reglas para el manejo de usuarios, roles y privilegios entre el nivel común (CDB) y local (PDB).
The document describes setting up a two-node Oracle 12c RAC cluster on two Oracle Linux VMs hosted on Oracle VirtualBox. Key steps include:
1. Installing Oracle Linux on VirtualBox and preparing it for the Oracle installation. This includes installing VirtualBox additions, configuring storage and networks, and disabling unnecessary services.
2. Cloning the first node VM to create an identical second node and reconfiguring its storage, networking and hostname.
3. Configuring DNS and hosts files on both nodes to resolve virtual IPs, scan name, and establish connectivity.
4. Installing Oracle Grid Infrastructure for a cluster using the Oracle installer, configuring SCAN name, adding the second
1) The document provides an overview of date and time data types in Oracle databases and how to work with date ranges and temporal validity.
2) It demonstrates how Oracle 12c introduces the concept of "periods" to represent date ranges as well as automatic hidden columns and query syntax to work with temporal data.
3) The presenter then discusses ways developers can enhance temporal functionality, such as adding temporal constraints, indexing for performance, and writing queries to find gaps, merge overlapping ranges, and join on intersecting date ranges.
The document discusses upgrading, migrating, and consolidating to Oracle Database 12c. It provides an introduction to preparation steps, upgrade/migration/consolidation options, fallback strategies, and new features in 12c. It also references Oracle's support policies and resources available to help customers upgrade to the latest version.
This document provides information about Pythian, a company that provides database management and consulting services. It begins by introducing the presenter, Christo Kutrovsky, and his background. It then provides details about Pythian, including that it was founded in 1997, has over 200 employees, 200 customers worldwide, and 5 offices globally. It notes Pythian's partnerships and awards. The document emphasizes Pythian's expertise in Oracle, SQL Server, and other technologies. It positions Pythian as a recognized leader in database management.
Benchmarking Oracle I/O Performance with Orion by Alex GorbachevAlex Gorbachev
Orion is a tool for benchmarking Oracle I/O performance. It generates I/O workloads similar to database patterns and measures I/O performance. Orion stresses the I/O subsystem without significant CPU usage. It collects multiple data points by running tests with varying levels of concurrent small and large I/Os. Orion is useful for infrastructure tuning when requirements are unknown, and for capacity planning when requirements are known.
The document discusses Oracle 12c's new "multi-process multi-threaded" model. This new feature allows Oracle database processes on Linux/Unix systems to run as operating system threads rather than processes. This reduces resource consumption by eliminating redundant memory and CPU usage from separate processes. Background processes and local client connections now run as threads within larger processes. Remote clients still use dedicated processes that connect via a connection broker thread.
The document describes the steps to configure Oracle sharding in an Oracle 12c environment. It includes installing Oracle software on shardcat, shard1, and shard2 nodes, creating an SCAT database, installing the GSM software, configuring the shard catalog, registering the shard nodes, creating a shard group and adding shards, deploying the shards to create databases on shard1 and shard2, verifying the shard configuration, creating a global service, and creating a sample schema and shard table to verify distribution across shards.
Oracle 12c New Features For Better PerformanceZohar Elkayam
This document discusses new features in Oracle 12c that improve database performance. It begins with an introduction of the speaker and their company Brillix. The document then covers Oracle Database In-Memory Column Store introduced in 12.1, which allows both row and column format data access. Oracle 12.2 introduced Sharded Database Architecture for horizontal scaling across multiple databases. Additional optimizer changes in 12c such as adaptive query optimization and dynamic statistics are also summarized.
The document provides an overview of new features in Oracle Database 12c for developers and DBAs. It begins with introductions and background about the presenter, Alex Zaballa. The presentation then covers many new 12c features such as pluggable databases, data redaction, JSON support, and improved availability, security, and manageability capabilities. Code examples and demos are provided to illustrate several of the new features.
This presentation talks about the different ways of getting SQL Monitoring reports, reading them correctly, common issues with SQL Monitoring reports - and plenty of Oracle 12c-specific improvements!
Oracle 12c Parallel Execution New FeaturesRandolf Geist
This document discusses new parallel execution features introduced in Oracle 12c. It begins with an introduction to key aspects of parallel execution, including the producer-consumer model and data distribution skew. The document then covers major new 12c features such as hybrid hash distribution, concurrent UNION ALL, and the 1 slave distribution method. It concludes with a question and answer section.
El documento compara las arquitecturas de Oracle Database 11g y 12c. La principal diferencia es que 12c introduce el concepto de Container Database (CDB) y Pluggable Database (PDB), lo que permite agrupar múltiples bases de datos en una sola instancia. También describe las reglas para el manejo de usuarios, roles y privilegios entre el nivel común (CDB) y local (PDB).
The document describes setting up a two-node Oracle 12c RAC cluster on two Oracle Linux VMs hosted on Oracle VirtualBox. Key steps include:
1. Installing Oracle Linux on VirtualBox and preparing it for the Oracle installation. This includes installing VirtualBox additions, configuring storage and networks, and disabling unnecessary services.
2. Cloning the first node VM to create an identical second node and reconfiguring its storage, networking and hostname.
3. Configuring DNS and hosts files on both nodes to resolve virtual IPs, scan name, and establish connectivity.
4. Installing Oracle Grid Infrastructure for a cluster using the Oracle installer, configuring SCAN name, adding the second
1) The document provides an overview of date and time data types in Oracle databases and how to work with date ranges and temporal validity.
2) It demonstrates how Oracle 12c introduces the concept of "periods" to represent date ranges as well as automatic hidden columns and query syntax to work with temporal data.
3) The presenter then discusses ways developers can enhance temporal functionality, such as adding temporal constraints, indexing for performance, and writing queries to find gaps, merge overlapping ranges, and join on intersecting date ranges.
The document discusses upgrading, migrating, and consolidating to Oracle Database 12c. It provides an introduction to preparation steps, upgrade/migration/consolidation options, fallback strategies, and new features in 12c. It also references Oracle's support policies and resources available to help customers upgrade to the latest version.
This document provides information about Pythian, a company that provides database management and consulting services. It begins by introducing the presenter, Christo Kutrovsky, and his background. It then provides details about Pythian, including that it was founded in 1997, has over 200 employees, 200 customers worldwide, and 5 offices globally. It notes Pythian's partnerships and awards. The document emphasizes Pythian's expertise in Oracle, SQL Server, and other technologies. It positions Pythian as a recognized leader in database management.
Benchmarking Oracle I/O Performance with Orion by Alex GorbachevAlex Gorbachev
Orion is a tool for benchmarking Oracle I/O performance. It generates I/O workloads similar to database patterns and measures I/O performance. Orion stresses the I/O subsystem without significant CPU usage. It collects multiple data points by running tests with varying levels of concurrent small and large I/Os. Orion is useful for infrastructure tuning when requirements are unknown, and for capacity planning when requirements are known.
The document discusses Oracle 12c's new "multi-process multi-threaded" model. This new feature allows Oracle database processes on Linux/Unix systems to run as operating system threads rather than processes. This reduces resource consumption by eliminating redundant memory and CPU usage from separate processes. Background processes and local client connections now run as threads within larger processes. Remote clients still use dedicated processes that connect via a connection broker thread.
The document describes the steps to configure Oracle sharding in an Oracle 12c environment. It includes installing Oracle software on shardcat, shard1, and shard2 nodes, creating an SCAT database, installing the GSM software, configuring the shard catalog, registering the shard nodes, creating a shard group and adding shards, deploying the shards to create databases on shard1 and shard2, verifying the shard configuration, creating a global service, and creating a sample schema and shard table to verify distribution across shards.
Oracle 12c New Features For Better PerformanceZohar Elkayam
This document discusses new features in Oracle 12c that improve database performance. It begins with an introduction of the speaker and their company Brillix. The document then covers Oracle Database In-Memory Column Store introduced in 12.1, which allows both row and column format data access. Oracle 12.2 introduced Sharded Database Architecture for horizontal scaling across multiple databases. Additional optimizer changes in 12c such as adaptive query optimization and dynamic statistics are also summarized.
The document provides an overview of new features in Oracle Database 12c for developers and DBAs. It begins with introductions and background about the presenter, Alex Zaballa. The presentation then covers many new 12c features such as pluggable databases, data redaction, JSON support, and improved availability, security, and manageability capabilities. Code examples and demos are provided to illustrate several of the new features.
This presentation talks about the different ways of getting SQL Monitoring reports, reading them correctly, common issues with SQL Monitoring reports - and plenty of Oracle 12c-specific improvements!
Oracle 12c Parallel Execution New FeaturesRandolf Geist
This document discusses new parallel execution features introduced in Oracle 12c. It begins with an introduction to key aspects of parallel execution, including the producer-consumer model and data distribution skew. The document then covers major new 12c features such as hybrid hash distribution, concurrent UNION ALL, and the 1 slave distribution method. It concludes with a question and answer section.
#RuPostgresLive 4: как писать и читать сложные SQL-запросыNikolay Samokhvalov
Онлайн-опросы неизменно показывают — всех нас очень интересуют две вещи: а) как писать наиболее эффективные SQL-запросы, б) как «читать» такие запросы, а точнее, как понимать, что именно делает или будет делать СУБД при их выполнении.
Эти две неразрывно связанные друг с другом темы чрезвычайно обширны, SQL-искусству можно (и нужно) учиться годами. Во время нашей очередной встречи в прямом эфире мы затронем некоторые аспекты обеих.
ЧАСТЬ 1: EXPLAIN
Алексей Ермаков. Как читать и интерпретировать вывод команды EXPLAIN
Команда EXPLAIN — основной инструмент анализа запросов, позволяющий разобраться, каким образом запрос будет выполняться и как можно его ускорить. Для сложных запросов вывод может быть довольно громоздким и его становится сложно читать. Я расскажу, из каких частей состоит план запроса, на какие «маркеры» в нём следует обращать внимание в первую очередь и как на это реагировать.
ЧАСТЬ 2: ADVANCED SQL
Николай Самохвалов. SQL современный и «продвинутый»
«Я не волшебник, я только учусь». Продвинутому SQL нас постоянно учат такие видные гуру как Markus Winand и Макс Богук. Рекурсивные CTE, LATERAL JOIN, виртуозная работа с массивами и строками, window functions и прочие модные штучки, которые помогут вам в дрессировке вашего Постгреса, — я постараюсь сделать хороший обзор, а если вдруг тема покажется интересной, то в следующих сеансах группового Постгреса мы обязательно пригласим настоящих гуру :)
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"Technopark
Технопарк Mail.ru Group, МГТУ им. Н.Э. Баумана. Курс "Базы данных".
Лекция №7 "Оптимизация запросов и индексирование". Лектор - Павел Щербинин.
Вначале рассказывается об оптимизации доступа к данным, о декомпозиции соединения и состоянии запроса. Далее идёт большой блок, посвящённый оптимизатору запросов (изменение порядка соединения, применение алгебраических правил эквивалентности, оптимизации COUNT(), MIN(), MAX(), вычисление и свертка константных выражений, покрывающие индексы, оптимизация подзапросов, раннее завершение, сравнение по списку IN() и распространение равенства). Затем последовательно рассматриваются такие вещи, как соединение (JOIN) в MySQL, оптимизатор сортировки, коррелированные подзапросы, слияние и непоследовательный просмотр индексов, функции SELECT & UPDATE, COUNT(). После этого рассказывается об оптимизации запросов с помощью JOIN, GROUP BY, DISTINCT и LIMIT со смещением. В конце лекции даётся информация о кэшировании запросов, объединённых таблицах и секционировании.
Видео лекции курса https://www.youtube.com/playlist?list=PLrCZzMib1e9obOz5K695ugYuiOOCBciEi
2. Концепции оптимизации
RULE -> Cost -> Adaptive Query Optimization (AQO?)
RBO
с начала времён
CBO
Oracle 7+
Adaptive Query Optimization 12c
11.2
+ Cardinality Feedback
+ Adaptive Cursor Sharing
+ ADS
12c+9+ Dynamic Sampling
11.2+ ADS
12c ADSВ начале было RULE, на смену пришёл CBO
В 12c работает Adaptive Query Optimizer, для которого Cost уже не играет определяющего
значения при выборе плана (если, конечно, не отключать Adaptive Features & ADS:)
3. Первые эксперименты с Automatic Dynamic Statistics в версии 11.2 - Different Level
for Dynamic Statistics (Dynamic Sampling) used than the Level Specified (Doc ID
1102413.1)*
Начиная с версии 12c, ADS – в «промышленной эксплуатации» и наиболее
структурировано причины использования ADS сформулированы в документе
Automatic Dynamic Statistics (Doc ID 2002108.1) (ранее называвшемся Dynamic
Sampling Level Is Changed Automatically in 12C)
… if dynamic statistics are enabled, then the optimizer automatically decides:**
1. Whether dynamic statistics are useful
2. What level to use
Automatic Dynamic Statistics
*) появление ADS в 11.2, вероятно, связано с первым появлением адаптивных технологий: Cardinality
Feedback, Adaptive Cursor Sharing
**) судя по определению, важно понимать, в каких случаях ADS enabled
4. Когда ADS enabled: неадаптивный ADS
Automatic Dynamic Statistics are enabled when any of the following conditions are true:
1. The OPTIMIZER_DYNAMIC_SAMPLING initialization parameter is set to the default
value or … to 11 (i.e. any value other than the default or 11 disables ADS)*
2. Dynamic statistics is invoked through a SQL hint
3. The query will run in parallel
4. The query was executed before and its history is available (from the cursor cache,
Automatic Workload Repository, or the SQL Management Base)
- эта часть Automatic Dynamic Sampling соответствует значению
OPTIMIZER_DYNAMIC_SAMPLING = 11 и доступна, начиная с 11.2.0.4
*) any value other than the default or 11 disables non-adaptive ADS* - так будет
правильнее, а то, что адаптивный ADS (вызванный применением SQL Plan Directive)
не отключается изменением параметра OPTIMIZER_DYNAMIC_SAMPLING - легко
проверить и получить в 10053 трейсе:
** Not using old style dynamic sampling since ADS is enabled.
>> Index Card adjusted from 130998.393291 to 3659.000000 due to adaptive
dynamic sampling
В вышеперечисленных случаях, ADS enabled без какой-либо связи с Adaptive Optimization,
соответственно, может быть обозначен как неадаптивная часть ADS
5. • Missing statistics
• Stale statistics
...when 10% or more of the rows in the table have changed...
• Insufficient statistics
Statistics can be insufficient whenever the optimizer estimates
the selectivity of predicates (filter or join) or the GROUP BY
clause without taking into account correlation between columns,
skew in the column data distribution, statistics on expressions,
and so on...
The optimizer can use dynamic statistics to compensate for the
lack of extended statistics or when it cannot use extended
statistics, for example, for non-equality predicates
Когда ADS enabled: неадаптивный ADS-2
В этих случаях ADS enabled в зависимости от состояния статистики и оценок оптимизатора, добавлена
Insufficient Statistics – опять же без связи с 12c Adaptive Features – т.е. также неадаптивный ADS
6. Когда ADS enabled: адаптивный ADS
Automatic Dynamic Sampling can be triggered during Adaptive Query Optimization as
follows:
1. ADS can trigger if optimizer finds the incorrect cardinality estimates (whether the
SQL statements are executed repeatedly or not)
2. ADS can also trigger if adaptive plans are used for the SQLs
3. ADS can trigger for SQL statements that are submitted for automatic re-
optimization as part of ADAPTIVE STATISTICS
(цикл Statistics Feedback => Automatic re-optimization => SQL Plan directives =>
ADS)
А в этих случаях ADS включается через 12c Adaptive Features:
• incorrect cardinality в процессе выполнения
• Применение Adaptive plan
• Automatic Reoptimization как части Adaptive Statistics
– эту часть условно можно назвать адаптивным ADS
7. 12c Automatic Reoptimization / Statistics Feedback
(11g Cardinality Feedback)
SQL> select * from GV$SQL_REOPTIMIZATION_HINTS where rownum <= 1;
SQL_ID CHILD_NUMBER HINT_ID HINT_TEXT REPARSE
------------- ------------ ------- ------------------------------------------------------- -------
cg2vx7c76w01h 1 2 OPT_ESTIMATE (@"SEL$3" TABLE "R"@"SEL$3" MIN=3.000000 ) 1
SQL> select distinct regexp_substr(hint_text, '[^ ]+', 1, 1) as HINT,
2 regexp_substr(hint_text, '[^ ]+', 1, 3) as IDENTIFIER,
3 regexp_substr(hint_text, '( )([A-Z_]+)(=)', 1, 1) as ADJUSTMENT
4 from GV$SQL_REOPTIMIZATION_HINTS
5 order by 1, 2, 3
6 /
HINT IDENTIFIER ADJUSTMENT
------------------ ------------------ ----------
OPT_ESTIMATE GROUP_BY ROWS=
OPT_ESTIMATE INDEX_FILTER MIN=
OPT_ESTIMATE INDEX_FILTER ROWS=
OPT_ESTIMATE INDEX_SCAN MIN=
OPT_ESTIMATE JOIN MIN=
OPT_ESTIMATE JOIN ROWS=
OPT_ESTIMATE JOIN
OPT_ESTIMATE QUERY_BLOCK ROWS=
OPT_ESTIMATE TABLE MIN=
OPT_ESTIMATE TABLE ROWS=
10 rows selected
Note
-----
- statistics feedback used for this statement -- никакого ADS ещё не применяется
Эта первая часть ADAPTIVE STATISTICS представляет собой
фактически сохранённую в памяти статистику плана
выполнения, для ограниченного набора операций для
конкретных дочерних курсоров (запрос №1)
Диапазон используемых хинтов – (запрос №2)
Данные только из статистики плана выполнения, хранятся в
SGA, ADS пока не используется
NOTE отражает состояние до создания SQL Plan Directive
8. SQL Plan Directives
SQL> select distinct f.type as FINDING_TYPE,
2 d.type as DIRECTIVE_TYPE,
3 f.reason as FINDING_REASON,
4 d.internal_state as INTERNAL_STATE,
5 case when d.internal_state = 'HAS_STATS' or d.redundant = 'YES' then 'SUPERSEDED'
6 when d.internal_state in ('NEW', 'MISSING_STATS', 'PERMANENT') then 'USABLE'
7 else 'UNKNOWN'
8 end as STATE
9 from sys."_BASE_OPT_DIRECTIVE" d
10 join sys."_BASE_OPT_FINDING" f on f.f_id = d.f_id
11 join sys."_BASE_OPT_FINDING_OBJ" fo on f.f_id = fo.f_id
12 order by 3,4,5
13 /
FINDING_TYPE DIRECTIVE_TYPE FINDING_REASON INTERNAL_STAT STATE
---------------------- ---------------- ------------------------------------ ------------- ----------
OPTIMIZER_BAD_DECISION DYNAMIC_SAMPLING GROUP BY CARDINALITY MISESTIMATE HAS_STATS SUPERSEDED
MISSING_STATS USABLE
NEW USABLE
PERMANENT USABLE
JOIN CARDINALITY MISESTIMATE HAS_STATS SUPERSEDED
MISSING_STATS USABLE
NEW USABLE
PERMANENT USABLE
SINGLE TABLE CARDINALITY MISESTIMATE HAS_STATS SUPERSEDED
MISSING_STATS USABLE
NEW USABLE
PERMANENT SUPERSEDED
PERMANENT USABLE
12 rows selected
В тексте запроса перечислены системные
таблицы с данными SQL Plan Directives –
концепция from-Finding-to-Directive
Рез-т запроса показывает весь наблюдаемый
набор возможных типов, причин создания и
состояний (внутренних и отображаемых) SPD
версии 12.1.0.2
Подробнее – у FRANC Pachot, точно
назвавшего SPD “памятью оптимизатора”
9. SQL Plan Directives
SQL> select distinct xml.column_value.getrootelement() nodes
2 from sys."_BASE_OPT_FINDING_OBJ" fo,
3 table(xmlsequence(fo.notes.extract('/obj_note/node()'))) xml
4 /
NODES
--------------------------------------------------------------------------------
filter_on_joining_object
simple_column_predicates_only
index_access_by_join_predicates
equality_predicates_only
4 rows selected
SQL> @spd_id "9921535714750699160,17120775226972789474"
DIRECTIVE_ID INT_STATE STATE REASON TAB_CNT TABLE_LIST COLUMN_LIST FILTER_ON_JOIN_OBJ
-------------------- --------- ---------- ---------------------------- ------- -------------------- ----------- ------------------
17120775226972789474 PERMANENT USABLE JOIN CARDINALITY MISESTIMATE 5 SCOTT.MV_OVER_EMP,.. YES
9921535714750699160 HAS_STATS SUPERSEDED JOIN CARDINALITY MISESTIMATE 7 SCOTT.MV_OVER_EMP,.. YES
SQL> @spd_obj SCOTT MV_OVER_EMP USABLE
DIRECTIVE_ID SPD_TYPE ENABLED INT_STATE STATE REASON TAB_CNT
---------------------- ---------------- ------- ---------------- ---------- ------------------------------------ ----------
18417925785821304475 DYNAMIC_SAMPLING YES NEW USABLE GROUP BY CARDINALITY MISESTIMATE 12
18406375706293258490 DYNAMIC_SAMPLING YES NEW USABLE GROUP BY CARDINALITY MISESTIMATE 12
18165540409165880262 DYNAMIC_SAMPLING YES PERMANENT USABLE JOIN CARDINALITY MISESTIMATE 7
18088459888625459118 DYNAMIC_SAMPLING YES PERMANENT USABLE JOIN CARDINALITY MISESTIMATE 7
17919466334120712154 DYNAMIC_SAMPLING YES NEW USABLE GROUP BY CARDINALITY MISESTIMATE 12
17916891119674459555 DYNAMIC_SAMPLING YES PERMANENT USABLE JOIN CARDINALITY MISESTIMATE 6
17719211294898367296 DYNAMIC_SAMPLING YES PERMANENT USABLE JOIN CARDINALITY MISESTIMATE 3
...
144 rows selected 1-й запрос показывает типы доп.информации, указываемой для SPD 12.1.0.2
2-й запрос – пример применения SPD_ID.SQL для вывода данных по DIRECTIVE_ID (или списку
директив)
3-й запрос просто демонстрирует на практическом примере кол-во директив, созданных для
одной таблицы – и это не максимальное кол-во!
10. SPD: особенности и проблемы
• Объектная ориентированность - на таблицы/столбцы/операции, без связи с SQL_ID, слабая диагностика и
управляемость на уровне запроса:
OPT_PARAM('_optimizer_dsdir_usage_control' 0) -- отключить ВСЕ директивы для запроса
OR –- для отключения конкретной директивы для ВСЕХ запросов:
SQL> exec DBMS_SPD.ALTER_SQL_PLAN_DIRECTIVE (&dir_id, 'ENABLED','NO')
- нет простой возможности найти все курсоры, использующие конкретную директиву
• Bug 19450314 - Unnecessary compiled PL/SQL invalidations in 12c*– исправлен в январском PSU
• Кроме возможного общего влияния на производительность, для ADS запросов порождает запросы типа SQL_ID
«frjd8zfy2jfdq» (The query with SQLID frjd8zfy2jfdq is executed by Dynamic Statistics to figure out the past execution
statistics and guide the time allowance for future execution of Dynamic Statistics):
1. Frequent Execution of SQL_ID «frjd8zfy2jfdq» in 12.1.0.2 (Doc ID 2059121.1) рекомендует регулировать
_optimizer_dsdir_usage_control=0
2. High Version Count
3. выполняется по RULE правилам на уровне сессии
4. на один CHILD_NUMBER в V$SQL может приходиться по несколько записей с разными CHILD_ADDRESS (!)
5. ADG: Bug 22364629 : EXADATA: ORA-29771: PROCESS USER BLOCKS LGWR FOR MORE THAN 70 SECONDS -> Bug
20413540 - Excessive executions of SQL frjd8zfy2jfdq (Doc ID 20413540.8)
LGWR (ospid: 10005) has not moved for 20 sec (1466006083.1466006063)
...
: waiting for event 'library cache lock' for 19 secs with wait_id 502.
===[ Wait Chain ]===
LGWR (ospid: 10005) waits for event 'library cache lock'.
USER (ospid: 10375) waits for event 'PX Deq: Parse Reply'.
PPA7 (ospid: 10377) waits for event 'library cache lock'.
LGWR (ospid: 10005) waits for event 'library cache lock'.
A cycle is detected.
• Необходимость импортировать statistics+directives (для директив в статусе HAS_STATS)
• SPD имеют единственный Directive_Type = Automatic Dynamic Sampling , что порождает «адаптивный» ADS +
автоматическое создание Extended Statistics во время Automatic Optimizer Statistics Collection, что может менять
DBA_TABLES.LAST_DDL_TIME и приводить к массовой PL/SQL invalidation*)
11. Запросы с использованием ADS в реальной системе
SQL> select case
2 when p.other_xml is null then 'no_plan'
3 when instr(p.other_xml,'<info type="dynamic_sampling" note="y">') > 0 then 'with_ADS'
4 else 'no_ADS'
5 end as "SQL Type",
6 case when REGEXP_SUBSTR(dbms_lob.substr(p.other_xml,4000),'<(cu)>([^<]+)</1>',1,1,NULL,2) > 0 then 'SPD_Used'
7 else 'SPD_not_Used'
8 end as "SPD",
9 sum(s.executions),
10 to_char(RATIO_TO_REPORT(sum(s.executions)) OVER() * 100, '990.99') as "EXECS PerCent"
11 from gv$sql s
12 left join gv$sql_plan p
13 on s.inst_id = p.inst_id
14 and s.sql_id = p.sql_id
15 and s.plan_hash_value = p.plan_hash_value
16 and s.child_address = p.child_address
17 and p.other_xml is not null
18 where s.sql_text not like 'SELECT /* DS_SVC */%'
19 group by case
20 when p.other_xml is null then 'no_plan'
21 when instr(p.other_xml,'<info type="dynamic_sampling" note="y">') > 0 then 'with_ADS'
22 else 'no_ADS'
23 end,
24 case when REGEXP_SUBSTR(dbms_lob.substr(p.other_xml,4000),'<(cu)>([^<]+)</1>',1,1,NULL,2) > 0 then 'SPD_Used'
25 else 'SPD_not_Used'
26 end
27 /
SQL Type SPD SUM(S.EXECUTIONS) EXECS PerCent
-------- ------------ ----------------- -------------
no_ADS SPD_not_Used 4841172545 46.08 -– запросы, не использующие ADS
no_plan SPD_not_Used 472229268 4.49 –- запросы без плана в SGA
with_ADS SPD_Used 4490346466 42.74 –- используют SPD и ADS (адаптивный)
with_ADS SPD_not_Used 702564089 6.69 -- ADS без SPD (неадаптивный ADS?)
Сравнение выполнений запросов с/без ADS получена из V$SQL, поскольку в ASH/AWR ADS запросы не попадают
Интересны последние 2 строки: запросы с адаптивным ADS (with_ADS+SPD_Used) > 42%, неадаптивный ADS > 6+%
12. Note -- Adaptive Statistics ADS
-----
- dynamic statistics used: dynamic sampling (level=2)
- 17 Sql Plan Directives used for this statement
Note -- «Simple» non-Adaptive ADS
-----
- dynamic statistics used: dynamic sampling (level=2)
SQL> select case when sql_text like 'SELECT /* DS_SVC */%' then 'ADS_sql'
2 when sql_text like 'SELECT /* OPT_DYN_SAMP */%' then 'Old_Style_DS'
3 else 'Regular_sql' end as SQL_TYPE,
4 sum(elapsed_time) as "Elapsed_uS",
5 to_char(RATIO_TO_REPORT(sum(elapsed_time)) OVER()*100,'990.99') as "ELA PerCent",
6 to_char(RATIO_TO_REPORT(sum(user_io_wait_time)) OVER()*100,'990.99') as "I/O PerCent"
7 from gv$sqlstats
8 group by case when sql_text like 'SELECT /* DS_SVC */%' then 'ADS_sql'
9 when sql_text like 'SELECT /* OPT_DYN_SAMP */%' then 'Old_Style_DS'
10 else 'Regular_sql' end
11 /
SQL_TYPE Elapsed_uS ELA PerCent I/O PerCent
------------ ---------- ----------- -----------
ADS_sql 3487969762 1.33 2.91 -- frjd8zfy2jfdq реально работает!
Old_Style_DS 14203103 0.00 0.00
Regular_sql 2580336515 98.67 97.09
Запросы с использованием ADS -2
Распределение долей DB Time (Elapsed) и
I/O между пользовательскими запросами,
запросами ADS и Old Style DS (версии до
12c)
13. Automatic Dynamic Sampling vs Old Style Dynamic Sampling
SQL> select
Note
-----
- dynamic statistics used: dynamic sampling (level=2)
- 3 Sql Plan Directives used for this statement
SQL> select --+ DYNAMIC_SAMPLING(10)
Note
-----
- dynamic statistics used: dynamic sampling (level=10) –- incorrect! *
- 3 Sql Plan Directives used for this statement
*) Christian Antognini -> SR: V$SQL_PLAN.OTHER_XML Can Contain Wrong Dynamic Sampling Level
Комментарий из 10053 трейса:
** Not using old style dynamic sampling since ADS is enabled. -- old style DS **
Применение в запросе ADS (ADS enabled) несовместимо с Old Style Dynamic Sampling, управляемым через
DYNAMIC_SAMPLING / OPTIMIZER_DYNAMIC_SAMPLING, изменение последних может ошибочно отражаться в выводе
DBMS_XPLAN.DISPLAY_CURSOR (*), однако тип и уровень DS при этом не меняется, что следует из трейса оптимизатора (**)
14. Возможности управления адаптивным ADS
optimizer_adaptive_features true/false:
• OPT_PARAM('_optimizer_adaptive_plans' 'true'/'false')
/*+ [NO_]ADAPTIVE_PLAN */
– OPT_PARAM('_optimizer_nlj_hj_adaptive_join' 'true'/'false')
– OPT_PARAM('_px_adaptive_dist_method' 'on'/'off')
• OPT_PARAM('_optimizer_gather_feedback' 'true'/'false')
• OPT_PARAM('_optimizer_use_feedback' 'true'/'false')
• OPT_PARAM('_optimizer_dsdir_usage_control' 126/0)
• OPT_PARAM('_optimizer_strans_adaptive_pruning' 'true'/'false')
ADS, порождённый Адаптивной оптимизацией (наиболее вероятно) управляется только косвенно через параметры, управляющие
всеми или отдельными Adaptive Features 12c
15. Управление DS
Отключение всех видов DS:
/*+ DYNAMIC_SAMPLING ( [@query_block] [tablespec] 0 ) */ -- ненадёжно в 12.1.0.2
or OPT_PARAM('optimizer_dynamic_sampling' 0)
При необходимости возвращения к Old Style Dynamic Sampling в дополнение к старому доброму уровню
OPTIMIZER_DYNAMIC_SAMPLING потребуется отключить источник ADS одним из способов:
• opt_param('_OPTIMIZER_DSDIR_USAGE_CONTROL' 0) – SPD, как наиболее вероятную причину
• opt_param('OPTIMIZER_ADAPTIVE_FEATURES' 'false') – если это Adaptive ADS
• OPTIMIZER_FEATURES_ENABLE('11.2.0.4') – надёжно!
- что приведёт к генерации в процессе DS запросов «старого типа»:
** Generated dynamic sampling query:
query text :
SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS IGNORE_WHERE_CLAUSE NO_PARALLEL(SAMPLESUB)
opt_param('parallel_execution_enabled', 'false')…
** Executed dynamic sampling query:…
If OPTIMIZER_DYNAMIC_SAMPLING is set to 11, then Automatic Dynamic Statistics is enabled forever
irrespective of setting of the parameter OPTIMIZER_ADAPTIVE_FEATURES (соответственно при этом ADS
может быть Адаптивным или НЕ-Адаптивным)
Кроме отключения нет возможности управлять уровнями ADS, например, изменить или усилить
16. Первоисточники
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
http://docs.oracle.com/
https://support.oracle.com/
Christian Antognini. Adaptive Dynamic Sampling
Franck Pachot. SQL Plan Directives. The memory of the optimizer
Усольцев Игорь
https://iusoltsev.wordpress.com/
#5: Без привязки к ни к адаптивному выполнению, ни к ADAPTIVE STATISTICS
Неадаптивный ADS
#6: Одно из определений в документации
Расширение уровней классического ADS
#7: цепочка Statistics Feedback => Automatic re-optimization => SQL Plan directives => ADS прослеживается наиболее
адаптивный ADS
#8: Эта часть ADAPTIVE STATISTICS представляет фактически сохранённую в памяти статистику выполнения ограниченного набора операций для конкретных дочерних курсоров
Только из статистики плана выполнения, без ADS
NOTE отражает состояние до создания SPD
Без ADS
#9: Из чего состоят
Finding-Directive
Подробнее – у FRANC Pachot (память оптимизатора)
#10: Из чего состоят, на что указывают
Подробнее – у FRANC Pachot (память оптимизатора)
#11: Уровень объектов (не запросов) - можно отключить использование всех SPD для запроса, либо отключить SPD для всех запросов
SPD -> Extended Statistics (+virtual columns) -> DBA_TABLES.LAST_DDL_TIME -> dependencies
Frjd8zfy2jfdq – RO-standby
Time Limit query
#12: Вернёмся к ADS
EPR-система, часто, т.е. сталкиваться придётся
#14: Если попробовать для запроса с ADS изменить уровень ADS описанными в доке [OPTIMIZER_]DYNAMIC_SAMPLING
Судя по трейсу, Old Style Dynamic Sampling exists)
#15: Поскольку чаще всего имеем адаптивный ADS
Зачем управлять – есть ситуации, в которых, даже несмотря на правильные оценки ADS, CBO план предпочтительнее ввиду невозможности, например, отслеживать кэширование отдельных объектов/индексов; для стабильности планов и т.д.
ADS порождёный Адаптивной оптимизацией (чаще всего) управляется только косвенно через параметры, управляющие всеми или отдельными Adaptive Features 12c
#16: Если попробовать для запроса с ADS изменить уровень ADS описанными в доке [OPTIMIZER_]DYNAMIC_SAMPLING
Нет возможности повлиять на уровень OPTIMIZER_DYNAMIC_SAMPLING для ADS – на то он и автоматический)