Useful Queries: Select From Where
Useful Queries: Select From Where
Esto es común a todos los queries, para dejar de lado las cosas propias de ORACLE:
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
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;
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;
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.
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.
Sanity Checking Check if the LOB variable has been initialized OCILobLocatorIsInit
Operations involving multiple Check whether the two LOB locators are the OCILobIsEqual
locators same
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.
Example function
/procedure
Category Operation in DBMS_LOB package
Operations Assign BFILE locator src to BFILE locator dst dst := src
involving
multiple Load BFILE data into a LOB LOADCLOBFROMFILE,
locators LOADBLOBFROMFILE
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')
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.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;
/
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
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 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
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
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