DB Database Data Base PLSQL Oracle
DB Database Data Base PLSQL Oracle
DB ORACLE
PLSQL
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
TABLESPACE
TABLESPACE
DATAFILE
DATAFILE
EXTENT
EXTENT
DBBLOC
KK
EXTENT
RIASSUNTO
TABLESPACES
OBJECTS
DATAFILES
STRUTTURA
LOGICA
DEL
DATABASE
SEGMENTS
EXTENTS
STRUTTURA
FISICA
DEL
DATABASE
DBBLOCKS
2. CORSO PL/SQL
PL/SQL il linguaggio di Oracle che estende lSQL con i costrutti tipici dei linguaggi di
programmazione procedurali consentendo la modularit, la dichiarazione di variabili, i loop e
altri costrutti logici, oltre ad una avanzata gestione degli errori.
Raggruppando i comandi SQL in un blocco PL/SQL si riduce il lavoro del client e si ottimizza
il traffico di rete, poich il programma PL/SQL viene inviato al database come ununica
transazione.
Una transazione lunit logica di lavoro che contiene una o pi istruzioni SQL eseguite da
un singolo utente; gli effetti di tutte le istruzioni SQL in una transazione possono essere
tutte committed (applicate effettivamente al database) o tutte rolled back (non riportate
sul database).
I programmi PL/SQL si distinguono in blocchi anonimi e procedure memorizzate:
Blocco anonimo: blocco PL/SQL che viene utilizzato da unapplicazione ma non ha
un nome e non memorizzato nel database.
Stored Procedure: blocco o modulo PL/SQL che Oracle compila e memorizza nel
database e che pu essere richiamato tramite il nome in qualsiasi contesto (ad
esempio da altri blocchi PL/SQL, dalle forms, dai reports, dal VB ). Possono essere
creati e memorizzati trigger, procedure, funzioni, packages.
3.1. Triggers
Sono blocchi di codice PL/SQL legati ad una tabella e vengono eseguiti al verificarsi di uno
specifico evento.
Il trigger va visto come un evento che scatena unazione; buona norma che il codice del
trigger contenga solo la chiamata alla funzione/procedura contenuta nella SP e quanto altro
proprio necessario.
I trigger di database possono essere associati allinserimento/modifica/cancellazione di una
tabella o di una vista;
Per la tabella sia nel momento BEFORE che nel momento AFTER,
per la vista solo come INSTEAD OF.
In generale si ha un trigger statement che scatta una sola volta al verificarsi dellevento.
I trigger possono essere creati con lopzione FOR EACH ROW che fa scattare il trigger ad
ogni riga che inserisco/aggiorno/cancello.
La sintassi per la creazione dei triggers la seguente:
CREATE [OR REPLACE] TRIGGER [nome_utente.]nome_trigger
{BEFORE | AFTER | INSTEAD OF} {DELETE | INSERT | UPDATE [OF col1 [,col2]]} ON
[nome_utente.]nome_tabella | nome_vista [referencing old as nuovo_nome | new as
nuovo_nome] [for each row] [when condizione]
DECLARE
sezione_dichiarativa_variabili
BEGIN
blocco_di_esecuzione
blocco_gestione_eccezioni
END;
Vengono create nello schema di un utente e il loro nome deve essere univoco allinterno
dello schema.
Possono essere eseguite in modo interattivo (SQL*Plus) o richiamate esplicitamente da
unapplicazione o nel codice di unaltra procedura o di un trigger.
Procedure e funzioni si distinguono perch le funzioni restituiscono sempre un valore al
chiamante, mentre le procedure non necessariamente.
Per essere utilizzate in comandi SQL non possono modificare lo stato del DB o il valore delle
variabili di un package.
Una funzione deve contenere listruzione RETURN:
RETURN expr;
Dove expr lespressione che deve essere restituita al chiamante.
La sintassi per la creazione di una funzione la seguente:
CREATE [OR REPLACE] FUNCTION [nome_utente.]nome_funzione (argomento1 tipo_arg1
datatype, argomento2 tipo_arg1 datatype,)
RETURN datatype
[AUTHID DEFINER | CURRENT_USER] AS
Sezione_dichiarativa_variabili
BEGIN
sezione_esecuzione
3.5. Packages
Un PACKAGE uno SCHEMA OBJECT costituito da una collezione di procedure e funzioni,
cursori e variabili che viene trattata come ununit.
I packages possono essere richiamati esplicitamente da unapplicazione o da un utente.
Un package composto da due parti:
specifica: dichiara tutti i costrutti pubblici del package (procedure e funzioni con i relativi
parametri) ed visibile allesterno.
corpo: contiene il codice di tutte le procedure e funzioni che rappresentano i costrutti
pubblici e privati;
La separazione di specifica e corpo implica i seguenti vantaggi:
maggiore flessibilit: si possono creare le specifiche senza creare effettivamente il
corpo
si possono cambiare i codici delle procedure nel corpo senza variare la relativa
dichiarazione nella specifica del package, con la conseguenza che gli oggetti che
fanno riferimento alle procedure variate non diventano invalidi e quindi non devono
essere ricompilati.
La sintassi per la creazione di una specifica di package la seguente:
CREATE [OR REPLACE] PACKAGE [nome_utente.]nome_package
[AUTHID DEFINER | CURRENT_USER] AS
FUNCTION nome_funzione1 (lista_argomenti) RETURN datatype;
PROCEDURE nome_procedura1 (lista_argomenti);
dichiarazione di cursori, variabili, costanti, exception;
END nome_package;
exception_name EXCEPTION;
(dichiarazione delle exception definite dallutente; esistono numerose exception predefinite
che non devono essere dichiarate)
PRAGMA EXCEPTION_INIT(exception_name, error_number);
( una direttiva allinterprete PL/SQL per associare gli errori standard Oracle agli errori
definiti dallutente con la dichiarazione di exception)
2. Eseguibile: E la sezione fondamentale di un blocco PL/SQL, lunica obbligatoria;
inizia con la parola chiave BEGIN e termina o con la parola chiave END relativa
allintero blocco o con la parola chiave EXCEPTION);
3. Gestione delle eccezioni: E la sezione finale di un blocco PL/SQL che contiene la
porzione di codice da eseguire in corrispondenza del verificarsi delle ECCEZIONI;
inizia con la parola chiave EXCEPTION.
Una exception o un errore definito dallutente deve sempre essere invocata con il comando
RAISE:
BEGIN
--- codice --IF condizione THEN
RAISE exception_name;
END IF;
--- codice --EXCEPTION
WHEN exception_name THEN
--- codice --END;
3.8. Identificatori
Un identificatore
%type per dichiarare una variabile con lo stesso datatype e la stessa dimensione della
colonna del database alla quale deve corrispondere.
%rowtype permette di creare un datatype composto, ovvero un record, costituito da
tutte le colonne di una riga di una tabella o di un cursore.
3.10.
Non possibile alterare lo step per lintervallo di iterazioni, che vale sempre 1. Si pu usare
il comando MOD(m,n) allinterno di una struttura IFEND IF.
Il comando EXIT pu essere usato allinterno di questa struttura per forzare luscita
prematura da loop.
GOTO etichetta: permette di modificare il flusso di esecuzione del programma saltando in
un punto qualsiasi allinterno di un qualsiasi blocco purch definito da una etichetta
(tuttavia non possibile saltare allinterno di un loop specifico mentre possibile uscire dal
loop).
3.11.
Etichette
BEGIN
;
END nome sub-block;
In questo modo possiamo far riferimento anche ad altri identificatori omonimi presenti
nellenclosing-block (es .nome blocco.nome identificatore).
3.12.
Records
Esistono inoltre forme di record implicite che possono essere utilizzate in tipiche istruzioni
come quelle che scorrono le righe associate ad un cursore in un ciclo FOR LOOP:
FOR REC1 IN CUR1 LOOP
istruzioni
END LOOP;
3.13.
Cursori
La potenza del PL/SQL in gran parte dovuta alla possibilit di utilizzare i cursori.
Un cursore gestisce laccesso a un indirizzo di memoria in cui sono memorizzati i record
risultanti dallesecuzione di un comando SQL e consente di manipolare singolarmente
ciascuna delle righe restituite da una SELECT.
Possono essere espliciti o impliciti.
CURSORI ESPLICITI: comandi SQL predefiniti che restituiscono pi di una riga.
Vengono gestiti in modo esplicito usando i comandi OPEN, FETCH e CLOSE o usando i
cursor loops:
o OPEN: carica le righe identificate dalla query
o FETCH: restituisce una riga dallinsieme di righe selezionate e inserisce i valori
in un record o insieme di variabili specificate nella clausola INTO.
o CLOSE: chiude il cursore, rilasciando la memoria che gli era stata assegnata.
Un cursor loop controlla il cursore senza la necessit di usare OPEN, FETCH o CLOSE; ha il
formato:
FOR rec_id IN cursor_id LOOP
--- codice --END LOOP;
I cursori (espliciti e impliciti) hanno degli attributi che permettono di verificare il loro stato.
Per i cursori espliciti gli attributi sono:
cursor_name%FOUND per un cursore aperto, vale NULL prima della fetch
iniziale. Diventa TRUE se lultima fetch stata eseguita con successo.
cursor_name%ISOPEN vale FALSE prima che il cursore venga aperto, TRUE se
stato aperto ed ancora aperto.
cursor_name%NOTFOUND vale FALSE se lultima fetch fornisce una riga. Vale
TRUE se lultima fetch non stata eseguita con successo.
cursor_name%ROWCOUNT restituisce il numero di righe su cui si effettuata
la fetch fino a quel momento. Vale NULL prima che il cursore venga aperto; zero
prima della fetch iniziale.
EX:
<<NomeEtichetta>>
loop
fetch tmpEle into tmpRec;
exit when tmpEle%NOTFOUND;
......
end if;
end loop NomeEtichetta;
Luso corretto dei cursori prevede una serie di operazioni articolate in quattro fasi distinte:
dichiarazione del cursore;
apertura del cursore con listruzione OPEN in modo da consentire la preparazione
delle risorse associate al cursore e lesecuzione della relativa istruzione SQL;
FETCH del cursore allinterno di un loop in modo da scorrere il set di records ed
associare i valori di ogni riga alle variabili specificate nella clausola INTO per ogni riga
ritrovata tramite la FETCH possiamo eventualmente eseguire il comando DELETE or
UPDATE facendo uso della clausola WHERE CURRENT OF;
chiusura del cursore al termine delle operazioni tramite listruzione CLOSE (il cursore
comunque pu sempre essere riaperto in qualsiasi altro momento);
o
o
o
DECLARE
Nome_exception EXCEPTION;
BEGIN
.
IF condizione THEN
RAISE nome_exception;
END IF;
..
EXCEPTION
WHEN nome_exception THEN
istruzioni;
END;
DECLARE
Nome_exception EXCEPTION;
PRAGMA EXCEPTION_INIT(Nome_exception, -NumeroErroreOracle);
BEGIN
.
EXCEPTION
WHEN nome_exception THEN
istruzioni;
END;
7. Corso SQL
SQL (Structured Query Language)
Oracle aderisce allo standard ANSI/ISO SQL.
Lo scopo di SQL quello di fornire uninterfaccia a un database relazionale.
Le caratteristiche di SQL sono:
Elabora un gruppo di dati piuttosto che unit individuali
I comandi per il controllo del flusso non fanno parte di SQL originale
(PL/SQL unestensione di SQL che consente la programmazione
procedurale)
SQL comprende comandi che consentono di:
Interrogare i dati;
Inserire, aggiornare e cancellare righe in una tabella;
Creare, modificare e eliminare oggetti;
Controllare laccesso ai database e ai loro aggetti;
7.3. TABELLE
Le tabelle sono lunita base di memorizzazione dei dati in un database Oracle.
I dati vengono memorizzati in righe (record) e colonne (campi).
Una tabella viene definita con un nome tabella e un insieme di colonne per ognuna
delle quali si specifica il nome colonna, il datatype con la relativa dimensione.
Per ciascuna colonna della tabella possono essere eventualmente specificate delle
regole chiamate INTEGRITY CONTRAINTS (es. NOT NULL).
7.1.1.
CREATE DATABASE
7.1.2.
CREATE TABLESPACE
7.1.3.
CREATE TABLE
7.1.4.
CREATE INDEX
crea un indice in modo esplicito (gli indici vengono creati implicitamente per le
constraint di PK e UK).
7.1.5.
CREATE SEQUENCE
crea una sequence. Una sequence un oggetto del database per la generazione
automatica di valori interi sequenziali. Per ottenere i valori di una sequence bisogna
usare le pseudo-colonne CURRVAL e NEXTVAL.).
CREATE SEQUENCE nome_sequenza
INCREMENT BY 10;
7.1.6.
CREATE VIEW
crea una vista (query memorizzata che Oracle tratta come una tabella); per creare
una vista lutente deve avere grants dirette su tutti gli oggetti che fanno parte delle
viste.
CREATE VIEW nome_vista (lista_colonne)
AS SELECT lista_campi
FROM nome_tabella
WHERE condizione;
7.1.7.
CREATE SYNONYM
7.1.8.
crea un segmento di rollback che memorizza limmagine dei dati prima di una
variazione; il segmento di rollback viene creato offline e per essere usato deve
essere portato online.
CREATE ROLLBACK SEGMENT nome_rbs
TABLESPACE nome_tablespace;
Crea un rollback segment nella tablespace indicate usando i valori di default per i
parametri di storage.
7.1.9.
CREATE FUNCTION
crea una funzione cio un programma PL/SQL memorizzato nel database che
restituisce almeno un singolo valore.
CREATE [OR REPLACE] FUNCTION nome_funzione (argomento1 tipo_argomento datatype,
)
RETURN datatype
IS blocco PL/SQL;
7.1.10.
CREATE PROCEDURE
crea una procedura cio un oggetto PL/SQL che pu restituire zero, uno o pi valori.
CREATE [OR REPLACE] PROCEDURE nome_procedura (argomento1 tipo_argomento
datatype, )
AS blocco PL/SQL;
7.1.11.
CREATE PACKAGE
7.1.12.
crea il corpo del package che contiene il codice PL/SQL relativo a tutti gli oggetti
contenuti nel package, sia pubblici che privati; deve essere creato dopo che stato
creata la specifica del package.
CREATE PACKAGE BODY nome_package AS
corpo delle funzioni/procedure dichiarate nella specifica del package
corpo delle funzioni/procedure private
dichiarazione di cursori, variabili, costanti, exception privati;
END nome_package;
7.9. ALTER
7.1.13.
ALTER PACKAGE
7.1.14.
ALTER FUNCTION
7.1.15.
ALTER PROCEDURE
DROP
Il comando DROP viene usato per rimuovere tabelle, indici, cluster, tablespaces,
sequence, stored objects, e sinonimi
Ogni comando che libera spazio, tipo DROP, TRUNCATE o ALTER con la clausola
DEALLOCATE, pu provocare frammentazioni nelle tablespace!
DROP TABLE
7.11.
CLAUSOLA STORAGE
7.12.
DATATYPES
Ogni colonna di una tabella e ogni argomento di una STORED PROCEDURE manipolata da
ORACLE ha un suo Datatype che definisce il dominio possibile.
7.13.
INSERT
Per fare INSERT in una tavola lutente deve avere il privilegio INSERT sulla tavola o il
privilegio INSERT ANY TABLE.
Esempi:
Supponiamo di avere la seguente tabella test1:
1) INSERT INTO test1 [(lista colonne)] SELECT campo1, campo2 FROM tabella2;
Inserisce nella tabella test1 tutte le righe della vista o tabella tabella2, utilizzando una
subquery (SELECT FROM): poich manca lelenco delle colonne di test1 in cui vanno
inseriti i valori, la subquery deve restituire ordinatamente un valore per ogni colonna della
tabella. I valori restituiti dalla subquery devono essere dello stesso tipo (o tipo convertibile)
dei corrispondenti campi di test1.
2) INSERT INTO test1 VALUES (valore1, valore2);
Inserisce nella tabella test1 una sola riga: poich manca lelenco delle colonne di test1 in
cui vanno inseriti i valori la clausola VALUES deve contenere ordinatamente un valore per
ogni colonna della tabella.
3) INSERT INTO test1 (campo1) VALUES (valore);
Inserisce nella tabella test1 un record con uno solo dei due campi valorizzato.
4) INSERT INTO test1 VALUES (valore1, valore2) RETURNING campo1, campo2
INTO :t1, :t2;
Usa la clausola RETURNING per aggiornare le variabili t1 e t2 ai valori dei campi del record
inserito.
7.14.
UPDATE
Per fare UPDATE in una tavola lutente deve avere il privilegio UPDATE sulla tavola o il
privilegio UPDATE ANY TABLE.
Il comando UPDATE non pu creare nuovi record ma solo aggiornare quelli
esistenti
1) UPDATE nome_tabella SET nome_colonna=nuovo_valore WHERE
nome_colonna=valore;
Viene aggiornato il valore del campo nome_colonna solo per i record che soddisfano la
clausola WHERE (che pu essere riferita a tutti i campi della tabella).
2) UPDATE nome_tabella SET nome_colonna=valore
Viene aggiornato il valore del campo nome_colonna per tutti i record della tabella.
3) UPDATE nome_tabella1 t1_alias SET t1_alias.nome_colonna1 =(SELECT t2_alias.
nome_colonna1 FROM nome_tabella2 t2_alias WHERE
t1_alias.nome_colonna1=t2_alias.nome_colonna2)
Viene aggiornato il valore del campo nome_colonna1 su tutte le righe di tabella1 utilizzando
una subquery.
4) UPDATE nome_tabella SET nome_colonna =nuovo_valore WHERE
nome_colonna=valore RETURNING nome_colonna INTO :t1
Quando si usa la clausola RETURNING i valori dei campi aggiornati vengono memorizzati
nelle variabili specificate con INTO.
7.15.
DELETE e TRUNCATE
7.16.
SELECT
Per fare SELECT in una tavola lutente deve avere il privilegio SELECT sulla tavola o il
privilegio SELECT ANY TABLE.
SELECT * FROM nome_tabella
restituisce tutti i record (compresi i duplicati) della tabella visualizzando tutti i campi;
SELECT DISTINCT * FROM nome_tabella
restituisce solo una copia di ciascun record della tabella;
7.17.
LA CLAUSOLA GROUP BY
7.18.
OPERATORI di SET
SELECT FROM
UNION | INTERSECT | MINUS
SELECT FROM
INTERSECT= mostra solo le righe comuni alle due SELECT scartando i duplicati
MINUS= restituisce tutte le righe distinte della prima SELECT che non appartengono
allinsieme delle righe restituite dalla seconda SELECT
NOTA
Le colonne delle due SELECT devono avere lo stesso nome;
Se i nomi non coincidono occorre utilizzare degli alias.
7.19.
TIPI DI JOIN
OUTER JOIN= usata quando per la tabella tab1 che partecipa al join mancano record
correlati in tab2 e si vuole che la SELECT restituisca comunque tutti i record di tab2.
tab1.col1(+)=tab2.col2
SELF-JOIN= usata quando una tabella in relazione con se stessa
Come esempio si possono considerare le query gerarchiche che consentono di ordinare le
righe in base ad una gerarchia usando la clausola: [START WITH condizione] CONNECT
BY condizione;
START WITH specifica la riga/ghe radice della gerarchia
CONNECT BY specifica la relazione tra righe padre e righe figlie della gerarchia
SELECT * FROM tab1
START WITH campo1=valore
CONNECT BY PRIOR campo1=campo2
7.20.
SUBQUERY
7.21.
PSEUDO COLONNE
Una pseudo colonna si comporta come qualsiasi colonna di una tabella pur non essendovi
memorizzata realmente.
CURRVAL e NEXTVAL
Servono per riferirsi ai valori di una sequence nelle istruzioni SQL.
LEVEL
Per ciascuna riga restituita da una query gerarchica la pseudocolonna indica il livello nella
gerarchia: 1 per la radice, 2 per un figlio della radice
ROWID
Per ogni riga nel database la pseudo colonna ROWID restituisce lindirizzo che la identifica
univocamente.
ROWNUM
Per ogni riga restituita da una query, la pseudo colonna ROWNUM indica lordine con cui
Oracle seleziona le righe da una o pi tabelle.
7.22.
TRANSAZIONE
Una transazione una unit logica di lavoro che comprende una o pi istruzioni SQL
eseguite da un singolo utente.
In base allo standard SQL a cui Oracle aderisce, una transazione comincia con il primo
comando SQL eseguibile che modifica i dati e finisce quando esplicitamente COMMITTED o
ROLLED BACK da quellutente.
Le transazioni offrono allutente del database la possibilit di garantire variazioni
consistenti dei dati.
Una transazione dovrebbe consistere di tutte le istruzioni che costituiscono una
unit logica di lavoro in modo che i dati coinvolti siano in uno stato consistente
prima dellinizio della transazione e dopo la sua fine.
Comandi per il controllo della transazione
Consentono allutente di raggruppare le modifiche sui dati effettuate con comandi DML in
TRANSAZIONI logiche:
COMMIT
ROLLBACK
SAVEPOINT
SET TRANSACTION
COMMIT
Il comando COMMIT rende permanenti le variazioni effettuate durante una
transazione;
Le variazioni fatte dai comandi SQL di una transazione diventano visibili alle sessioni
di altri utenti solo dopo il COMMIT della transazione; eventuali accessi in lettura da
parte di altri utenti ai dati coinvolti da una diversa transazione sono sempre possibili
e visibili in maniera consistente; se una transazione contiene comandi DML che
richiedono LOCK sulle righe riservate da una diversa transazione, allora il comando
DML rimane in attesa fino a quando le righe non vengono rilasciate.
se la singola istruzione fallisce, viene eseguito un ROLLBACK che non annulla il resto della
transazione.
SAVEPOINT name;
-- istruzioni
ROLLBACK TO SAVEPOINT name;
SET TRANSACTION
Il comando SET TRANSACTION stabilisce che la transazione corrente READ
ONLY o READ WRITE, oppure assegna la transazione corrente ad uno specifico
ROLLBACK SEGMENT (nel caso in cui si vogliono assegnare transazioni di diverso
tipo a ROLLBACK SEGMENT di diverse dimensioni Oracle invece assegna la
transazione corrente al primo ROLLBACK SEGMENT libero-).
Esempio:
SET TRANSACTION USE ROLLBACK SEGMENT nome_segmento_rollback;
Se si usa il comando SET TRANSACTION questo deve essere il primo comando
della transazione !
7.23.
OPERATORI
(+) e (-)
operatori unari che indicano il segno algebrico di un numero
(*), (/), (+), (-)
operatori binari di moltiplicazione e divisione
(||)
operatore binario di concatenazione di stringhe
NOT, AND, OR
operatori logici
(=)
operatore di uguaglianza
(!=), (^=),(<>)
operatori di disuguaglianza
[NOT] BETWEEN x AND y
[Non] maggiore di o uguale a x e minore di o uguale a y
EXISTS
TRUE se la subquery restituisce almeno una riga
x [NOT] LIKE y [ESCAPE z]
TRUE se la stringa x contiene la stringa y. Allinterno di y il carattere speciale % indica una
stringa di zero o pi caratteri mentre il carattere speciale _ indica un qualsiasi carattere. I
caratteri speciali % e _ preceduti dal carattere che segue la clausola ESCAPE perdono la
loro peculiarit per riassumere il loro valore letterale.
IS [NOT] NULL
Verifica se un valore nullo. Il valore NULL indefinito e come tale non uguale a nessun
altro valore, neanche a un altro NULL.
(>),(>=),(<),(<=)
operatori di confronto
IN,(=ANY),(=SOME)
operatore di appartenenza ad una lista
NOT IN, (!=ALL)
operatore di non appartenenza
ANY,SOME
operatori di confronto con almeno un valore di una lista (devono essere preceduti da un
operatore di uguaglianza, disuguaglianza o confronto)
ALL
operatore di confronto con tutti i valori di una lista (deve essere preceduto da un operatore
di uguaglianza, disuguaglianza o confronto)
7.24.
CEIL(n)
Arrotonda n allintero superiore.
FLOOR(n)
Arrotonda n allintero inferiore.
ROUND(n [,m])
Restituisce n arrotondato a m cifre decimali (m positivo o senza segno); se m negativo,
larrotondamento viene effettuato alla posizione m della parte intera, dove la posizione 0
indica lunit (come quando m viene omesso).
TRUNC(n [,m])
Restituisce n troncato a m cifre decimali. Se m omesso tronca a 0 cifre decimali.
CHR(n)
Restituisce il carattere che ha il codice ASCII = n nel set di caratteri corrente per il
database.
CONCAT(char1,char2)
Restituisce char1 concatenato con char2
INITCAP(char)
Restituisce char con la prima lettera di ogni parola in maiuscolo
LOWER(char)
Restituisce char con tutti i caratteri minuscoli
LPAD(char1,n[,char2])
Esempio: SELECT LPAD(Pag. 1,10,*) ESEMPIO FROM DUAL;
LTRIM(char[,set])
Rimuove i caratteri set sulla parte sinistra di char; il set di default un singolo spazio.
REPLACE(char, stringa_da_cercare, stringa_da_sostituire)
Converte d (di tipo dato DATE) ad un valore di tipo VARCHAR2 nel formato eventualmente
specificato da fmt.
TO_CHAR(n[,fmt])
Converte n (di tipo dato NUMBER) ad un valore di tipo VARCHAR2 nel formato
eventualmente specificato da fmt.
TO_DATE(char,[,fmt])
Converte char (di tipo CHAR o VARCHAR2) ad un valore di tipo DATE. Fmt un formato
data che specifica quello di char, se omesso allora char deve essere nel formato data di
default.
TO_NUMBER(char[,fmt])
Converte char (di tipo CHAR o VARCHAR2) ad un tipo di dato NUMBER
LEAST(expr1, expr2, ...)
Restituisce il pi piccolo expr della lista; tutti gli expr successivi al primo sono
implicitamente convertiti al tipo di dato del primo.
GREATEST(expr1,expr2,...])
Restituisce lelemento della lista di valore maggiore; tutti gli expr successivi al primo sono
implicitamente convertiti al tipo di dato del primo.
MOD(m,n)
Restituisce il resto di m diviso n. Restituisce m se n zero
NVL(expr1, expr2)
Se expr1 nullo restituisce expr2, altrimenti restituisce expr1
USER
Restituisce lutente Oracle corrente
COUNT(*,[distinct, all] expr)
Restituisce il numero di righe di una query.
Se si specifica expr, la funzione restituisce il numero di righe escluse quelle per cui expr
nulla.
Si possono contare tutte le righe (all) o solo i valori distinti (distinct) di expr. Utilizzando
COUNT(*), la funzione restituisce tutte le righe inclusi i duplicati ed i nulli. E una funzione
di aggregazione.
MAX([distinct, all]expr)
Restituisce il valore massimo di expr. E una funzione di aggregazione.
MIN([distinct, all]expr)
Restituisce il valore minimo di expr. E una funzione di aggregazione.
SUM([distinct][all] n)
Restituisce la somma dei valori di n. E una funzione di aggregazione.
7.25.
NULLS
Ogni espressione aritmetica che contiene anche un solo null vale sempre null.
Tutti gli operatori, eccetto la concatenazione (||), e tutte le funzioni scalari, eccetto
NVL e TRANSLATE restituiscono null se uno degli operandi/argomenti null.
Per testare un null usare solo gli operatori IS NULL e IS NOT NULL.
Un non null uguale a nessun altro valore nemmeno ad un altro null!
8. SQL*Plus
Programma che consente di:
Scrivere, memorizzare, richiamare ed eseguire comandi SQL e blocchi PL/SQL;
Impostare laspetto del risultato di una query, memorizzarlo e stamparlo in forma di
report.
Elencare le colonne di ciascuna tabella e le loro definizioni;
Accedere ai dati di diversi database SQL e copiarli;
Eseguire comandi SQL e blocchi PL/SQL parametrizzati e di ricevere input da parte
dellutente;
Eseguire le operazioni di amministrazione del database.
Piccola nota: a volte i TAB possono dare problemi. Quindi in caso di situazioni anomale
verificare tutti i TAB presenti nello script SQL.
Posizione
Server
Tnsnames.ora
Client
Funzione
File di parametri per il processo listener con le
informazioni di connessione per ogni SID
Service name, host, protocollo, SID
Sqlnet.ora
There was a Japanese translation of the Oracle FAQ some time ago. Maybe it is still out there
(difficult to tell). If you want to translate one of the FAQs, or know about some cool translation
techniques, please let us know.
10. ESERCIZI
CREARE SULLO SCHEMA CORSO (gi definito su tablespace USERS) DUE TABELLE SIA_AZIENDE E
SIA_IMPIEGATI SAPENDO CHE FANNO PARTE DEL PROGETTO SISTEMA INFORMATIVO AZIENDALE
E CHE IN UNAZIENDA POSSONO LAVORARE MOLTI IMPIEGATI E CHE UN IMPIEGATO DEVE
LAVORARE IN UNA SOLA AZIENDA.
LE COLONNE CHE DEFINISCONO LA TABELLA SIA_AZIENDE SONO:
AZI_NUMAZI NUMBER(2)NOT NULL, CHIAVE
AZI_NOME VARCHAR2(14),
AZI_LOCALITA VARCHAR2(13),
LE COLONNE CHE DEFINISCONO LA TABELLA SIA_IMPIEGATI SONO:
IMP_NUMIMP NUMBER(4) NOT NULL, CHIAVE
IMP_NOME VARCHAR2(10),
IMP_RUOLO VARCHAR2(9),
IMP_DATA_ASSUNZIONE DATE,
IMP_SALARIO NUMBER(7,2),
AZI_NUMAZI NUMBER(2).
PASSI:
PROVARE UPDATE;
UPDATE SIA_AZIENDE
SET AZI_NOME='ETA';
.
PROVARE LA DELETE;
DELETE FROM SIA_AZIENDE;
(CANCELLA TUTTE LE RIGHE)
OPPURE
DELETE SIA_AZIENDE;
(CANCELLA TUTTE LE RIGHE)
DELETE FROM SIA_AZIENDE
WHERE AZI_NUMAZI = 1;
(CANCELLA SOLO LA RIGA CON AZI_NUMAZI = 1)
PROVARE LA TRUNCATE;
TRUNCATE TABLE SIA_AZIENDE;
FARE LA DROP DELLA TABELLA;
DROP TABLE SIA_AZIENDE;
RICREARE LA TABELLA SIA_AZIENDE SENZA CONSTRAINTS;
CREATE TABLE SIA_AZIENDE (
AZI_NUMAZI NUMBER(2),
AZI_NOME VARCHAR2(14),
AZI_LOCALITA VARCHAR2(13));
VERIFICARE DESCRIZIONE DELLA TABELLA;
DESC SIA_AZIENDE
_______________________
10,58
_______________________
ALFASUD
_______________________
26/10/1983
_______________________
15/12/97 10:35
_______________________
_______________________
1,3145E+12
_______________________
_______________________
Indicare il valore massimo che potr registrare in una colonna con tale Datatype:
NUMBER(6)
_______________________
CHAR(1)
_______________________
VARCHAR2(1)_______________________
NUMBER(3,2) _______________________
NUMBER(4,2) _______________________
VARCHAR2(4)_______________________
NUMBER(1)
_______________________
DATE
_______________________
DDL
DML
TCL
create index...
select ...
commit;
update...
drop table...
insert into...
alter tablespace...
rollback;
Quale istruzione risulta pi pericolosa: INSERT o UPDATE? (sottolinea la risposta)
Quale istruzione risulta pi pericolosa: DELETE, DROP o TRUNCATE? (sottolinea la risposta)
Quale istruzione risulta pi pericolosa: CREATE o ALTER? (sottolinea la risposta)
WHERE
FROM
column-list o lista delle colonne
tavola
condizione_2
AND/OR
;
AND/OR
HAVING
condizione_1
ORDER BY colonna_x
GROUP BY colonna_y
condizione_3
DISTINCT
SELECT
AND/OR
AND/OR
condizione_3
condizione_1
condizione_2
tavola
UPDATE
SET
valore_1
colonna_2
=
,
=
colonna_1
valore_2
WHERE
VALUES
(val1, val2)
(col1, col2)
INTO
;
INSERT
tavola
h)
i)
j)
k)
l)
m)
n)
o)
SELECT
FROM...
val1, val2
(col1, col2)
INTO
;
INSERT
tavola
condizione2
WHERE
tavola
;
DELETE
condizione1
AND/OR
___________________
X maggiore di Y
___________________
Z non nullo
___________________
Z compreso fra 10 e 20
___________________
___________________
X diverso da Y
___________________
x > 10 or y < 5
________________
b) valore assoluto di X
________________
c) segno di 58
________________
d) 20 alla 10 potenza
________________
e) segno di 0 (zero)
________________
________________
________________
h) 4 al cubo
________________
i)
radice quadrata di 16
________________
j)
________________
________________
scrivere una select che fornisca contemporaneamente tutti i suddetti valori, ciascuno sotto un alias
che corrisponda al carattere di punto elenco (a-b-c-...)
b) ciao
c) x12
d) x12
e) 15
f) N
___________________________
___________________________
___________________________
___________________________
___________________________
___________________________
___________________________
___________________________
___________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
____________________________
_____________________________
_____________________________
_____________________________
_____________________________
_____________________________
_____________________________
_____________________________
_____________________________
________________________
________________________
________________________
riportare le 4 istruzioni fondamentili della categoria DML________________________
________________________
________________________
________________________
riportare le 3 istruzioni pi comuni della categoria DDL ________________________
________________________
________________________
12. DOCENTE
prima si doveva usare il package DMBS_SQL, che per richiedeva molto codice e
tecnologia di duplicazione dei dati
adesso c un linguaggio intuitivo
molto meno codice
molto pi veloce, dal 30% fino al 400%
EXECUTE IMMEDIATE (prepara, esegue e dealloca uno stmt SQL)
vedi formato a pag.13
ed esempio molto pi chiaro a pag.14
alcuni modi per stabilire i diritti dellinvocante piuttosto che quelli del proprietario di
istruzioni centralizzate con AUTHID CURRENT_USER...
VARRAY type
UROWID type
new date e time type
TRIM ??
CAST ??
quanto sopra non viene spiegato...
bulk binding = assegnare una intera collezione dati con un passaggio
FORALL index IN inizio..fine
sql_stmt;
(non un for-loop)
BULK COLLECT INTO
collezione1, collezione2, ...
sono istruzioni molto pi veloci perch evitano i context switch
si pu usare nelle SELECT INTO, FETCH INTO, RETURNING INTO
vedi formati di esempio pag. 32 e successive
sezione dichiarativa dei parametri
xxx IN OUT NOCOPY datatype
xxx OUT NOCOPY datatype
utile quando si passano strutture di dati, non dati semplici
ci sono delle famiglie di API aggiuntive
DBMS_DEBUG
debug
DBMS_PROFILER
execution time profiler
DBMS_TRACING
trace
il terzo doc.PDF andrebbe conservato per scopiazzare le slide dei formati + esempi
Attention: In general, you should use the cost-based optimization approach. The rule-based
approach is available for the benefit of existing applications, but all new optimizer functionality uses
the cost-based approach.
The cost-based approach generally chooses an execution plan that is as good as or better than the
plan chosen by the rule-based approach, especially for large queries with multiple joins or multiple
indexes. The cost-based approach also improves productivity by eliminating the need for you to tune
your SQL statements yourself. Finally, many Oracle performance features are available only through
the cost-based approach.
Cost based optimization must be used to achieve efficient star query performance. Similarly, it must
be used with hash joins and histograms. Cost-based optimization is always used with parallel query
and with partition views. You must therefore perform ANALYZE at the partition level with partition
views.
13.2.
To enable cost-based optimization for a statement, collect statistics for the tables accessed by the
statement and be sure the OPTIMIZER_MODE initialization parameter is set to its default value of
CHOOSE.
You can also enable cost-based optimization in these ways:
To enable cost-based optimization for your session only, issue an ALTER SESSION statement
with an OPTIMIZER_GOAL option value of ALL_ROWS or FIRST_ROWS.
To enable cost-based optimization for an individual SQL statement, use any hint other than
RULE.
The plans generated by the cost-based optimizer depend on the sizes of the tables. When using the
cost-based optimizer with a small amount of data to prototype an application, do not assume that
the plan chosen for the full database will be the same as that chosen for the prototype.
13.3.
For non-uniformly distributed data, you should create histograms describing the data distribution of
particular columns. For this type of data, histograms enable the cost based optimization approach to
accurately guess the cost of executing a particular statement. For data that is uniformly distributed,
the optimizer does not need histograms to accurately estimate the selectivity of a query.
7.1.16.
Create histograms on columns that are frequently used in WHERE clauses of queries and have a
highly-skewed data distribution. You create a histogram by using the ANALYZE TABLE command. For
example, if you want to create a 10-bucket histogram on the SAL column of the EMP table, issue the
following statement:
ANALYZE TABLE emp COMPUTE STATISTICS FOR COLUMNS sal SIZE 10;
The SIZE keyword states the maximum number of buckets for the histogram. You would create a
histogram on the SAL column if there were an unusual number of employees with the same salary
and few employees with other salaries.
7.1.17.
The default number of buckets is 75. This value provides an appropriate level of detail for most data
distributions. However, since the number of buckets in the histogram, the sampling rate, and the
data distribution all affect the usefulness of a histogram, you may need to experiment with different
numbers of buckets to obtain the best results.
If the number of frequently occurring distinct values in a column is relatively small, then it is useful
to set the number of buckets to be greater than the number of frequently occurring distinct values.
7.1.18.
Viewing Histograms
You can find information about existing histograms in the database through the following data
dictionary views:
USER_HISTOGRAMS
ALL_HISTOGRAMS
DBA_HISTOGRAMS
Find the number of buckets in each column's histogram in:
USER_TAB_COLUMNS
ALL_TAB_COLUMNS
DBA_TAB_COLUMNS
13.4.
Generating Statistics
Since the cost-based approach relies on statistics, you should generate statistics for all tables,
clusters, and indexes accessed by your SQL statements before using the cost-based approach. If the
size and data distribution of these tables changes frequently, you should generate these statistics
regularly to ensure that they accurately represent the data in the tables.
Oracle can generate statistics using these techniques:
Use estimation, rather than computation, unless you think you need exact values:
Computation always provides exact values, but can take longer than estimation. The time
necessary to compute statistics for a table is approximately the time required to perform a full
table scan and a sort of the rows of the table.
Estimation is often much faster than computation, especially for large tables, because
estimation never scans the entire table.
To perform a computation, Oracle requires enough space to perform a scan and sort of the table. If
there is not enough space in memory, temporary space may be required. For estimations, Oracle
requires enough space to perform a scan and sort of all of the rows in the requested sample of the
table.
Because of the time and space required for the computation of table statistics, it is usually best to
perform an estimation with a 20% sample size for tables and clusters. For indexes, computation does
not take up as much time or space, so it is best to perform a computation.
When you generate statistics for a table, column, or index, if the data dictionary already contains
statistics for the analyzed object, Oracle updates the existing statistics with the new ones. Oracle
invalidates any currently parsed SQL statements that access any of the analyzed objects. When such
a statement is next executed, the optimizer automatically chooses a new execution plan based on
the new statistics. Distributed statements issued on remote databases that access the analyzed
objects use the new statistics when they are next parsed.
Some statistics are always computed, regardless of whether you specify computation or estimation.
If you choose estimation and the time saved by estimating a statistic is negligible, Oracle computes
the statistic.
You can generate statistics with the ANALYZE command.
Example: This example generates statistics for the EMP table and its indexes:
The execution plan produced by the optimizer can vary depending upon the optimizer's goal.
Optimizing for best throughput is more likely to result in a full table scan rather than an indexed
scan, or a sort-merge join rather than a nested loops join. Optimizing for best response time is more
likely to result in an index scan or a nested loops join.
For example, consider a join statement that can be executed with either a nested loops operation or
a sort-merge operation. The sort-merge operation may return the entire query result faster, while the
nested loops operation may return the first row faster. If the goal is best throughput, the optimizer is
more likely to choose a sort-merge join. If the goal is best response time, the optimizer is more likely
to choose a nested loops join.
Choose a goal for the optimizer based on the needs of your application:
For applications performed in batch, such as Oracle Reports applications, optimize for best
throughput. Throughput is usually more important in batch applications because the user
initiating the application is only concerned with the time necessary for the application to
complete. Response time is less important because the user does not examine the results of
individual statements while the application is running.
For interactive applications, such as Oracle Forms applications or SQL*Plus queries, optimize
for best response time. Response time is usually important in interactive applications because
the interactive user is waiting to see the first row accessed by the statement.
For queries that use ROWNUM to limit the number of rows, optimize for best response time.
Because of the semantics of ROWNUM queries, optimizing for response time provides the best
results.
By default, the cost-based approach optimizes for best throughput. You can change the goal of the
cost-based approach in these ways:
To change the goal of the cost-based approach for all SQL statements in your session, issue
an ALTER SESSION statement with the OPTIMIZER_GOAL option.
To specify the goal of the cost-based approach for an individual SQL statement, use the
ALL_ROWS or FIRST_ROWS hint.
Example: This statement changes the goal of the cost-based approach for your session to best
response time:
ALTER SESSION SET OPTIMIZER_GOAL = FIRST_ROWS;
13.6.
OPTIMIZER_GOAL
OPTIMIZER_MODE
OPTIMIZER_PERCENT_PARALLEL
HASH_JOIN_ENABLED
HASH_AREA_SIZE
HASH_MULTIBLOCK_IO_COUNT
SORT_AREA_SIZE
SORT_DIRECT_WRITES
SORT_WRITE_BUFFER_SIZE
DB_FILE_MULTIBLOCK_READ_COUNT
large value gives cheaper table scan cost and favors table
scans over indexes
ALWAYS_ANTI_JOIN
PARTITION_VIEW_ENABLED
V733_PLANS_ENABLED
BITMAP_MERGE_AREA_SIZE
is the size of the area used to merge the different bitmaps that
match a range predicate. Larger size will favor use of bitmap
indexes for range predicates.
Note that the following sort parameters can now be modified using ALTER SESSION SET ... or ALTER
SYSTEM SET ... DEFERRED:
SORT_AREA_SIZE
SORT_AREA_RETAINED_SIZE
SORT_DIRECT_WRITES
SORT_WRITE_BUFFERS
SORT_WRITE_BUFFER_SIZE
SORT_READ_FAC
See Also: Oracle7 Server Reference for complete information about each parameter.
13.7.
The cost-based optimization approach assumes that a query will be executed on a multiuser system
with a fairly low buffer cache hit rate. Thus a plan selected by cost-based optimization may not be
the best plan for a single user system with a large buffer cache. Timing a query plan on a single user
system with a large cache may not be a good predictor of performance for the same query on a busy
multiuser system.
Analyzing a table uses more system resources than analyzing an index. It may be helpful to analyze
the indexes for a table separately, with a higher sampling rate.
Use of access path and join method hints causes the cost-based optimization to be invoked. Since
cost-based optimization is dependent on statistics, it is important to analyze all tables referenced in a
query which has hints, even though rule-based optimization may have been selected as the system
default.
14.Using Rule-Based Optimization
If you have developed applications using version 6 of Oracle and have carefully tuned your SQL
statements based on the rules of the optimizer, you may want to continue using rule-based
optimization when you upgrade these applications to Oracle7.
If you neither collect statistics nor add hints to your SQL statements, your statements will use rulebased optimization. However, you should eventually migrate your existing applications to use the
cost-based approach, because the rule-based approach will not be available in future versions of
Oracle.
You can enable cost-based optimization on a trial basis simply by collecting statistics. You can then
return to rule-based optimization by deleting them or by setting either the value of the
OPTIMIZER_MODE initialization parameter or the OPTIMIZER_GOAL parameter of the ALTER
SESSION command to RULE. You can also use this value if you want to collect and examine statistics
for your data without using the cost-based approach.
15.Introduction to Hints
As an application designer, you may know information about your data that the optimizer cannot. For
example, you may know that a certain index is more selective for certain queries than the optimizer
can determine. Based on this information, you may be able to choose a more efficient execution plan
than the optimizer can. In such a case, you can use hints to force the optimizer to use your chosen
execution plan.
Hints are suggestions that you give the optimizer for optimizing a SQL statement. Hints allow you to
make decisions usually made by the optimizer. You can use hints to specify
where:
DELETE SELECT Is a DELETE, SELECT, or UPDATE keyword that begins a statement block. Comments
UPDATE
containing hints can only appear after these keywords.
+
Is a plus sign that causes Oracle to interpret the Comment as a list of hints. The plus
sign must follow immediately after the Comment delimiter (no space is permitted).
hint
Is one of the hints discussed in this section. If the Comment contains multiple hints,
each pair of hints must be separated by at least one space.
text
If you specify hints incorrectly, Oracle ignores them but does not return an error:
Oracle ignores hints if the Comment containing them does not follow a DELETE, SELECT, or
UPDATE keyword.
Oracle ignores hints containing syntax errors, but considers other correctly specified hints
within the same Comment.
Oracle ignores combinations of conflicting hints, but considers other hints within the same
Comment.
Oracle also ignores hints in all SQL statements in environments which use PL/SQL Version 1, such as
SQL*Forms Version 3 triggers.
The optimizer only recognizes hints when using the cost-based approach. If you include any hint
(except the RULE hint) in a statement block, the optimizer automatically uses the cost-based
approach.
The following sections show the syntax of each hint.
17.Hints for Optimization Approaches and Goals
The hints described in this section allow you to choose between the cost-based and the rule-based
optimization approaches and, with the cost-based approach, between the goals of best throughput
and best response time.
ALL_ROWS
FIRST_ROWS
CHOOSE
RULE
If a SQL statement contains a hint that specifies an optimization approach and goal, the optimizer
uses the specified approach regardless of the presence or absence of statistics, the value of the
OPTIMIZER_MODE initialization parameter, and the OPTIMIZER_GOAL parameter of the ALTER
SESSION command.
Note: The optimizer goal applies only to queries submitted directly. Use hints to determine the
access path for any SQL statements submitted from within PL/SQL. The ALTER SESSION
OPTIMIZER_GOAL statement does not affect SQL that is run from within PL/SQL.
17.1.
ALL_ROWS
The ALL_ROWS hint explicitly chooses the cost-based approach to optimize a statement block with a
goal of best throughput (that is, minimum total resource consumption). For example, the optimizer
uses the cost-based approach to optimize this statement for best throughput:
SELECT /*+ ALL_ROWS */ empno, ename, sal, job
FROM emp
WHERE empno = 7566;
17.2.
FIRST_ROWS
The FIRST_ROWS hint explicitly chooses the cost-based approach to optimize a statement block with
a goal of best response time (minimum resource usage to return first row).
This hint causes the optimizer to make these choices:
If an index scan is available, the optimizer may choose it over a full table scan.
If an index scan is available, the optimizer may choose a nested loops join over a sort-merge
join whenever the associated table is the potential inner table of the nested loops.
If an index scan is made available by an ORDER BY clause, the optimizer may choose it to
avoid a sort operation.
For example, the optimizer uses the cost-based approach to optimize this statement for best
response time:
SELECT /*+ FIRST_ROWS */ empno, ename, sal, job
FROM emp
WHERE empno = 7566;
The optimizer ignores this hint in DELETE and UPDATE statement blocks and in SELECT statement
blocks that contain any of the following syntax:
These statements cannot be optimized for best response time because Oracle must retrieve all rows
accessed by the statement before returning the first row. If you specify this hint in any of these
statements, the optimizer uses the cost-based approach and optimizes for best throughput.
If you specify either the ALL_ROWS or FIRST_ROWS hint in a SQL statement and the data dictionary
contains no statistics about any of the tables accessed by the statement, the optimizer uses default
statistical values (such as allocated storage for such tables) to estimate the missing statistics and
subsequently to choose an execution plan. Since these estimates may not be as accurate as those
generated by the ANALYZE command, you should use the ANALYZE command to generate statistics
for all tables accessed by statements that use cost-based optimization. If you specify hints for access
paths or join operations along with either the ALL_ROWS or FIRST_ROWS hint, the optimizer gives
precedence to the access paths and join operations specified by the hints.
17.3.
CHOOSE
The CHOOSE hint causes the optimizer to choose between the rule-based approach and the costbased approach for a SQL statement based on the presence of statistics for the tables accessed by
the statement. If the data dictionary contains statistics for at least one of these tables, the optimizer
uses the cost-based approach and optimizes with the goal of best throughput. If the data dictionary
contains no statistics for any of these tables, the optimizer uses the rule-based approach.
SELECT /*+ CHOOSE */
empno, ename, sal, job
FROM emp
WHERE empno = 7566;
17.4.
RULE
The RULE hint explicitly chooses rule-based optimization for a statement block. This hint also causes
the optimizer to ignore any other hints specified for the statement block. For example, the optimizer
uses the rule-based approach for this statement:
SELECT
--+ RULE
empno, ename, sal, job
FROM emp
WHERE empno = 7566;
The RULE hint, along with the rule-based approach, will not be available in future versions of Oracle.
18.Hints for Access Methods
Each hint described in this section suggests an access method for a table.
FULL
ROWID
CLUSTER
HASH
HASH_AJ
INDEX
INDEX_ASC
INDEX_COMBINE
INDEX_DESC
INDEX_FFS
MERGE_AJ
AND_EQUAL
USE_CONCAT
Specifying one of these hints causes the optimizer to choose the specified access path only if the
access path is available based on the existence of an index or cluster and the syntactic constructs of
the SQL statement. If a hint specifies an unavailable access path, the optimizer ignores it.
You must specify the table to be accessed exactly as it appears in the statement. If the statement
uses an alias for the table, you must use the alias, rather than the table name, in the hint. The table
name within the hint should not include the schema name, if the schema name is present in the
statement.
18.1.
FULL
The FULL hint explicitly chooses a full table scan for the specified table. The syntax of the FULL hint
is
FULL(table)
where table specifies the name or alias of the table on which the full table scan is to be performed.
For example, Oracle performs a full table scan on the ACCOUNTS table to execute this statement,
even if there is an index on the ACCNO column that is made available by the condition in the WHERE
clause:
SELECT /*+ FULL(a) Don't use the index on ACCNO */ accno, bal
FROM accounts a
WHERE accno = 7086854;
Note: Because the ACCOUNTS table has an alias, A, the hint must refer to the table by its alias, rather than by its
name. Also, do not specify schema names in the hint, even if they are specified in the FROM clause.
The fast full scan was an operation that appeared in Oracle 7.3, although in that version of Oracle there was a time
when it had to be invoked explicitly by the hing /*+ index_ffs(alias index) */.
Under this operation, the index would not be treated like an index, it would be treated as if it were a narrow table,
holding just the columns defined as part of the index. Because of this, Oracle is able to read the index segment
using multiblock reads (discarding branch blocks as it goes), even using parallel query methods to read the
segment in the shortest possible time. Of course, the data coming out of an index fast full scan will not be sorted.
The full scan, however, simply means that Oracle walks the index from end to end, following leaf blocks in the right
order. This can be quite slow, as Oracle can only use single block reads to do this (although in fact 8.1.5ish
introduced the _non_contiguous_multiblock_read, and various readahead strategies). However the results do come
out in index order without the need for an sort. You might notice that Oracle tends to choose this option when there
is an index that happens to suit the order by clause of a query, even if it doesn't suit the where clause of the query this may also result in a SORT ORDER BY (NO SORT) line appearing in your execution plan.
18.2.
ROWID
The ROWID hint explicitly chooses a table scan by ROWID for the specified table. The syntax of the
ROWID hint is
ROWID(table)
where table specifies the name or alias of the table on which the table access by ROWID is to be
performed.
18.3.
CLUSTER
The CLUSTER hint explicitly chooses a cluster scan to access the specified table. The syntax of the
CLUSTER hint is
CLUSTER(table)
where table specifies the name or alias of the table to be accessed by a cluster scan.
The following example illustrates the use of the CLUSTER hint.
SELECT --+ CLUSTER emp
ename, deptno
FROM emp, dept
WHERE deptno = 10 AND
emp.deptno = dept.deptno;
18.4.
HASH
The HASH hint explicitly chooses a hash scan to access the specified table. The syntax of the HASH
hint is
HASH(table)
where table specifies the name or alias of the table to be accessed by a hash scan.
18.5.
HASH_AJ
The HASH_AJ hint transforms a NOT IN subquery into a hash anti-join to access the specified table.
The syntax of the HASH_AJ hint is
HASH_AJ(table)
where table specifies the name or alias of the table to be accessed.
18.6.
INDEX
The INDEX hint explicitly chooses an index scan for the specified table. The syntax of the INDEX hint
is
where:
table Specifies the name or alias of the table associated with the index to be scanned.
index Specifies an index on which an index scan is to be performed.
This hint may optionally specify one or more indexes:
If this hint specifies a single available index, the optimizer performs a scan on this index. The
optimizer does not consider a full table scan or a scan on another index on the table.
If this hint specifies a list of available indexes, the optimizer considers the cost of a scan on
each index in the list and then performs the index scan with the lowest cost. The optimizer
may also choose to scan multiple indexes from this list and merge the results, if such an
access path has the lowest cost. The optimizer does not consider a full table scan or a scan on
an index not listed in the hint.
If this hint specifies no indexes, the optimizer considers the cost of a scan on each available
index on the table and then performs the index scan with the lowest cost. The optimizer may
also choose to scan multiple indexes and merge the results, if such an access path has the
lowest cost. The optimizer does not consider a full table scan.
For example, consider this query, which selects the name, height, and weight of all male patients in a
hospital:
SELECT name, height, weight
FROM patients
WHERE sex = 'M';
Assume that there is an index on the SEX column and that this column contains the values M and F.
If there are equal numbers of male and female patients in the hospital, the query returns a relatively
large percentage of the table's rows and a full table scan is likely to be faster than an index scan.
However, if a very small percentage of the hospital's patients are male, the query returns a relatively
small percentage of the table's rows and an index scan is likely to be faster than a full table scan.
The number of occurrences of each distinct column value is not available to the optimizer. The costbased approach assumes that each value has an equal probability of appearing in each row. For a
column having only two distinct values, the optimizer assumes each value appears in 50% of the
rows, so the cost-based approach is likely to choose a full table scan rather than an index scan.
If you know that the value in the WHERE clause of your query appears in a very small percentage of
the rows, you can use the INDEX hint to force the optimizer to choose an index scan. In this
statement, the INDEX hint explicitly chooses an index scan on the SEX_INDEX, the index on the SEX
column:
SELECT /*+ INDEX(patients sex_index) Use SEX_INDEX, since there
are few male patients
*/
name, height, weight
FROM patients
WHERE sex = 'M';
18.7.
INDEX_ASC
The INDEX_ASC hint explicitly chooses an index scan for the specified table. If the statement uses an
index range scan, Oracle scans the index entries in ascending order of their indexed values. The
syntax of the INDEX_ASC hint is
Each parameter serves the same purpose as in the INDEX hint.
Because Oracle's default behavior for a range scan is to scan index entries in ascending order of their
indexed values, this hint does not currently specify anything more than the INDEX hint. However,
since Oracle Corporation does not guarantee that the default behavior for an index range scan will
remain the same in future versions of Oracle, you may want to use the INDEX_ASC hint to specify
ascending range scans explicitly, should the default behavior change.
18.8.
INDEX_COMBINE
If no indexes are given as arguments for the INDEX_COMBINE hint, the optimizer will use on the
table whatever boolean combination of bitmap indexes has the best cost estimate. If certain indexes
are given as arguments, the optimizer will try to use some boolean combination of those particular
bitmap indexes. The syntax of INDEX_COMBINE is
18.9.
INDEX_DESC
The INDEX_DESC hint explicitly chooses an index scan for the specified table. If the statement uses
an index range scan, Oracle scans the index entries in descending order of their indexed values.
Syntax of the INDEX_DESC hint is
Each parameter serves the same purpose as in the INDEX hint. This hint has no effect on SQL
statements that access more than one table. Such statements always perform range scans in
ascending order of the indexed values. For example, consider this table, which contains the
temperature readings of a tank of water holding marine life:
or equal to T to Step 3. Note that Step 3 needs only the greatest of these values. Using the
INDEX_DESC hint, you can write an equivalent query that reads only one TIME value from the index:
SELECT /*+ INDEX_DESC(tank_readings un_time) */ temperature
FROM tank_readings
WHERE time <= TO_DATE(:t)
AND ROWNUM = 1
ORDER BY time DESC;
The execution plan for this query looks like the following figure:
INDEX_FFS
This hint causes a fast full index scan to be performed rather than a full table scan. The syntax of
INDEX_FFS is
18.11.
MERGE_AJ
The MERGE_AJ hint transforms a NOT IN subquery into a merge anti-join to access the specified
table. The syntax of the MERGE_AJ hint is
MERGE_AJ(table)
where table specifies the name or alias of the table to be accessed.
18.12.
AND_EQUAL
The AND_EQUAL hint explicitly chooses an execution plan that uses an access path that merges the
scans on several single-column indexes. The syntax of the AND_EQUAL hint is:
where:
table Specifies the name or alias of the table associated with the indexes to be merged.
index
Specifies an index on which an index scan is to be performed. You must specify at least two
indexes. You cannot specify more than five.
18.13.
USE_CONCAT
The USE_CONCAT hint forces combined OR conditions in the WHERE clause of a query to be
transformed into a compound query using the UNION ALL set operator. Normally, this transformation
occurs only if the cost of the query using the concatenations is cheaper than the cost without them.
19.Hints for Join Orders
The hints in this section suggest join orders:
ORDERED
STAR
19.1.
ORDERED
The ORDERED hint causes Oracle to join tables in the order in which they appear in the FROM clause.
For example, this statement joins table TAB1 to table TAB2 and then joins the result to table TAB3:
SELECT /*+ ORDERED */ tab1.col1, tab2.col2, tab3.col3
FROM tab1, tab2, tab3
WHERE tab1.col1 = tab2.col1
AND tab2.col1 = tab3.col1;
If you omit the ORDERED hint from a SQL statement performing a join, the optimizer chooses the
order in which to join the tables.
You may want to use the ORDERED hint to specify a join order if you know something about the
number of rows selected from each table that the optimizer does not. Such information would allow
you to choose an inner and outer table better than the optimizer could.
19.2.
STAR
The STAR hint forces the large table to be joined last using a nested loops join on the index. The
optimizer will consider different permutations of the small tables.
Usually, if you analyze the tables the optimizer will choose an efficient star plan. You can also use
hints to improve the plan. The most precise method is to order the tables in the FROM clause in the
order of the keys in the index, with the large table last. Then use the following hints:
/*+ ORDERED USE_NL(facts) INDEX(facts fact_concat) */
A more general method is to use the STAR hint /*+ STAR */.
20.Hints for Join Operations
Each hint described in this section suggests a join operation for a table.
USE_NL
USE_MERGE
NO_MERGE
USE_HASH
You must specify a table to be joined exactly as it appears in the statement. If the statement uses an
alias for the table, you must use the alias rather than the table name in the hint. The table name
within the hint should not include the schema name, if the schema name is present in the statement.
The USE_NL and USE_MERGE hints must be used with the ORDERED hint. Oracle uses these hints
when the referenced table is forced to be the inner table of a join, and they are ignored if the
referenced table is the outer table.
20.1.
USE_NL
The USE_NL hint causes Oracle to join each specified table to another row source with a nested loops
join using the specified table as the inner table. The syntax of the USE_NL hint is
where table is the name or alias of a table to be used as the inner table of a nested loops join.
For example, consider this statement, which joins the ACCOUNTS and CUSTOMERS tables. Assume
that these tables are not stored together in a cluster:
SELECT accounts.balance,
customers.last_name,
customers.first_name
FROM accounts, customers
WHERE accounts.custno = customers.custno;
Since the default goal of the cost-based approach is best throughput, the optimizer will choose either
a nested loops operation or a sort-merge operation to join these tables, depending on which is likely
to return all the rows selected by the query more quickly.
However, you may want to optimize the statement for best response time, or the minimal elapsed
time necessary to return the first row selected by the query, rather than best throughput. If so, you
can force the optimizer to choose a nested loops join by using the USE_NL hint. In this statement,
the USE_NL hint explicitly chooses a nested loops join with the CUSTOMERS table as the inner table:
SELECT /*+ ORDERED USE_NL(CUSTOMERS) USE N-L TO GET FIRST ROW
FASTER */
accounts.balance,
customers.last_name,
customers.first_name
FROM accounts, customers
WHERE accounts.custno = customers.custno;
In many cases, a nested loops join returns the first row faster than a sort-merge join. A nested loops
join can return the first row after reading the first selected row from one table and the first matching
row from the other and combining them, while a sort-merge join cannot return the first row until
after reading and sorting all selected rows of both tables and then combining the first rows of each
sorted row source.
20.2.
USE_MERGE
The USE_MERGE hint causes Oracle to join each specified table with another row source with a sortmerge join. The syntax of the USE_MERGE hint is
where table is a table to be joined to the row source resulting from joining the previous tables in the
join order using a sort-merge join.
20.3.
NO_MERGE
The NO_MERGE hint causes Oracle not to merge mergeable views. The syntax of the NO_MERGE hint
is:
This hint is most often used to reduce the number of possible permutations for a query and make
optimization faster. This hint has no arguments. For example,
SELECT*
FROMt1,(SELECT/*+NO_MERGE*/
*
FROMt2)v ...
causes view v not to be merged.
20.4.
USE_HASH
The USE_HASH hint causes Oracle to join each specified table with another row source with a hash
join. The syntax of the USE_HASH hint is
where table is a table to be joined to the row source resulting from joining the previous tables in the
join order using a hash join.
21.Hints for Parallel Query Execution
The hints described in this section determine how statements are parallelized or not parallelized
when using the parallel query feature.
PARALLEL
NOPARALLEL
21.1.
PARALLEL
The PARALLEL hint allows you to specify the desired number of concurrent query servers that can be
used for the query. The syntax is
The PARALLEL hint must use the table alias if an alias is specified in the query. The PARALLEL hint
can then take two values separated by commas after the table name. The first value specifies the
degree of parallelism for the given table, the second value specifies how the table is to be split
among the instances of a parallel server. Specifying DEFAULT or no value signifies the query
coordinator should examine the settings of the initialization parameters (described in a later section)
to determine the default degree of parallelism.
In the following example, the PARALLEL hint overrides the degree of parallelism specified in the EMP
table definition:
SELECT/*+FULL(SCOTT_EMP)PARALLEL(SCOTT_EMP,5)*/
Ename
FROM scott.emp scott_emp;
In the next example, the PARALLEL hint overrides the degree of parallelism specified in the EMP table
definition and tells the optimizer to use the default degree of parallelism determined by the
initialization parameters. This hint also specifies that the table should be split among all of the
available instances, with the default degree of parallelism on each instance.
SELECT /*+ FULL(scott_emp) PARALLEL(scott_emp, DEFAULT,DEFAULT) */
ename
FROM scott.emp scott_emp;
21.2.
NOPARALLEL
The NOPARALLEL hint allows you to disable parallel scanning of a table, even if the table was created
with a PARALLEL clause. The following example illustrates the NOPARALLEL hint:
SELECT /*+ NOPARALLEL(scott_emp) */
ename
FROM scott.emp scott_emp;
22.1.
CACHE
The CACHE hint specifies that the blocks retrieved for the table in the hint are placed at the most
recently used end of the LRU list in the buffer cache when a full table scan is performed. This option
is useful for small lookup tables. In the following example, the CACHE hint overrides the table's
default caching specification:
SELECT /*+ FULL (scott_emp) CACHE(scott_emp) */
ename
FROM scott.emp scott_emp;
22.2.
NOCACHE
The NOCACHE hint specifies that the blocks retrieved for this table are placed at the least recently
used end of the LRU list in the buffer cache when a full table scan is performed. This is the normal
behavior of blocks in the buffer cache. The following example illustrates the NOCACHE hint:
SELECT /*+ FULL(scott_emp) NOCACHE(scott_emp) */
ename
FROM scott.emp scott_emp;
22.3.
PUSH_SUBQ
The PUSH_SUBQ hint causes nonmerged subqueries to be evaluated at the earliest possible place in
the execution plan. Normally, subqueries that are not merged are executed as the last step in the
execution plan. If the subquery is relatively inexpensive and reduces the number of rows
significantly, it will improve performance to evaluate the subquery earlier.
The hint will have no effect if the subquery is applied to a remote table or one that is joined using a
merge join.
23.Considering Alternative SQL Syntax
Because SQL is a flexible language, more than one SQL statement may meet the needs of your
application. Although two SQL statements may produce the same result, Oracle may process one
faster than the other. You can use the results of the EXPLAIN PLAN statement to compare the
execution plans and costs of the two statements and determine which is more efficient.
This example shows the execution plans for two SQL statements that perform the same function.
Both statements return all the departments in the DEPT table that have no employees in the EMP
table. Each statement searches the EMP table with a subquery. Assume there is an index,
DEPTNO_INDEX, on the DEPTNO column of the EMP table.
This is the first statement and its execution plan:
SELECT dname, deptno
FROM dept
WHERE deptno NOT IN
(SELECT deptno FROM emp);
23.1.
In merito a %ROWTYPE
1) il %ROWTYPE deve essere usato solo per dichiarare variabili di appoggio per contenere il
contenuto di cursori dichiarati esplicitamente (rVariabile cCursore%ROWTYPE).
2) IL %ROWTYPE non deve essere MAI usato verso tabelle o viste, in quanto perfettamente
analogo a scrivere select * from..., ovvero se il numero o l'ordinamento dei campi in una tabella
cambia, la form deve essere ricompilata, che un errore di cattiva programmazione.
Sfrutto il punto 2 per evidenziare alcuni corollari, che possono ssembrare banali, ma magari per un
novizio non lo sono.
2b) MAI usare SELECT *
2c) nelle insert dichiarare SEMPRE esplicitamente le colonne: INSERT INTO TABELLA (COLONNA1,
COLONNA2, ECC...) VALUES(1,2,ECC...)
2d) nelle CREATE VIEW scrivere SEMPRE ESPLICITAMENTE LE COLONNE: CREATE VIEW VISTA
(COLONNA1, COLONNA2, ECC...)
In merito a %TYPE, l'utilizzo di questa sintassi DEVE essere incentivato, infatti se il formato di una
colonna cambia, i programmi si riallineano automaticamente, basta ricompilarli, oltretutto la cosa
viene segnalata esplicitamente con l'errore di cui sopra, se non si facesse cos, invece, avremmo un
generico "numeric or value error", con grandi malditesta per caprine la causa e sopratutto la
necessit di modificare il codice per riallinearlo al nuovo formato, con un potenziale impatto in
cascata.
EX1
QUERY LENTA
SELECT DISTINCT a.*,
b.billing,
b.codazi,
c.desazi,
d.serviz,
e.intmora,
e.dilatori,
e.flag,
e.mora,
(RTRIM (e.destop)|| RTRIM (e.desvia)) AS recapito,
f.descon,
g.desmod
FROM cliente a,
billing b,
azienda c,
servizio d,
regole e,
convenzioni f,
pagamento g,
cliente h
WHERE a.codalt = h.codalt
AND h.codalt = b.codalt
AND b.codazi = c.codazi
AND b.billing = e.billing
AND e.codcon = f.codcon
AND e.codmod = g.codmod
AND b.codser = d.codser
AND a.codalt = 'PAR'
AND e.datfine =
(SELECT MAX (e.datfine)
FROM regole e, billing b, cliente a
WHERE b.billing = e.billing
AND b.codalt = a.codalt
AND a.codalt = 'PAR')
STESSA QUERY VELOCE
SELECT DISTINCT a.*,
b.billing,
b.codazi,
(SELECT c.desazi FROM azienda c WHERE c.codazi = b.codazi) AS desazi,
(SELECT d.serviz FROM servizio d WHERE b.codser = d.codser) AS desser,
e.intmora,
e.dilatori,
e.flag,
e.mora,
(RTRIM (e.destop)|| RTRIM (e.desvia)) AS recapito,
(SELECT f.descon FROM convenzioni f WHERE e.codcon = f.codcon) AS descon,
(SELECT g.desmod FROM pagamento g WHERE e.codmod = g.codmod) AS desmod
FROM cliente a,
billing b,
regole e,
cliente h
WHERE a.codalt = h.codalt
AND h.codalt = b.codalt
AND b.billing = e.billing
AND a.codalt = 'PAR'
AND TO_CHAR (e.datfine, 'YYYYMMDD') || e.billing IN (
24.2.
EX3
SELECT s.ROWID,
s.ser_ute,
s.ser_puntopresa,
s.ser_codsersub,
l.let_matricola,
l.let_cod_fab
FROM serviz s, lettur l
WHERE s.ser_ute = 'BO'
AND l.let_ute = s.ser_ute
AND l.let_puntopresa = s.ser_puntopresa
AND s.ser_stato_cont = '5'
AND s.ser_codsersub IS NULL
AND l.let_dat_lettur =
(SELECT MAX (l2.let_dat_lettur)
FROM lettur l2
WHERE l2.let_ute = s.ser_ute
AND l2.let_puntopresa = s.ser_puntopresa
AND l2.let_tip_lettur != 'M')
AND 0 <
(SELECT COUNT (0)
FROM serviz s1, lettur l1
WHERE s1.ser_ute = 'BO'
AND s1.ser_statoserv = '1'
AND s1.ser_datainifor >= s.ser_datainifor
AND l1.let_ute = s1.ser_ute
AND l1.let_puntopresa = s1.ser_puntopresa
AND l.let_matricola = l1.let_matricola
AND l.let_cod_fab = l1.let_cod_fab
AND l1.let_dat_lettur > l.let_dat_lettur)
Di fronte ad una query del genere la prima cosa da fare lexplan Plan (CTRL+E):
Bisogna verificare se gli indici che vengono usati automaticamente sono i pi adeguati cio quelli che
hanno una maggiore incidenza a livello di maggiore selezione.
Lindice I2 non adeguato perch si basa su statoser e ute mentre sarebbe pi adeguato usare I1
basato su puntopresa e ute. Si pu forzare con: /*index(s1I1_serviz)*/ per a causa del
ANDs1.ser_statoserv='1'c un ulteriore forzamento di I2 e non basta /*index(s1
I1_serviz)*/. Bisogna usare lo stratagemma di inserire una funzione superflua che permette di
non forzare quellindice a causa della join che sembrerebbe pi restrittiva perch agganciata ad una
costante ('1') e cio: ANDLTRIM(s1.ser_statoserv)='1'
Inoltre si mettono in ordine prima i campi si I1 e poi quelli di s1 come stanno nel FROM.
Cercare pi volte a cambiare lordine sia della join e sia delluguaglianza e verificando LExplain Plan
ogni volta.
A livello pratico si passati da un tempo di oltre 1 ora a circa 30 secondi!
Ottimizzata:
SELECTs.ROWID,
s.ser_ute,
s.ser_puntopresa,
s.ser_codsersub,
l.let_matricola,
l.let_cod_fab
FROMservizs,letturl
WHEREs.ser_ute='BO'
ANDl.let_ute=s.ser_ute
ANDl.let_puntopresa=s.ser_puntopresaANDl.let_puntopresa='3198700212137'
ANDs.ser_stato_cont='5'
ANDs.ser_codsersubISNULL
ANDl.let_dat_lettur=
(SELECTMAX(l2.let_dat_lettur)
FROMletturl2
WHEREl2.let_ute=s.ser_ute
ANDl2.let_puntopresa=s.ser_puntopresa
ANDl2.let_tip_lettur!='M')
AND0<
(SELECT/*rule*//*index(s1I1_serviz)*/COUNT(0)
FROMletturl1,servizs1
WHERE
l1.let_ute=s.ser_ute
ANDl1.let_matricola=l.let_matricola
ANDl1.let_cod_fab=l.let_cod_fab
ANDl1.let_puntopresa!=s.ser_puntopresa
ANDl1.let_dat_lettur>l.let_dat_lettur
ANDs1.ser_puntopresa=l1.let_puntopresa
ANDs1.ser_ute=l1.let_ute
ANDs1.ser_datainifor>=s.ser_datainifor
ANDLTRIM(s1.ser_statoserv)='1'
24.3.
La cosa probabilmente nota ai pi, io l'ho scoperta solo ieri, vista l'insidia che nasconde ve la giro
(non si sa mai!):
in un blocco pl/sql se si effettua una
select field
into var
from table
where ....
se si verifica un'eccezione TOO_MANY_ROWS e, nella sua gestione,
non controllata la valorizzazione della variabile var, la stessa rimane valorizzata
con il valore di field relativo al record con rownum = 1 della select stessa.
es:
begin
select field
into var
from table
where ...;
exception
end;
--> qui var valorizzata con il primo valore estratto dalla select!
24.4.
Interi, Decimali
MAX (LENGTH (TRUNC (let_lettura)))
SELECT MAX(DECODE(LENGTH (LTRIM (LTRIM ((let_lettura) - TRUNC ((let_lettura)), '0123456789')
,',')),NULL,0,LENGTH (LTRIM (LTRIM ((let_lettura) - TRUNC ((let_lettura)), '0123456789') ,','))))
FROM lettur
24.5.
ESEMPIO DBLINK
25. TIPS
25.1.
Il commento /* .. */
Va bene se e solo se in mezzo non c ad esempio una forzatura di un indice come
ad esempio:
/*
PROMPT
PROMPT
PROMPT
select /*+ index(ana i1_ana)
use_nl(ana) */
1
from anacon
where a_ute = m_ute and
a_codser = m_codser and
a_matcon = m_matcon and
nvl(aco_sigcon,'') = nvl(m_sigcon,'') and
a_codfab = m_codfab and
a_anno_fab = m_anno_fab)
*/
25.2.
SELECT
UTE,
PUNTOPRESA,
count(*)
FROM
letturgroupbyLET_UTE,
LET_PUNTOPRESA,
havingcount(*)>1
25.3.
Stesso procedimento di prima.in questo caso per i dati sono salvati sul db locale
e quindi non c il rischio di modificare i dati sul DB Oracle.
altro file su 8i overview
25.4.
Se SQL lento
v$session.audsid=sys_context('userenv','sessionid');
mod: module name
mh: module hash
act: ah
len Length of SQL statement.
dep Recursive depth of the cursor.
uid Schema user id of parsing user.
oct Oracle command type.
lid Privilege user id.
ela Elapsed time. 8i: in 1/1000th of a second, 9i: 1/1'000'000th of a second
tim Timestamp. Pre-Oracle9i, the times recorded by Oracle only have a resolution of 1/100th of a
second (10mS). As of Oracle9i some times are available to microsecond accuracy (1/1,000,000th
of a second).
hv Hash id.
ad SQLTEXT address (see v$sqlarea and v$sqltext).
3.
4.
5.
6.
7.
introdurre HINT per il Query Optimizer onde evitare full scan ecc.
togliere inizializzazioni o calcoli dai loop
evitare dichiarazione di variabili non utilizzate
evitare passaggio di dati non necessari alle funzioni
se si devono utilizzare numeri interi, evitare Number e Integer, usare piuttosto
PLS_INTEGER che nativo
8. evitare le conversioni implicite: es con Number meglio sommare 15,0 che 15 (poich
essendo intero deve prima essre convertito in Number e poi sommato...)
9. evitare variabili definite con constraint, es. not null, poich richiedono variabili temporanee
di appoggio; meglio togliere il constraint e poi fare un test con raise di errore
10. se una condizione multipla prevede la OR, mettere per prima quella pi frequente: se risulta
verificata la seconda non viene neppure valutata
11. se una condizione multipla prevede la AND, mettere per seconda eventuali funzioni booleane,
ecc. in modo che siano eseguite solo le prima verificata
12. la Shared Pool Memory deve essere sufficientemente ampia da contenere i package usati
pi di frequente, altrimenti fa dentro e fuori di continuo
13. altra possibilit per il punto sopra usare i package PINNED per non fargli usare FIFO-LRU
14. si pu usare il nuovo tool Profiler per trovare le aree problematiche
15. Verificare anche con SPOT-Light della QUEST i problemi del server
poi ci sono esempi di BULK e FORALL copiare o studiare esempi pag. 28 e 29
25.5.
DECLARE
DATE1 TIMESTAMP := to_date('01/01/2007','dd/mm/yyyy');
DATE2 TIMESTAMP := sysdate;
DIFF_DATE varchar(50);
BEGIN
SELECT DATE2-DATE1 INTO DIFF_DATE FROM DUAL;
DBMS_OUTPUT.PUT_LINE('DATE1 : '
|| TO_CHAR(DATE1, 'DD-MM-YYYY HH24:MI:SS.FF'));
DBMS_OUTPUT.PUT_LINE('DATE2 : '
|| TO_CHAR(DATE2, 'DD-MM-YYYY HH24:MI:SS.FF'));
DBMS_OUTPUT.PUT_LINE('DIFF. DATE2-DATE1: '|| DIFF_DATE);
DBMS_OUTPUT.PUT_LINE('SETTIMANE : '
|| TRUNC(TO_NUMBER(SUBSTR(DIFF_DATE, 1, INSTR(DIFF_DATE, ' ')))/7));
DBMS_OUTPUT.PUT_LINE('GIORNI : '
|| TRUNC(TO_NUMBER(SUBSTR(DIFF_DATE, 1, INSTR(DIFF_DATE, ' ')
))));
DBMS_OUTPUT.PUT_LINE('ORE : '
|| TRUNC(TO_NUMBER(SUBSTR(DIFF_DATE, INSTR(DIFF_DATE, ' ') + 1,
2))));
DBMS_OUTPUT.PUT_LINE('MINUTI : '
|| TRUNC(TO_NUMBER(SUBSTR(DIFF_DATE, INSTR(DIFF_DATE, ' ') + 4,
2))));
DBMS_OUTPUT.PUT_LINE('SECONDI : '
|| TRUNC(TO_NUMBER(SUBSTR(DIFF_DATE, INSTR(DIFF_DATE, ' ') + 7,
2))));
END;
AND EXISTS (
SELECT ser_ute, ser_puntopresa
FROM serviz@isuintdblink si
WHERE s.ser_ute = si.ser_ute
AND s.ser_puntopresa = si.ser_puntopresa)
-- Count(*) : 9175
http://www.akadia.com/html/publications.html#Oracle%20Tips%20of%20the%20Week
Non e' necessario passare sempre dati su host variables ma e' possibile utilizzare le funzioni offerte
dall'RDBMS per le necessarie elaborazioni o conversioni dei dati.
E' necessario porre attenzione alle clausole not in quanto Oracle ritiene che una condizione in not sia
poco selettiva. E' spesso opportuno valutare selezioni alternative.
I valori posti a null richiedono un corretto trattamento sia per la semantica dello statement SQL che per la
sua ottimizzazione. Se ben definiti i valori a null consentono risparmi nella scrittura di codice ed efficienza
nell'esecuzione. Vi sono specifiche funzioni per il trattamento dei valori a null (nvl()).
Le operazioni di outer join sono relativamente complesse e trattate con modalita' necessariamente
differenti dai join comuni. E' in genere sconsigliato l'utilizzo di outer joins sia per motivi di portabilita' che di
efficienza.
E' spesso possibile utilizzare alcune delle potenti funzioni Oracle (decode, conversioni, ..) per ottenere
risposte altrimenti complesse.
Debbono essere attentamente valutate le selezioni annidate; in alcuni casi la forma di selezione annidata
e' maggiormente performante, in altri casi e' opportuno effettuare trasformazioni. E' importante notare che
tutte le selezioni possono essere trasformate in selezioni annidate (in genere meno efficienti).
In alcuni casi puo' essere utile sfruttare l'istruzione di union (per formare l'unione insiemistica dei risultati di
due differenti selezioni).
Gli indici composti (costruiti su piu' colonne) vengono usati solo se le colonne che li compongono sono
richiamate nello statement SQL in un certo modo: solo la prima, la prima + la seconda, la prima + la
seconda + la terza, ecc. Se e' richiamata solo la seconda colonna e non la prima, l'indice composto non
viene utilizzato. La corretta definizione di indici composti puo' portare ad una notevole efficienza nelle
ricerche.
Evitare operazioni che richiedano ingenti spazi temporanei per l'esecuzione (ordinamenti di tabelle molto
grandi, ..). Le clausole di DISTINCT e di GROUP BY sono analoghe (da punto di vista computazionale) alla
clausola di ORDER BY. Lo stesso tipo di problema puo' presentarsi alla creazione di indici.
Controllare la gestione dei lock per evitare blocchi ai dati su accessi in contemporanea.
Possono essere costruite condizioni di selezione molto complesse ed efficienti per gli statement di
DELETE, INSERT ed UPDATE utilizzando le selezioni annidate.
Evitare transazioni di lunga durata.
Gli statement SQL hanno un costo (tale costo e' evidente nelle operazioni molto frequenti e di veloce
esecuzione). Tale aspetto deve essere tenuto in conto. In generale e' opportuno limitare il numero di
statement SQL.
Per la cancellazione di tutti i record di una tabella e' opportuno l'utilizzo del comando TRUNCATE
(versione 7).
Per elementi di maggior dettaglio sui punti presentati e' necessario fare riferimento alla specifica manualistica.
Explain Plan
Il comando EXPLAIN PLAN (CTRL+E in TOAD) mostra l'esatto percorso compiuto dall'ottimizzatore ORACLE per
eseguire uno statement SQL: e' cosi' possibile verificare se vengono adeguatamente sfruttati gli indici presenti.
Il comando EXPLAIN PLAN (applicato a un determinato statement SQL) popola una tavola di servizio da cui e'
possibile estrarre tutte le informazioni sull'esecuzione dello statement.
http://213.92.21.88/meo/white/varie/sql_tune.htm