0% found this document useful (0 votes)
11 views11 pages

Useful Queries: Select From Where

The document provides a comprehensive overview of useful SQL queries for Oracle databases, covering various aspects such as schema information, table structures, constraints, triggers, and large object management. It includes specific SQL commands to retrieve data about tables, columns, and user privileges, as well as details on managing large objects like BLOBs and CLOBs. Additionally, it discusses the use of UTL_FILE for file operations within Oracle, emphasizing the importance of directory permissions.

Uploaded by

Marcelo Armocida
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Useful Queries: Select From Where

The document provides a comprehensive overview of useful SQL queries for Oracle databases, covering various aspects such as schema information, table structures, constraints, triggers, and large object management. It includes specific SQL commands to retrieve data about tables, columns, and user privileges, as well as details on managing large objects like BLOBs and CLOBs. Additionally, it discusses the use of UTL_FILE for file operations within Oracle, emphasizing the importance of directory permissions.

Uploaded by

Marcelo Armocida
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

USEFUL QUERIES

Esto es común a todos los queries, para dejar de lado las cosas propias de ORACLE:

where tab.owner not in ('ANONYMOUS','CTXSYS','DBSNMP','EXFSYS', 'LBACSYS', 'MDSYS', 'MGMT_VIEW', 'OLAPSYS', 'OWBSYS',


'ORDPLUGINS', 'ORDSYS','OUTLN', 'SI_INFORMTN_SCHEMA','SYS','SYSMAN','SYSTEM', 'TSMSYS', 'WK_TEST','WKSYS', 'WKPROXY',
'WMSYS','XDB','APEX_040000', 'APEX_PUBLIC_USER','DIP', 'FLOWS_30000','FLOWS_FILES','MDDATA', 'ORACLE_OCM',
'SPATIAL_CSW_ADMIN_USR', 'SPATIAL_WFS_ADMIN_USR', 'XS$NULL','PUBLIC')

VISTAS ORACLE

USER_ - include objects owned by the current user only, not suitable in this case
ALL_ - include objects all objects (from all schemas) accessible to the current user
DBA_ - includes all objects, but requires DBA role

SELECT * BULK COLLECT INTO v_columns FROM user_tab_columns WHERE table_name =


upper(p_table_name); esa tabla tiene todas las tablas y columnas de un usuario.

select tab.owner as schema_name, tab.table_name as table_name, obj.created, obj.last_ddl_time as last_modified,


tab.num_rows, tab.last_analyzed, comm.comments
from all_tables tab inner join all_objects obj on obj.owner = tab.owner and obj.object_name = tab.table_name
left outer join all_tab_comments comm on tab.table_name = comm.table_name and tab.owner = comm.owner
-- and tab.owner = 'HR' / --tab.owner in
(select username from all_users where oracle_maintained = 'N') --DESDE 12C
order by tab.owner, tab.table_name;

select obj.owner as schema_name, obj.object_name as view_name, obj.created, obj.last_ddl_time as last_modified,


def.text as definition, comm.comments
from all_objects obj left outer join all_views def on obj.owner = def.owner and obj.object_name = def.view_name
left outer join all_tab_comments comm on obj.object_name = comm.table_name and obj.owner = comm.owner
where obj.object_type = 'VIEW' / --and obj.owner = 'HR' order by obj.owner, obj.object_name;

select col.owner as schema_name, col.table_name, col.column_name, col.data_type, decode(char_length,


0, data_type, data_type || '(' || char_length || ')') as data_type_ext, col.data_length, col.data_precision,
col.data_scale, col.nullable, col.data_default as default_value,nvl(pk.primary_key, ' ') as primary_key,
nvl(fk.foreign_key, ' ') as foreign_key, nvl(uk.unique_key, ' ') as unique_key, nvl(check_const.check_constraint, ' ')
check_constraint,comm.comments
from all_tables tab inner join all_tab_columns col on col.owner = tab.owner and col.table_name = tab.table_name
left join all_col_comments comm on col.owner = comm.owner and col.table_name = comm.table_name
and col.column_name = comm.column_name
left join (select constr.owner, col_const.table_name, col_const.column_name, 'PK' primary_key
from all_constraints constr inner join all_cons_columns col_const on constr.constraint_name =
col_const.constraint_name and col_const.owner = constr.owner
where constr.constraint_type = 'P') pk on col.table_name = pk.table_name and col.column_name = pk.column_name
and col.owner = pk.owner
left join (select constr.owner, col_const.table_name, col_const.column_name, 'FK' foreign_key
from all_constraints constr inner join all_cons_columns col_const on constr.constraint_name =
col_const.constraint_name and col_const.owner = constr.owner where constr.constraint_type = 'R'
group by constr.owner, col_const.table_name, col_const.column_name) fk
on col.table_name = fk.table_name and col.column_name = fk.column_name and col.owner = fk.owner
left join (select constr.owner, col_const.table_name, col_const.column_name, 'UK' unique_key
from all_constraints constr inner join all_cons_columns col_const on constr.constraint_name =
col_const.constraint_name and constr.owner = col_const.owner where constr.constraint_type = 'U'
union
select ind.owner, col_ind.table_name, col_ind.column_name, 'UK' unique_key
from all_indexes ind inner join all_ind_columns col_ind on ind.index_name = col_ind.index_name
where ind.uniqueness = 'UNIQUE') uk on col.table_name = uk.table_name and col.column_name = uk.column_name
and col.owner = uk.owner
left join (select constr.owner, col_const.table_name, col_const.column_name, 'Check' check_constraint
from all_constraints constr inner join all_cons_columns col_const on constr.constraint_name =
col_const.constraint_name and col_const.owner = constr.owner
where constr.constraint_type = 'C' group by constr.owner, col_const.table_name,
col_const.column_name) check_const on col.table_name = check_const.table_name
and col.column_name = check_const.column_name and col.owner = check_const.owner
where col.owner not in (....)
-- and col.owner = 'HR' -- and lower(tab.table_name) like '%'
order by col.owner, col.table_name, col.column_name;

ESQUEMAS
select username as schema_name from sys.all_users order by username;
TABLAS EN MI ESQUEMA
select object_name as table_name from user_objects where object_type = 'TABLE'
--OWNER= 'xx' order by object_name

DEFAULT VALUES
select col.owner as schema_name, col.table_name, col.column_name, col.column_id, col.data_default as def
from sys.all_tab_columns col inner join sys.all_tables t on col.owner = t.owner and col.table_name = t.table_name
where col.owner not in (....) and col.data_default is not null
order by t.owner, t.table_name, col.column_id;

COLUMNAS DE TABLA
select col.column_id, col.owner as schema_name, col.table_name, col.column_name, col.data_type,
col.data_length, col.data_precision, col.data_scale, col.nullable
from sys.all_tab_columns col
inner join sys.all_tables t on col.owner = t.owner and col.table_name = t.table_name
where col.owner not in (...)
order by col.owner, col.table_name, col.column_id;

TABLES, PK, CONSTRAINT


select tab.owner as schema_name, tab.table_name, acc.constraint_name, LISTAGG(acc.column_name,',')
WITHIN GROUP (order by acc.position) as columns, con.status
from sys.all_tables tab left join sys.all_constraints con on con.owner = tab.owner and con.table_name =
tab.table_name
and con.constraint_type = 'P' left join sys.all_cons_columns acc on con.owner = acc.owner and
con.constraint_name = acc.constraint_name where tab.owner not in (...) group by tab.owner, tab.table_name,
acc.constraint_name,
con.status order by tab.owner, tab.table_name;

TRIGGERS
select owner as trigger_schema_name, trigger_name, trigger_type, triggering_event, table_owner as
schema_name,
table_name as object_name, base_object_type as object_type, status, trigger_body as script
from sys.all_triggers
where owner not in (...) order by trigger_name, table_owner, table_name, base_object_type;

DB version
select * from V$VERSION

GRANTS
SELECT PRIVILEGE FROM sys.dba_sys_privs WHERE grantee = <theUser>
UNION
SELECT PRIVILEGE
FROM dba_role_privs rp JOIN role_sys_privs rsp ON (rp.granted_role = rsp.role) WHERE rp.grantee = <theUser>
ORDER BY 1;

Direct grants to tables/views:


SELECT owner, table_name, select_priv, insert_priv, delete_priv, update_priv, references_priv, alter_priv, index_priv
FROM table_privileges WHERE grantee = <theUser>
ORDER BY owner, table_name;

Indirect grants to tables/views:


SELECT DISTINCT owner, table_name, PRIVILEGE
FROM dba_role_privs rp JOIN role_tab_privs rtp ON (rp.granted_role = rtp.role)
WHERE rp.grantee = <theUser>
ORDER BY owner, table_name;

DIRECTORIES
Nombre alias de un directorio real en el file system donde esta la DB. solo se eaccde a un archivo fisico, si tenemos
permiso
CREATE OR REPLACE DIRECTORY scott_dir AS '/usr/home/scott'; no verifica que exista.
CREATE DIRECTORY "small_cap_dir" AS "G:\DATA\SOURCE"; en windows, no case sensitive
la vista ALL_DIRECTORIES son los que el user puede acceder.
Large Objects are used to hold large amounts of data inside Oracle Database, SecureFiles provides performance
comparable to file system performance, and DBFS provides file system interface to files stored in Oracle Database.

Large Objects: from 8 terabytes to 128 terabytes depending on how your database is configured. Storing data in
LOBs enables you to access and manipulate the data efficiently in your application.

SecureFile LOBs: SecureFile LOBs are LOBs that are created in a tablespace managed with Automatic Segment
Space Management (ASSM). SecureFiles is the default storage mechanism for LOBs in database tables. Oracle
strongly recommends SecureFiles for storing and managing LOBs.

Database File System (DBFS) provides a file system interface to files that are stored in an Oracle Database.

Files stored in an Oracle Database are usually stored as SecureFiles LOBs, and path names, directories, and other file
system information is stored in the database tables. SecureFiles LOBs is the default storage method for DBFS, but
BasicFiles LOBs can be used in some situations.

With DBFS, you can make references from SecureFiles LOB locators to files stored outside the database. These
references are called DBFS Links or Database File System Links.

Table 1-1 Types of Large Object Data

BLOB Binary Large Object Stores any kinds of data in binary format. Used for images, audio, and video.

CLOB Character Large Object Stores string data in the database character set format. Used for large strings or
documents that use the database character set exclusively. Characters in the database character set are in a fixed
width format.

NCLOB National Character Set Large Object Stores string data in National Character Set format, typically large
strings or documents. Supports characters of varying width format.

BFILE External Binary File A binary file stored outside of the database in the host operating system file system, but
accessible from database tables. BFILEs can be accessed from your application on a read-only basis. Use BFILEs to
store static data, such as image data, that is not manipulated in applications.
Any kind of data, that is, any operating system file, can be stored in a BFILE. For example, you can store character
data in a BFILE and then load the BFILE data into a CLOB, specifying the character set upon loading.

A LOB instance has a locator and a value. A LOB locator is a reference, or a pointer, to where the LOB value is physically
stored. The LOB value is the data stored in the LOB.

Table 8-1 Operations supported by LOB APIs

Example function/procedure in DBMS_LOB or


Category Operation OCILob

Sanity Checking Check if the LOB variable has been initialized OCILobLocatorIsInit

Find out if the BLOB or CLOB locator is a ISSECUREFILE


SecureFile

Open/Close Open a LOB OPEN

Check is a LOB is open ISOPEN

Close the LOB CLOSE

Read Operations Get the length of the LOB GETLENGTH

Get the LOB storage limit for the database GET_STORAGE_LIMIT


configuration

Get the optimum read or write size GETCHUNKSIZE

Read data from the LOB starting at the READ


specified offset

Return part of the LOB value starting at the SUBSTR


specified offset using SUBSTR

Return the matching position of a pattern in a INSTR


Example function/procedure in DBMS_LOB or
Category Operation OCILob

LOB using INSTR

Modify Operations Write data to the LOB at a specified offset WRITE

Write data to the end of the LOB WRITEAPPEND

Erase part of a LOB, starting at a specified ERASE


offset

Trim the LOB value to the specified shorter TRIM


length

Operations involving multiple Check whether the two LOB locators are the OCILobIsEqual
locators same

Compare all or part of the value of two LOBs COMPARE

Append a LOB value to another LOB APPEND

Copy all or part of a LOB to another LOB COPY

Assign LOB locator src to LOB locator dst dst:=src, OCILobLocatorAssign

Converts a BLOB to a CLOB or a CLOB to CONVERTTOBLOB, CONVERTTOCLOB


a BLOB

Load BFILE data into a LOB LOADCLOBFROMFILE,


LOADBLOBFROMFILE

Operations Specific to Returns options (deduplication, compression, GETOPTIONS


SecureFiles encryption) for SecureFiles.

Sets LOB features (deduplication and SETOPTIONS


compression) for SecureFiles

Gets the content string for a SecureFiles. GETCONTENTTYPE

Sets the content string for a SecureFiles. SETCONTENTTYPE

Delete the data from the LOB at the given FRAGMENT_DELETE


offset for the given length

Insert the given data (< 32KBytes) into the FRAGMENT_INSERT


LOB at the given offset

Move the given amount of bytes from the FRAGMENT_MOVE


given offset to the new given offset

Replace the data at the given offset with the FRAGMENT_REPLACE


given data (< 32kBytes)

BFILEs are data objects stored in operating system files, outside the database tablespaces. Data stored in a table column of
type BFILE is physically located in an operating system file, not in the database. The BFILE column stores a reference to
the operating system file.

Table 4-1 Operations on BFILEs

Example function
/procedure
Category Operation in DBMS_LOB package

Sanity Checking Check if the BFILE exists on the server FILEEXISITS

Get the DIRECTORY object name and file name FILEGETNAME


Example function
/procedure
Category Operation in DBMS_LOB package

Set the name of a BFILE in a locator without BFILENAME


checking if the directory or file exists

Open / Close Open a file OPEN

Check if the file was opened using the ISOPEN


input BFILE locators

Close the file CLOSE

Close all previously opened files FILECLOSEALL

Read Get the length of the BFILE GETLENGTH


Operations
Read data from the BFILE starting at the specified READ
offset

Return part of the BFILE value starting at the SUBSTR


specified offset using SUBSTR

Return the matching position of a pattern in INSTR


a BFILE using INSTR

Operations Assign BFILE locator src to BFILE locator dst dst := src
involving
multiple Load BFILE data into a LOB LOADCLOBFROMFILE,
locators LOADBLOBFROMFILE

Compare all or part of the value of two BFILEs COMPARE


JSON: js object notation. se guardan como v2,clob o blob, v232767 los primeros 3.5k se guardan en la fila ojo. usar
lob si supera los 32767. usar blob sobre clob, mas si el charset es AL32UTF8 (UCS2) ocupan 2bytes

ALL_JSON_COLUMNS. y para saber si unacolumna es json tiene que tener la constrin is json. con la misma
funcion sabremos si estamos en modo lax o strict

para insert y update, si es v2 o clob no problem, si es blob o sqlplus hay que convertir con
UTL_RAW.convert(UTL_RAW.cast_to_raw('{....}'),

'AL32UTF8',

'WE8MSWIN1252')

 po.po_document.PONumber – The value of field PONumber.


 po.po_document.LineItems[1] – The second element of array LineItems (array positions are zero-based).
 po.po_document.LineItems[*] – All of the elements of array LineItems (* is a wildcard).
 po.po_document.ShippingInstructions.name – The value of field name, a child of
object ShippingInstructions.

absolute simple path $

object step.

array step[

function step ()
UTL_FILES

UTL_FILE uses the oracle directories and not the OS directories. So a logical directory to be created by SYS user and read and write
access of that directory to be granted to the user or to public.
SELECT * FROM ALL_DIRECTORIES;

UTL_FILE.FOPEN(LOCATION, FILENAME , OPEN_MODE (R W A), MAX_LINESIZE 1024/32767) RETURN FILE_TYPE;


(Hasta 50 a la vez)

UTL_FILE.IS_OPEN(FILE FILE_TYPE) RETURN BOOLEAN

UTL_FILE.FCLOSE(FILE IN OUT FILE_TYPE); UTL_FILE.FCLOSE_ALL;

UTL_FILE.NEW_LINE(FILE FILE_TYPE, LINES NATURAL := 1);

UTL_FILE.PUT(FILE FILE_TYPE, BUFFER VARCHAR2);

UTL_FILE.PUT_LINE(FILE FILE_TYPE, BUFFER VARCHAR2, AUTOFLUSH BOOLEAN DEFAULT NULL);


Flushes the buffer to disk after write

UTL_FILE.GET_LINE(FILE FILE_TYPE, BUFFER OUT VARCHAR2, LEN PLS_INTEGER DEFAULT NULL);

UTL_FILE.GET_LINE(FILE FILE_TYPE, BUFFER OUT VARCHAR2, LEN PLS_INTEGER DEFAULT NULL);

UTL_FILE.FREMOVE(LOCATION VARCHAR2, FILENAME VARCHAR2);

UTL_FILE.FGETATTR(LOCATION , FILENAME, EXISTS OUT BOOLEAN, FILE_LENGTH OUT NUMBER, BLOCKSIZE OUT NUMBER);

DECLARE
CURSOR EMP_CUR IS
SELECT * FROM tabla;
V_FILE_GRABO UTL_FILE.FILE_TYPE;
V_FILE_LEO UTL_FILE.FILE_TYPE;

BEGIN
V_FILE := UTL_FILE.FOPEN('UTL_DIR', 'EMP_DETAILS.CSV', 'W', MAX_LINESIZE => 32767; --(si no lo pongo es 1024 default)
FOR I IN EMP_CUR LOOP
UTL_FILE.PUT_LINE(V_FILE_GRABO,TITULOS'||I.COLUMNAS);
END LOOP;
UTL_FILE.FCLOSE(V_FILE);
END;
/

UTL_FILE.GET_LINE(V_FILE, V_DTL, 32767);

UTL_FILE PACKAGE EXCEPTIONS:

EXCEPTION NAME DESCRIPTION


INVALID_PATH File location is invalid
INVALID_MODE The OPEN_MODE parameter of FOPEN is invalid
INVALID_FILEHANDLE File handle is invalid
INVALID_OPERATION File could not opened or operated on as requested
READ_ERROR Operating system error occurred during read operation
WRITE_ERROR Operating system error occurred during write operation
INTERNAL_ERROR Unspecified PLSQL error
FILE_OPEN Requested operation is failed as the file is opened
INVALID_MAXLINESIZE It should be within range of 1 to 32767
INVALID_FILENAME FILENAME parameter is invalid
ACCESS_DENIED Permission to access the file location is denied
DELETE_FAILED Requested delete operation is failed
RENAME_FAILED Requested file rename operation is failed

Oracle Database Globalization Support Guide – Appendix A – Locale Data.


Oracle recomienda unicode AL32UTF8 para la base
Para saber que caracteres estan definidos para un conjunto de caracteres oracle se usa Locale Builder
CHARACTER SET / CHARACTER ENCODING, caracteres que se guardan en la DB y define como cada caracter es mapeado a una
secuencia de bytes que lo representa.
Puede ser siglebyte (hasta 256) o multibyte (1,2,3,4)
Lo que no es unicode, se llama en general legacy charsets
Si charset A tiene los de B mas algunos, A es superset de B y B subset de A. si A define exactamente todo lo de B, igual es
superset/subset pero estricto o binario.
Caracteres no disponibles son convertidos a otros por default. en unicode es U+FFFD.
si la DB es superset binaria, la declaracion cambias olo en metadata (schema), es rapido y simple. aun no siendo binaria, si por
ejemplo todos los caracteres son ascii entre 0 y 127, no necesitan convertirse

Migracion incluye: identificar el superset ideal, clasificar los char como sin cambios o convertibles, chequear requerimientos de
tamaño, arreglar kilombos, cambiar la declaracion en el data dictionary.
Ayudados con Database Character Set Scanner utility or the Database Migration Assistant for Unicode (DMU)

NLS_LANG
idioma, zona, conjunto de caracteres NO ES UN PARAMETRO. SOLO para ORACLE CLIENT SOFTWARE
En unix es una variable de entorno local, en W en el registro
3 comp: idioma (mensajes oracle, orden, nros, nombre d elos meses) , territorio (fecha formatos numeros y $),
conjunto
Se setean a nivel session, instancia, DB
NLS_LANG=language_territory.charset: no cambia el lenguaje del cliente, solo informa a Oracle. Default
AMERICAN_AMERICA.US7ASCII se puede setear solo un componente.

select * from nls_instance_parameters, del init.ora, desde el inicio de la DB o despues de un ALTER SYSTEM
select * from nls_session_parameters

NLS_LANG is not set, it defaults to NLS_LANG=LANGUAGE_TERRITORY.US7ASCII with the LANGUAGE_TERRITORY


components derived from the NLS Oracle Database instance parameters.

NLS_LANGUAGE,NLS_TERRITORY son PARAMETROS


no se define charset de la base en parametros, sino al crear la DB

Cuando NLS_LANG del cliente se configura con el mismo valor que el charset de la DB, Oracle asume que los datos
que se reciben tienen la misma, no hay validaciones o conversiones asi que ojo con el charset del cliente

En unix vemos la configuracion con locale (linux en /usr/share/locale/locale.alias


y vemos como esta configurada con host echo $NLS_LANG

Para saber que parametros estan disponibles locale -a


Para configurar, se hace export PAR=valor o setenv PAR valor

En W, el esquema de codificacion (charset) se especifica mediante una pagina de codigos. para oracle pagina de
codigos y charset es lo mismo. W usa dos juegos diferentes para ANSI (sqlplusw.exe) y OEM(dos box, sqlplus.exe)
OEM es la pagina de codigos para MS-DOS, salvo para chino japones que es ansi
Hay que definir una subclave en el registro por cada directorio raiz oracle.
para Oracle 10 es HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_
Al iniciar sqlplusw se lee oracle.key en el mismo directorio para saber que jerarquia de registro se usa.
Tambien podrian ser variables de sistema o entorno de usuario (MYPC->prop->adv->EV

La pagina de codigos ANSI (ACP) esta definida por la conf. regional predet. de W; si tenemos W2000 en UK y
queremos usar cirilico, se busca ACP en HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\NLS\CodePage

Se puede usar UTF8 en WNT,2000,XP pero solo en prog de clientes que explictamente usen esta conf, porque
WIN32 no es utf8 y hay conversion

MSDOS usa pagina de codigo OEM, asi que antes de usar slqplus etc para svrmgrl debe configurar manualmente
NSL_LANG como una variable de entorno "set"
chcp te dice que nro de pagina de codigos esta en uso y se informa a Oracle con la que coresponde
set NLS_LANG=smerican_america.US8PC437

GUI -- OEM
ingles uk/usa ENGLISH_UNITED KINGDOM/AMERICAN_AMERICA -- WE8PC850 / US8PC437
frances can/francia CANADIAN FRENCH_CANADA/FRENCH_FRANCE -- WE8PC850
español esp/ven SPANISH_SPAIN/LATIN AMERICAN SPANISH_VENEZUELA -- WE8PC850
todos .WE8MSWIN1252

nls_date_format esto cambia la manera de tratar la fecha por sqlplus, se puede hacer con alter session set

Table 18-2 OLAP DML NLS Options

Option Name Description


NLS_CALENDAR The calendar for the session.
NLS_CURRENCY The local currency symbol for the L number format element for the session.
NLS_DATE_FORMAT The default format for DATETIME values.
NLS_DATE_LANGUAGE The language for days, months, and similar language-dependent DATE format elements.
NLS_DUAL_CURRENCY A second currency symbol in addition to the local currency symbol (which is identified by
NLS_CURRENCY). It is used primarily to identify the Euro symbol.
NLS_ISO_CURRENCY The international currency symbol for the C number format element.
NLS_LANG The current language, territory, and database character set, which are determined by session-wide
globalization parameters.
NLS_LANGUAGE The current language for the session.
NLS_NUMERIC_CHARACTERS The decimal marker and thousands group marker for the session.
NLS_SORT the sequence of character values used when sorting or comparing text.
NLS_TERRITORY The current territory for the session.

COMANDO DUMP
SELECT SYS_CONTEXT ('USERENV', 'NLS_CURRENCY') FROM DUAL;
SELECT * FROM V$PARAMETER
dbms_stats
EXPLAIN PLAN
SQL TRACE FACILITY WITH TKPROF
dbms_trace
ORACLE TRACE
FORALL
CONNECT BY
REGEXP_
EVITAR LLAMADA S FUNCIONES , PRIMERO FILTRZAR REGISTORS CON INNER QUERY.
EVITAR CONVERSION DE DATOS
PLS_INTEGER,BINARY_FLOAT,BINARY_DOUBLE USA ARITMETICA DE MAQUINA ES MEJOR
AGRUPAR FUNCIONES EN PACKAGE QUE SE CARGAN DE UNA EN SHARED MEMORY
DBMS_SHARED_POOL para clavar un pkg en memoria
PROFILER API, DBMS_PROFILER, para saber como funciona mi pl

PL SQL OPTIMIZER: antes de 10g el compilador no aplicaba cambios al codigo, ahora lo reordena para mejorar rendimiento.
PLSQL_OPTIMIZER_LEVEL=1 no hace nada, 2 optimiza.

EXPLAIN PLAN: nos muestra cual es el plan de ejecucion para DML, variando por costo, parametros y esquemas. Nos permite
descartar errores y mejorar rendimiento. No nos dice qsi esta mal lo que hacemos, pero nos orienta.
Tiene que estar creada la tabla PLAN_TABLE, hay un UTLXPLAN.sql

EXPLAIN PLAN [INTO OTRA_TABLA [SET STATEMENT_ID='algo']] FOR SELECT ....


Hay dos scripts para ver el resultado UTLXPLS procesamiento serie, UTLXPLP, columnas de ejecucion paralelas

select plan_table_output from table(dbms_xplan.display('plan_table',null,'serial'));


select * from table(dbms_xplan.display()); --esta es mas actual

El Optimizador
Diferentes maneras de ejecutar un query: full table scans, index, nested loops, hash joins. El resultado de la optimizacion es
un plan de ejecucion, que analiza
Evaluation of expressions The optimizer first evaluates expressions and conditions containing constants as fully as
and conditions possible.
Statement transformation For complex statements involving, for example, correlated subqueries or views, the
optimizer might transform the original statement into an equivalent join statement.
Choice of optimizer goals The optimizer determines the goal of optimization.
Choice of access paths For each table accessed by the statement, the optimizer chooses one or more of the
available access paths to obtain table data.
Choice of join orders For a join statement that joins more than two tables, the optimizer chooses which pair of
tables is joined first, and then which table is joined to the result, and so on.

Componentes:
Transformer: determina si hay que reescribir el query usando
View merging: si se consulta una view, el tfm puede recrear la query usando la tabla original, si es un select sin funciones de
agrupacion. usuario tiene que tener MERGE ANY VIEW
Predicate pushing: por ejemplo si se crea una view con UNION y luego se hace select con where, se aplica el where directamente
en UNION
subquery unnesting. si tengo un select con where campo in (select...) si el campo es clave, se hace select con ambas tablas que es
mejor
Materializated views: se guarda el resultado de una query en una vista entonbces futuros queries compatibles se basan en esa
vista y puede ser reescrito por el optimizador. CREATE MATERIALIZED VIEW nn ENABLE QUERY REWRITE

Estimacion: el costo se estima por:


selectividad: el predicado de un where determina cuantas filas se eligen de un total. la selectivity (filtradas/total) va de 0.0, no filas,
a 1.0, todo el set. cercano a 0 es mejor. solo si estadisticas estan activadas, sino se usa valores internos para estimar. Si la tabla (la
columna) tiene histograma, se usa.
Cardinality: cantidad de filas que devuelve el query
Costo: medido en uso de CPU y memoria. el access path, es decir la manera en la que se extrae data, determina el nro de unidades
de trabajo requeridas para leer datos de una tabla. Full scan, fast full index scan, index scan, el costo de la lectura de bloques en
disco, lectura de B-tree, hojas de las ramas, registros traidos por rowid para los indices, es decir muchos factores

You might also like