lunes, 10 de noviembre de 2014

Automatic Tuning Optimizer

Cuando las sentencias SQL son ejecutadas por la base de datos Oracle, el optimizador de consultas es utilizado para generar los planes de ejecución
en dos modos: un modo normal y un modo de afinación.

En modo normal, el optimizador compila el codigo SQL y genera un plan de ejecución. El modo normal del optimizador genera un plan razonable de ejecución para la mayoría de sentencias SQL. Bajo modo normal, el optimizador opera con restricciones muy estrictas, generalmente una fracción de segundo, durante la cual debe encontrar un buen plan de ejecución.

En modo de afinación, el optimizador realiza un analisis adicional para revisar sí el plan de ejecución producido bajo modo normal puede ser mejorado aún más. La salida del optimizador de consultas no es un plan de ejecución, sino una serie de acciones, junto con sus beneficio racionales y esperados para producir un plan significativamente superior. Cuando se ejecuta en modo de afinación, el optimizador es referido como Automatic Tuning Optimizer.

Bajo modo de afinación, el optimizador puede tomar varios minutos para afinar un sentencia unica. Consume una gran cantidad de recursos y tiempo invocar el Automatic  Tuning Optimizer cada vez que una sentencia tiene que ser analizada. El Automatic Tuning Optimizer esta destinado a ser utilizado con sentencias SQL de alta carga de trabajo que no tienen un impacto trivial en el sistema entero. El Automatic Database Diagnostic Monitor (ADDM) identifica proactivamente las sentencias SQL con alta carga de trabajo las cuales son buenas candidatas para el afinador de SQL. Cuando las sentencias SQL son ejecutadas por la base de datos Oracle, el optimizador de consultas es utilizado para generar los planes de ejecución
en dos modos: un modo normal y un modo de afinación.

En modo normal, el optimizador compila el codigo SQL y genera un plan de ejecución. El modo normal del optimizador genera un plan razonable de ejecución para la mayoría de sentencias SQL. Bajo modo normal, el optimizador opera con restricciones muy estrictas, generalmente una fracción de segundo, durante la cual debe encontrar un buen plan de ejecución.

En modo de afinación, el optimizador realiza un analisis adicional para revisar sí el plan de ejecución producido bajo modo normal puede ser mejorado aún más. La salida del optimizador de consultas no es un plan de ejecución, sino una serie de acciones, junto con sus beneficio racionales y esperados para producir un plan significativamente superior. Cuando se ejecuta en modo de afinación, el optimizador es referido como Automatic Tuning Optimizer.

Bajo modo de afinación, el optimizador puede tomar varios minutos para afinar un sentencia unica. Consume una gran cantidad de recursos y tiempo invocar el Automatic  Tuning Optimizer cada vez que una sentencia tiene que ser analizada. El Automatic Tuning Optimizer esta destinado a ser utilizado con sentencias SQL de alta carga de trabajo que no tienen un impacto trivial en el sistema entero. El Automatic Database Diagnostic Monitor (ADDM) identifica proactivamente las sentencias SQL con alta carga de trabajo las cuales son buenas candidatas para el afinador de SQL.
https://docs.oracle.com/cd/B28359_01/server.111/b28274/sql_tune.htm#PFGRF02604

sábado, 8 de noviembre de 2014

Automatic Workload Repository

Automatic Workload Repository

Repositorio Automatico de carga de trabajo
El repositorio automatico de carga de trabajo es una colección de estadisticas persistentes del rendimiento del sistema que le pertenecen al usuario SYS. El repositorio automatico de carga de trabajo reside en el espacio de tablas  SYSAUX.

Un SNAPSHOT(imagen instantanea) es un conjunto de estadisticas de rendimiento capturadas en cierto tiempoo y guardadas en el repositorio automatico de carga de trabajo. Cada snapshot es identificado por un número de secuencia (snap_id) que es único en el AWR. Por defecto, los snapshots son generados cada 60 minutos. Puedes ajustar esta frecuencia cambiando el parametro de intervalo de snapshot. Porque los asesores de base de datos dependen de los snapshots, debes estar consiente que el ajuste del nivel puede afectar la precisión de diagnostico.

viernes, 7 de noviembre de 2014

Asesores de Oracle

Utilizando los asesores de Oracle

Obten consejos sobre retos clave de administración y mejora el rendimiento en Oracle Database 11g.

Los asesores son herramientas potentes que proveen un consejo especifico sobre como enfrentar retos clave
de administración, cubriendo una amplia variedad de areas, incluyendo espacio de almacenamiento, rendimiento,
y administración de undo. Los advisors estan construidos sobre dos componentes de la infraestructura.

El repositorio automatico de carga de trabajo (AWR). Este repositorio provee servicios para la recolección, mantenimiento, y utilización de estadisticas con el proposito de la detección de problemas y auto afinación.
La información estadistica es guardada en el repositorio AWR en forma de instantaneas(snapshots).

Automatic database diagnostic monitor (ADDM). Este monitor realiza analisis, detecta cuellos de botella, y recomienda soluciones. Las recomendaciones pueden incluir el tipo de asesores que pueden ser utilizados para
resolver le problema.

Este texto se centra en algunos de los asesores que son invocados por el ADDM para ayudar a mejorar el rendimiento de la base de datos. Presenta preguntas de muestra del tipo que podrias encontrar cuando presentas el examen Oracle Database 11g Administration Workshop I, el cual te permite ganar el nivel de certificación Oracle Certified Associate.

SQL tuning Advisor

El asesor de afinación SQL analiza problemas con sentencias SQL individuales, tales como un plan optimizador de mal desempeño o el uso equivocado de ciertas estructuras SQL, y hace recomendaciones para mejorar su desempeño.
Puede ejecutar el asesor de ajuste SQL contra las sentencias SQL que requieren muchos recursos.

Un conjunto de sentencias SQL durante un período de tiempo, o de una carga de trabajo SQL. Normalmente , se ejecuta este consejero en respuesta a un hallazgo rendimiento ADDM que recomienda su uso.

Oracle Database 11g introduce el asesor de afinación SQL automático , que puede ser configurado para ejecutarse de forma automática durante las ventanas de mantenimiento del sistema como una tarea de mantenimiento . Durante cada ejecución automática, el asesor selecciona consultas SQL de gran carga en el sistema y genera recomendaciones sobre cómo ajustarlas.

Juan empieza a crear una nueva tabla basada en los datos de la tabla de clientes . Los siguientes criterios deben aplicarse en los datos:

Todas las columnas de la tabla de clientes deben estar disponibles en la nueva tabla .
    La nueva tabla debe tener datos sólo para aquellos clientes cuyo pedido promedio es de US $ 1 millón o más por trimestre , que no han efectuado pagos correspondientes a los dos últimos pedidos , y cuyo plazo de pago ha superado el período de crédito.

sábado, 25 de octubre de 2014

Restore spfile from a backupset without dbid

restore spfile from '+fra/rcat/autobackup/2014_10_22/s_861663111.258.861663531';






STARTUP NOMOUNT
CREATE CONTROLFILE REUSE DATABASE "RCAT" NORESETLOGS  ARCHIVELOG
    MAXLOGFILES 16
    MAXLOGMEMBERS 3
    MAXDATAFILES 100
    MAXINSTANCES 8
    MAXLOGHISTORY 292
LOGFILE
  GROUP 1 '+DATA/rcat/redo01.log'  SIZE 50M BLOCKSIZE 512,
  GROUP 2 '+DATA/rcat/redo02.log'  SIZE 50M BLOCKSIZE 512,
  GROUP 3 '+DATA/rcat/redo03.log'  SIZE 50M BLOCKSIZE 512
DATAFILE
  '+DATA/rcat/system01.dbf',
  '+DATA/rcat/sysaux01.dbf',
  '+DATA/rcat/undotbs01.dbf',
  '+DATA/rcat/users01.dbf',
  '+DATA/rcat01.dbf'
CHARACTER SET AL32UTF8
;

domingo, 19 de octubre de 2014

Cambiar el tamaño de la Fast recovery area

Size in bytes
1 kb= 1024   bytes
1 mb= 1024^2 bytes
1 gb= 1024^3 bytes

SQL> select * from v$recovery_file_dest;

NAME
--------------------------------------------------------------------------------
SPACE_LIMIT SPACE_USED SPACE_RECLAIMABLE NUMBER_OF_FILES
----------- ---------- ----------------- ---------------
+FRA
 4259315712  268435456         0        9



SQL> show parameter recovery_file_dest_size;

NAME         TYPE  VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest_size      big integer 4062M

ALTER SYSTEM SET db_recovery_file_dest_size = 6442450944 SCOPE=BOTH;

viernes, 3 de octubre de 2014

Database Advisors

 Using Database Advisors

Get advice on key management challenges and improve performance in Oracle Database 11g.

Advisors are powerful tools that provide specific advice on how to address key database management challenges, covering a wide range of areas, including space, performance, and undo management. Advisors are built around two infrastructure components:

Automatic workload repository (AWR). This repository provides services for collecting, maintaining, and utilizing statistics for problem detection and self-tuning purposes. The statistical information is stored in the AWR in the form of snapshots.

Automatic database diagnostic monitor (ADDM). This monitor performs analysis, detects bottlenecks, and recommends solutions. Recommendations can include the type of advisor that needs to be used to resolve the problem.

This column focuses on some of the database advisors that are invoked by ADDM to help you improve database performance. It presents sample questions of the type you may encounter when taking the Oracle Database 11g Administration Workshop I exam, which enables you to earn the Oracle Certified Associate level of certification.
SQL Tuning Advisor

The SQL tuning advisor analyzes problems with individual SQL statements, such as a poorly performing optimizer plan or the mistaken use of certain SQL structures, and makes recommendations for improving their performance. You can run the SQL tuning advisor against resource-intensive SQL statements, a set of SQL statements over a period of time, or from a SQL workload. Typically, you run this advisor in response to an ADDM performance finding that recommends its use.

Oracle Database 11g introduces the automatic SQL tuning advisor, which can be configured to automatically run during system maintenance windows as a maintenance task. During each automatic run, the advisor selects high-load SQL queries in the system and generates recommendations on how to tune them.

John starts to create a new table based on data in the customer table. The following criteria must be applied on the data:



    All columns of the customer table must be available in the new table.
    The new table must have data for only those customers whose average order is US$1 million or more per quarter, who have not made payments for the last two orders, and whose payment period has exceeded the credit period.



John notices that the table-creation process is taking very long to complete. The DBA has enabled the automatic SQL tuning advisor with automatic implementation, but when he runs the SQL tuning advisor, he notes that this SQL statement was poorly formed and not automatically tuned. Why did the server not automatically tune this statement?

A. The automatic SQL tuning advisor ignores CREATE TABLE AS SELECT statements.
B. The automatic SQL tuning advisor ignores CREATE TABLE statements.
C. The automatic SQL tuning advisor tunes only SQL queries.
D. The automatic SQL tuning advisor does not tune DML statements.

The correct answer is A. Even though the automatic SQL tuning advisor is enabled, it does not resolve every SQL performance issue. It does not automatically resolve issues with the following types of SQL statements: CREATE TABLE AS SELECT and INSERT SELECT, ad hoc or rarely repeated SQL, parallel queries, and recursive SQL.

You have received complaints about the degradation of SQL query performance and have identified the most-resource-intensive SQL queries. What is your next step to get recommendations about restructuring the SQL statements to improve query performance?

A. Run the segment advisor
B. Run the SQL tuning advisor on the most-resource-intensive SQL statements
C. Run the AWR report
D. Run ADDM on the most-resource-intensive SQL statements

The correct answer is B. After you have identified the SQL statements that are the most resource intensive, you use the SQL tuning advisor to get recommendations on how to tune them. Answer A is incorrect because the segment advisor reports on the growth trend of segments and provides recommendations on whether a segment needs to be shrunk. Answer C is incorrect because AWR is a repository that stores performance-related information in the form of snapshots. Answer D is incorrect because ADDM uses these statistics to perform analysis and detect bottlenecks and then recommends solutions.
SQL Access Advisor

The SQL access advisor provides recommendations for improving the performance of a workload. In addition to analyzing indexes and materialized views as in Oracle Database 10g, the SQL access advisor in Oracle Database 11g analyzes tables and queries and provides recommendations on optimizing storage structures.

The SQL access advisor tunes a schema to a particular workload. Typically, when you use the SQL access advisor for performance tuning, you perform the following steps: create a task, define the workload, generate recommendations, and implement recommendations.

You can use the SQL access advisor to receive recommendations on which of the following:

A. Schema modifications
B. Tuning resource-intensive SQL statements
C. Improving the execution plan of SQL statements
D. SQL workload

The correct answers are A and D. The SQL access advisor analyzes an entire workload and recommends changes to indexes, materialized views, and tables to improve performance. Answers B and C are incorrect because the SQL tuning advisor makes recommendations on tuning resource-intensive SQL statements and improving the execution plan of SQL statements.
Memory Advisor

The memory advisor is a collection of several advisory functions that help determine the best settings for the total memory used by the database instance. They provide graphical analyses of total memory target settings (as shown in Figure 1), SGA and PGA target settings, or SGA component size settings. You use these analyses to tune database performance and for what-if planning. Several memory advisors are available for memory tuning (note that the availability of these advisors depends on whether the automatic memory management [AMM] and the automatic shared memory management [ASMM] features are enabled or disabled): The SGA advisor provides information about percentage improvement in DB (database) time for various sizes of SGA, the shared pool advisor provides information about the estimated parse time in the shared pool for different pool sizes, the buffer cache advisor provides information about physical reads and time for the cache size, and the PGA advisor provides information about cache hit percentage against PGA target memory size.

You have enabled AMM and ASMM features in your database, and you use Oracle Enterprise Manager to manage your database. Which memory advisors—memory size advisor, shared pool advisor, buffer cache advisor, or Java pool advisor—will you be able to use?

A. Only memory size advisor
B. Only shared pool advisor
C. All four of the memory advisors
D. Shared pool advisor, buffer cache advisor, and Java pool advisor

The correct answer is A. When AMM and ASMM are enabled, the system adapts to workload changes by automatically sizing SGA and PGA components. Because you will not receive advice on these individual components of SGA, the corresponding advisors will be disabled.
Undo Advisor

The undo advisor helps you determine the size of the undo tablespace. You can compute the minimum size of the undo tablespace, based on either the statistics gathered over a designated time period or an undo retention period. Using the runtime statistics collected in the AWR, you can use the undo advisor to extrapolate how future requirements might affect the size of the undo tablespace. You then use the Undo Management page in Oracle Enterprise Manager to make the changes recommended by the undo advisor.

You are a DBA of an online transaction processing (OLTP) system that supports thousands of users and millions of transactions every day. As part of the periodic tuning activity, you plan to use the undo advisor to ensure that the size of the undo tablespace meets the requirements of the longest-running transaction of the instance. What information will the advisor use to determine the size of the undo tablespace?

A. The analysis time period
B. The undo retention period
C. The undo generation rate
D. The number of undo tablespaces in the database
figure 1
Figure 1: Total memory target settings


The correct answers are A, B, and C. The undo advisor uses the analysis time period, the undo retention period, and the rate of undo generation to recommend the minimum size of the undo tablespace that can meet the requirements of the longest-running transaction. Answer D is incorrect because only one undo tablespace is active at any particular time, so it does not matter how many undo tablespaces a database has.
Conclusion

This column has focused on some advisors that help you manage and tune your database:



    SQL tuning advisor provides recommendations on actions such as rewriting the statement, changing the instance configuration, and adding indexes.
    SQL access advisor takes a SQL workload as an input and recommends which indexes, materialized views, and logs to create, drop, or retain for faster performance.
    Memory advisor provides graphical analyses of total memory target settings, SGA and PGA target settings, or SGA component size settings.
    Undo advisor determines the undo tablespace size that is required to support a given retention period.

martes, 23 de septiembre de 2014

Funciones oracle

Trigger: es un bloque de código que se ejecuta automáticamente cuando ocurre algún evento (como inserción, actualización o borrado) sobre una determinada tabla (o vista).
Se crean para conservar la integridad y la coherencia de los datos.

CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :new.sal - :old.sal;
dbms_output.put('Old salary: ' || :old.sal);
dbms_output.put(' New salary: ' || :new.sal);
dbms_output.put_line(' Difference ' || sal_diff);
END;
/
 
create or replace trigger NOMBREDISPARADOR
MOMENTO-- before, after o instead of
EVENTO-- insert, update o delete
of CAMPOS-- solo para update
on NOMBRETABLA
NIVEL--puede ser a nivel de sentencia (statement) o de fila (for each row)
when CONDICION--opcional
begin
CUERPO DEL DISPARADOR--sentencias
end NOMBREDISPARADOR;