Thursday, 19 January 2012

Oracle Query Tuning Tips

Query Tuning
-------------------

CO-Relations (vs) Joins (vs) Sets
++++++++++++++++++++++++++++++++++

Co-Relations/Joins/Sets are actually using for joint or disjoint collections.

1. Co-Relations sub queries are high cost expensive queries when compare to Joins.
2. However, Co-Relations are using less memory when compared to Joins.
3. Joins are always using some builting algorithms like (Hash join (Small set of rows), Merge Join (Huge set of row + Sort)) which makes the things very faster.

Find the below examples

-> CREATE TABLE TEST(T INT);
-> CREATE TABLE TEST1(T1 INT);
-> INSERT INTO TEST VALUES(GENERATE_SERIES(1,1000));
-> INSERT INTO TEST VALUES(GENERATE_SERIES(500,1499));


CO-Relation
-----------
postgres=# EXPLAIN SELECT * FROM TEST AS OUT WHERE OUT.T IN (SELECT INN.T1 FROM TEST1 AS INN WHERE INN.T1=OUT.T);
QUERY PLAN
------------------------------------------------------------------
Seq Scan on test "out" (cost=0.00..48043.00 rows=1200 width=4)
Filter: (SubPlan 1)
SubPlan 1
-> Seq Scan on test1 inn (cost=0.00..40.00 rows=1 width=4)
Filter: (t1 = "out".t)
(5 rows)


If you want to tune this Co-Relation then use "EXISTS" instead of "IN" Operation.(Note:- Replacing EXISTS/NOT EXISTS with IN/NOT IN is depends on the subquery logic).

postgres=# EXPLAIN SELECT * FROM TEST AS OUT WHERE EXISTS (SELECT INN.T1 FROM TEST1 AS INN WHERE INN.T1=OUT.T);
QUERY PLAN
-------------------------------------------------------------------------
Hash Semi Join (cost=26.50..54.25 rows=1000 width=4)
Hash Cond: ("out".t = inn.t1)
-> Seq Scan on test "out" (cost=0.00..14.00 rows=1000 width=4)
-> Hash (cost=14.00..14.00 rows=1000 width=4)
-> Seq Scan on test1 inn (cost=0.00..14.00 rows=1000 width=4)
(5 rows)

Observer the cost of both queries.

Joins
-----
postgres=# EXPLAIN SELECT * FROM TEST AS OUT INNER JOIN TEST1 AS INN ON INN.T1=OUT.T;
QUERY PLAN
-------------------------------------------------------------------------
Hash Join (cost=26.50..54.25 rows=1000 width=8)
Hash Cond: ("out".t = inn.t1)
-> Seq Scan on test "out" (cost=0.00..14.00 rows=1000 width=4)
-> Hash (cost=14.00..14.00 rows=1000 width=4)
-> Seq Scan on test1 inn (cost=0.00..14.00 rows=1000 width=4)
(5 rows)


Set Operators(Intersect)
------------------------
postgres=# EXPLAIN SELECT * FROM TEST INTERSECT SELECT * FROM TEST1;
QUERY PLAN
---------------------------------------------------------------------------------
HashSetOp Intersect (cost=0.00..53.00 rows=1000 width=4)
-> Append (cost=0.00..48.00 rows=2000 width=4)
-> Subquery Scan on "*SELECT* 1" (cost=0.00..24.00 rows=1000 width=4)
-> Seq Scan on test (cost=0.00..14.00 rows=1000 width=4)
-> Subquery Scan on "*SELECT* 2" (cost=0.00..24.00 rows=1000 width=4)
-> Seq Scan on test1 (cost=0.00..14.00 rows=1000 width=4)


In the above three plans Set Operator's plan showing optimal result. We mayn't the same for all the cases. The execution plan always depends on the number of conditions what we are implying and the no.of rows and the row length.

In some of the cases Join Operations gives us very less cost when compares to Intersect operation.Because, Set operators always uses some internal SORT algorithms.


Inserted more records.

postgres=# SELECT COUNT(*) FROM TEST;
count
-------
32000
(1 row)

postgres=# SELECT COUNT(*) FROM TEST1;
count
-------
32000
(1 row)


Co-Relations
------------
postgres=# EXPLAIN SELECT * FROM TEST AS OUT WHERE OUT.T IN (SELECT INN.T1 FROM TEST1 AS INN WHERE INN.T1=OUT.T);
QUERY PLAN
--------------------------------------------------------------------
Seq Scan on test "out" (cost=0.00..8417806.00 rows=16000 width=4)
Filter: (SubPlan 1)
SubPlan 1
-> Seq Scan on test1 inn (cost=0.00..526.00 rows=32 width=4)
Filter: (t1 = "out".t)
(5 rows)

postgres=# EXPLAIN SELECT * FROM TEST AS OUT WHERE EXISTS (SELECT INN.T1 FROM TEST1 AS INN WHERE INN.T1=OUT.T);
QUERY PLAN
---------------------------------------------------------------------------
Hash Semi Join (cost=846.00..1772.00 rows=32000 width=4)
Hash Cond: ("out".t = inn.t1)
-> Seq Scan on test "out" (cost=0.00..446.00 rows=32000 width=4)
-> Hash (cost=446.00..446.00 rows=32000 width=4)
-> Seq Scan on test1 inn (cost=0.00..446.00 rows=32000 width=4)
(5 rows)


Joins
------
postgres=# EXPLAIN SELECT * FROM TEST AS OUT INNER JOIN TEST1 AS INN ON INN.T1=OUT.T;
QUERY PLAN
---------------------------------------------------------------------------
Hash Join (cost=846.00..12892.00 rows=1024000 width=8)
Hash Cond: ("out".t = inn.t1)
-> Seq Scan on test "out" (cost=0.00..446.00 rows=32000 width=4)
-> Hash (cost=446.00..446.00 rows=32000 width=4)
-> Seq Scan on test1 inn (cost=0.00..446.00 rows=32000 width=4)
(5 rows)

Set Operators
-------------
postgres=# EXPLAIN SELECT * FROM TEST INTERSECT SELECT * FROM TEST1;
QUERY PLAN
-----------------------------------------------------------------------------------
HashSetOp Intersect (cost=0.00..1692.00 rows=1000 width=4)
-> Append (cost=0.00..1532.00 rows=64000 width=4)
-> Subquery Scan on "*SELECT* 1" (cost=0.00..766.00 rows=32000 width=4)
-> Seq Scan on test (cost=0.00..446.00 rows=32000 width=4)
-> Subquery Scan on "*SELECT* 2" (cost=0.00..766.00 rows=32000 width=4)
-> Seq Scan on test1 (cost=0.00..446.00 rows=32000 width=4)
(6 rows)


We need to check all the cases for fine tuning the query. Sometimes, we might get a better plan with JOINS when compares to INTERSECT.

We may get the co-related queries with DELETE/UPDATE Statements also. So, please re-write them with USING/FROM always. If possible we can go with INTERSECT also.

UPDATE
------

Actual
------

UPDATE Test AS OUT
SET T = ( SELECT T1 FROM Test1 INN WHERE INN.T=OUT.T);

Recommended
-----------

UPDATE Test AS OUT
SET T = T1
FROM Test1 AS INN Where INN.T=OUT.T;


DELETE
------
Actual
------
DELETE From Test As OUT Where NOT Exists (Select INN.T1 FROM TEST1 Where OUT.T!=INN.T1);

Recommended
-----------
DELETE From Test As Out USING Test1 as Inn where Out.T!=Inn.T1


Equating Single Values (vs) In Single Value
-------------------------------------------

There could be slight cheper cost when compares to "=" and "IN". Find the below test case with "=" and using "IN".

postgres=# BEGIN WORK;
postgres=# DELETE FROM TEST WHERE T =1;
DELETE 64
Time: 65.426 ms
postgres=# ROLLBACK;

postgres=# BEGIN WORK;
postgres=# DELETE FROM TEST WHERE T IN(1);
DELETE 64
Time: 34.683 ms
postgres=# ROLLBACK;


UNION (vs) FULL OUTER JOINS
---------------------------

Actual Query with Unions.
-------------------------
SELECT * FROM test WHERE true AND t IN (2,3,4,5) AND mp > 0
UNION
SELECT * FROM test WHERE true AND t IN (2,3,4,5) AND sp > 0
UNION
SELECT * FROM TEST WHERE TRUE AND T IN (2,3,4,5) AND TP>0;

Most of the Set operators are using Sort operations. If the sort operation is taking much more time, then following one is recommended with the indexes.


And with FullOuter Joins.
-------------------------
SELECT coalesce(a.*,b.*,c.*) FROM
(SELECT * FROM test WHERE true AND t IN (2,3,4,5)AND mp > 0) AS A
FULL OUTER JOIN
(SELECT * FROM test WHERE true AND t IN (2,3,4,5)AND sp> 0) AS B
ON A.t=B.t and a.mp=b.mp and a.sp=b.sp and a.tp=b.tp
FULL OUTER JOIN
(SELECT * FROM test WHERE true AND t IN (2,3,4,5)AND tp> 0) AS C
ON B.t=C.t and B.mp=C.mp and C.sp=b.sp and C.tp=b.tp;

DISTINCT (vs) Group By
----------------------
DISTINCT operation also using "SORT" when it's in action. So, please use Group by instead of DISTINCT.

Actual
------
SELECT DISTINCT T FROM TEST;

Recommended
-----------
SELECT T FROM TEST GROUP BY T;

Teradata tutorial link

Saturday, 7 January 2012

::CSV files in Oracle ::

How to make a csv/flat file in oracle through UTL_FILE
+++++++++++++++++++++++++++++++++++++++++++++++++++++++

CSV(comma separated values) are mostly useful in data transformation. I believe these files are mostly useful in DWH.

We can do the same through sqlplus features.

SQL> set heading off
SQL> set feedback off
SQL> spool /home/oracle/test/csv.txt
SQL> select empno||','||ename||','||job||','||mgr||','||hiredate||','||sal||','||comm||','||deptno from emp;

7369,SMITH,CLERK,7902,17-DEC-80,800,,20
7499,ALLEN,SALESMAN,7698,20-FEB-81,1600,300,30
7521,WARD,SALESMAN,7698,22-FEB-81,1250,500,30
7566,JONES,MANAGER,7839,02-APR-81,2975,,20
7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
7698,BLAKE,MANAGER,7839,01-MAY-81,2850,,30
7782,CLARK,MANAGER,7839,09-JUN-81,2450,,10
7788,SCOTT,ANALYST,7566,19-APR-87,3000,,20
7839,KING,PRESIDENT,,17-NOV-81,5000,,10
7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
7876,ADAMS,CLERK,7788,23-MAY-87,1100,,20
7900,JAMES,CLERK,7698,03-DEC-81,950,,30
7902,FORD,ANALYST,7566,03-DEC-81,3000,,20

7934,MILLER,CLERK,7782,23-JAN-82,1300,,10

SQL> spool off;

SQL> host more /home/oracle/test/csv.txt
SQL> select empno||','||ename||','||job||','||mgr||','||hiredate||','||sal||','||comm||','||deptno from emp;

7369,SMITH,CLERK,7902,17-DEC-80,800,,20
7499,ALLEN,SALESMAN,7698,20-FEB-81,1600,300,30
7521,WARD,SALESMAN,7698,22-FEB-81,1250,500,30
7566,JONES,MANAGER,7839,02-APR-81,2975,,20
7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
7698,BLAKE,MANAGER,7839,01-MAY-81,2850,,30
7782,CLARK,MANAGER,7839,09-JUN-81,2450,,10
7788,SCOTT,ANALYST,7566,19-APR-87,3000,,20
7839,KING,PRESIDENT,,17-NOV-81,5000,,10
7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
7876,ADAMS,CLERK,7788,23-MAY-87,1100,,20
7900,JAMES,CLERK,7698,03-DEC-81,950,,30
7902,FORD,ANALYST,7566,03-DEC-81,3000,,20

7934,MILLER,CLERK,7782,23-JAN-82,1300,,10


Here you can find the other way with UTL_FILE. This concept is similar to FILES in C language.

Step 1:
--------
Need to create a directory at os level

Ex:-
-----
/home/oracle/test

Step 2:
---------
Need to connect to the database as a sysdba grant below privileges to the required user.

CONNECT / AS SYSDBA

GRANT EXECUTE ON UTL_FILE TO scott;

CREATE OR REPLACE DIRECTORY test AS '/home/oracle/test'; in windows('c:\test\');

GRANT read, write ON DIRECTORY test TO scott;


Step 3:
---------
CONNECT scott/tiger

CREATE OR REPLACE Procedure make_csv_emp(csv_symbol char)
IS

fp UTL_FILE.FILE_TYPE;
BEGIN
fp:=UTL_FILE.FOPEN('TEST','emp_csv.txt','w');
FOR REC IN (SELECT * FROM EMP)
LOOP
UTL_FILE.PUTF(fp,REC.EMPNO||csv_symbol||REC.ENAME||csv_symbol||REC.JOB||csv_symbol||REC.MGR||csv_symbol||REC.HIREDATE||csv_symbol||REC.SAL||csv_symbol||REC.COMM||csv_symbol||REC.DEPTNO||'\n');
END LOOP;
UTL_FILE.FCLOSE(fp);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000,'ORA-ERROR::'||SQLCODE||'::'||SQLERRM);
END;

Step 4:
--------

Just execute the function and open the file.

SQL> exec make_csv_emp(',');

PL/SQL procedure successfully completed.

[oracle@localhost test]$ more emp_csv.txt
7369,SMITH,CLERK,7902,17-DEC-80,800,,20
7499,ALLEN,SALESMAN,7698,20-FEB-81,1600,300,30
7521,WARD,SALESMAN,7698,22-FEB-81,1250,500,30
7566,JONES,MANAGER,7839,02-APR-81,2975,,20
7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
7698,BLAKE,MANAGER,7839,01-MAY-81,2850,,30
7782,CLARK,MANAGER,7839,09-JUN-81,2450,,10
7788,SCOTT,ANALYST,7566,19-APR-87,3000,,20
7839,KING,PRESIDENT,,17-NOV-81,5000,,10
7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
7876,ADAMS,CLERK,7788,23-MAY-87,1100,,20
7900,JAMES,CLERK,7698,03-DEC-81,950,,30
7902,FORD,ANALYST,7566,03-DEC-81,3000,,20
7934,MILLER,CLERK,7782,23-JAN-82,1300,,10

ORACLE ARCHITECTURE