Friday, 25 January 2013

Sql tuning

Hi Guys,

In almost all the projects that i have worked for over the last few years one of the most common requirement in sql tuning .The database might be different but sql tuning is one of the most important things to know in Business Intellegence .It gives you the edge in any project that you are working .

Now this is a big topic and I am not DBA to know all the details but i am going to mention few points that everyone can look into and try to get their sql to perform better .I will also help you to understand the explain plan ( its quite diff to make use of it in few minutes).



Below TIP for finding query time is for Oracle 11g

One useful thing I found today .Usually we are using set timing on Or we are looking at elapsed time from sql developer.Which is not correct way of testing how much time a query takes to execute because oracle will store the result set in cache


USUAL way of looking at run time 




Consider we execute the same query 5 time then if at first run it takes 10 s then at 5th run it might take 0.5 s without us making any change to query .This is because of oracle cache.Use below statement to find the run time .Consider we run a statement 5 times then executions column will show 5.Its Best to look for time_taken when execution is 1

To identify your query just put a comment in the query UPPER(SQL_TEXT) like '%KAP%'


select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' , MODULE, SQL_TEXT elasped ,executions from v$sql
where UPPER(SQL_TEXT) like '%KAP%'
AND UPPER(MODULE) LIKE '%SQL%DEVE%'
  order by LAST_LOAD_TIME desc


Point to be noted in this time

1)      This time does not include time oracle takes to print result set to our screen
2)      Consider we run the same query 10 times then we need to divide the time taken by number of executions to get average time.

-------------------------------------------------------------------------------------------------------------------
Basic idea (irrespective of database)

1) Find the query that is causing the most trouble (delays)
a) Simple idea is to use select count(*) from ( select * from most trouble) .This will give you the time required for the query to run

2)Check the filters used . By reducing the amount of data we can speed up the query .Like if your query fetches last 4 years data check with business if some one really is using this 4 years data or can you make it to fetch only last 24 months .

3)Make sure table has indexes (Its very difficult to find project in which tables are not indexed properly but give it a shot ... )

4)Try to simplify query .Queries with nested subqueries,inline views perform poorly .

(most commonly found) ---here k is your inline view.
select k.dept,a.emp from emp a ,(select dept from xyz) k

5) Make use of WITH clause (Subquery factoring) this performs faster then your inline views.

WITH dept_cost as ( select dept from xyz)
select dept,a.emp from emp a,dept_cost

6)Most professional way of doing it is by Using explain plan.But since most developer do not have that level of db knowledge and would usaully will not like to go for it .I have discussed it at the last

7) Below are some points that i liked taken from the link below

Beginners Sql site


 Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as
SELECT name 
FROM employee 
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age) 
FROM employee_details) 
AND dept = 'Electronics'; 
Instead of:
SELECT name 
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details) 
AND age = (SELECT MAX(age) FROM employee_details) 
AND emp_dept = 'Electronics';


Make use of IN and EXISTS efficiently .
a) IN has slower performance

This is not Always true it depends on your situation.  Sometimes in may be faster sometime Exists may be faster. Understand the situation first. Below is taken from ASKtom. To read full article

ASKtom website link for article

Well, the two are processed very very differently.

Select * from T1 where x in ( select y from T2 )

is typically processed as:

select * 
  from t1, ( select distinct y from t2 ) t2
 where t1.x = t2.y;

The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then joined to 
the original table -- typically.


As opposed to 

select * from t1 where exists ( select null from t2 where y = x )

That is processed more like:


   for x in ( select * from t1 )
   loop
      if ( exists ( select null from t2 where y = x.x )
      then 
         OUTPUT THE RECORD
      end if
   end loop

It always results in a full scan of T1 whereas the first query can make use of an index 
on T1(x).


So, when is where exists appropriate and in appropriate?

Lets say the result of the subquery
    ( select y from T2 )

is "huge" and takes a long time.  But the table T1 is relatively small and executing ( 
select null from t2 where y = x.x ) is very very fast (nice index on t2(y)).  Then the 
exists will be faster as the time to full scan T1 and do the index probe into T2 could be 
less then the time to simply full scan T2 to build the subquery we need to distinct on.


Lets say the result of the subquery is small -- then IN is typicaly more appropriate.


If both the subquery and the outer table are huge -- either might work as well as the 
other -- depends on the indexes and other factors. 


IN Example

select ename from emp e
    where mgr in (select empno from emp where ename = 'KING');

Same as 

select e1.ename from emp e1,(select empno from emp where ename = 'KING') e2
    where e1.mgr = e2.empno;

The idea to use In is the result from inner query is less compared to outer query . In such cases In works well 

EXISTS

select ename from emp e
    where exists (select 0 from emp where e.mgr = empno and ename = 'KING');


My favorite is the below .As you will notice that we end up having distinct in our subqueries .Which slows the performance the most as first entire data is picked up and then grouped to find distinct .So best is to try to avoid having distinct especially in your inline views


 Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as
SELECT d.dept_id, d.dept 
FROM dept d 
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
Instead of:
SELECT DISTINCT d.dept_id, d.dept 
FROM dept d,employee e 
WHERE e.dept = e.dept;

For those who want to impr.ove their sql tuning skill further my idea is to start from Oracle basics how it works .I have noted few points in by article below



Adding Two more things to check 

I was facing issue that the seq.next_val was taking long time as the caching value was low. This was causing the inserts to take time. You can know this by lookin at v$sesion table and knowing on what is the session waiting for . It will be waiting long time on things like db_sequention_read then you can find out what is the object on which it is waiting . you can chek out below link 

http://cognossimplified.blogspot.com/2013/10/etl-tools-and-sessions-in-db.html

Using Wrong data type for index column like product_key = '40' . This causes oracle to skip using the index on product key make sure you are passing correct data type for indexed columns

With Clause for SQL tuning  

With clause is best to be used when you code is getting too long and you can easily divide it into parts. With clause speeds up the query by allowing oracle to store intermediate result in intermediate tables. The concept is similar to global temporary concept which was there before. But only difference is global temporary table would force oracle to create temporary tables. By using with clause oracle has the choice of creating temporary tables if it think its a good idea.

But we cannot always trust oracle. It will estimate the cost of not creating temp tables and it might think its good idea not to go for temp tables. In such cases you need to force oracle to go for temp tables to store the with clause result by using the hint /*+materialize*/ . I have obtained a query improvement of 75 seconds for huge volume by going for that hint.






Regarding Using Case statement

I had a query which was taking 130 seconds to execute. When I checked by building query block by block I observed case statement takes maximum time. Without case it hardly took 10 seconds. So here is what was happening

Select case( 1=1 and 2=2 and 3=3) a1,
          case( 1=3 and 5=4 and 6=6) b1
From
( select 1 , 2 , 3 from abc inner join with hhh on 1=8 )

So what I did was push the condition. Its easy for oracle to do row level calculation like suppose we have two columns 1 and 3 then its easier for oracle to compare ,  add, subtract and all that

Select a1,b1          
From
( select 1 , 2 , 3, ( 1=1 and 2=2 and 3=3) a1, case( 1=3 and 5=4 and 6=6) b1 from abc inner join with hhh on 1=8 )

How to tune by reading Explain pland and Statistics IO

This is the actual way of doing it.But it will take atleast a weeks reading to understand the basics and use it to help you solve your professional problems.Below are some of my notes for starting.

How to check the explain plan .

run the below statement 

explain plan for (select * from abc)

this will store the explain plan data in a plan table which can be accessed by using below statement

select * from table (dbms_xplan.display)

Go through below article it will give you some basic idea of explain plan.Understanding explain plan and using it to tune is a big task will take lot of patient ( days worth of work ).Not for the faint hearted .


Below are link for my articles on Oracle db basic and Reading Explain plans(For the experienced folks )




Below is link for Article on Temp space issue in DB which was causing performance issues for us. 


http://cognossimplified.blogspot.com/2014/01/lack-of-temp-space-causing-performance.html


Bitmap Indexes on Fact Table can improve performance a lot. Hints like star transformation in oracle has huge impact 

http://cognossimplified.blogspot.com/2013/07/sql-tuning-with-bitmap-indexes-and-star.html 

Sometime Cast conversion from varchar to integer has impact on performance ,Consider you fact stores result as varchar and you are summing on it. Oracle will convert it to int. Which will affect performance. So make sure you know the datatype of columns you are summing




Tuesday, 27 November 2012

Outer Joined better understanding


Hi Guys,

Below is something which sounds very simple.But understanding it will give you a better understanding of queries

Emp.emp_id = dept.emp_id(+)
dept.abc_id =state.abc_id(+)

the main driving force here is emp here .notice that it has outer join with dept .So in simple terms it means it will return all the values for emp even if
there are no matching values in dept.Notice there are no matching values in dept corresponding to emp_id so all are null then you try to join state based on
abc_id id to dept .Now since abc_id is null there wont be any location picked up .
So here the data is control based on emp. to get data you need to insert data into dept table with corresponding emp_id

So point to remember are when you are joining is outer join allows you to join nulls as if one side is null it cannot find anything matching on other sides
substitutes null. second once you outer join on one table and then you join the non driving table to other table .The driving table controls your data.In
this case driving table is EMP

Monday, 5 November 2012

Issue faced during Cognos Install

Hi Guys,

I reinstalled Cognos and I faced a couple of issue so below is their resolution.Hope you find them handy and you will save time.


Oracle Install 

If you are planning to use oracle as content store.I will tell you this will be the most difficult part of cognos install .80% of issue faced in your install will be related to Oracle.Atleast that has been my experience .But it will take your knowledge about Oracle to Next level .So dont Give up Easily.

Important Note .

I dont know how to uninstall Oracle Server if install goes wrong .Like u might set up wrong Character set .BEWARE.

Please create a System restore point in your Machine and Set the Memory size of your System restore to 3 GB so that it wont get over writen in a month by a New system restore point which gets created automatically by Windows everytime a new update to any software like flash or java is made by windows .or  even a simple windows update.


1) RIGHT CLICK ON MY COMPUTER
2) GO TO PROPERTIES
3)SYSTEM PROTECTION
4) CREATE SYSTEM RESTORE POINT.

if you are fun loving person like me and want to edit your window registries to get rid of oracle dont do this .there is fun in learning this tooo :-P.


Some points to remember .

1)Oracle is by default installed on E drive in Apps folder
2)Oracle does not have a default unistall option so if you messed it up its difficult to remove from your system without proper formating . or registry clean up.So have a system restore point handy
3)You need to install server type database and not desktop type database
4)There is a step called database identifiers where you have to specify the dataset as UTF8 .Remember that.If you miss this,you will have to uninstall Oracle(Painfull .....)
5)Below are the steps for some FOOLS :-P

If you have not created a system restore like me and dont have patience to unistall oracle using commands as there is no direct unistaller .Delete oracle folder and clean up your registry using below method .I would not recommend it .But sometime you might have to resort to it when time is short.
------------------------------------------------------------------------
Start Regedit.exe and navigate to the following branch:

HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services

6) You will need to free up temp space once you do this.Otherwise it wont allow you to install Oracle again.Better to create System restore


use disk clean up utility to free up space on your windows 7 .this space might have been used due to bad oracle install.go to start and click on disk clean up to free up space.go to environment variables and remove oracle path also when deleting oracle

7)The oracle ojdc14 file can be in diff folder also .Just search for it files get moved to diff folder depending on version of oracle .so no worries

Ojdbc14 is for Oracle 10g .If you are using Oracle 11g then Ojdbc5

8)Once Oracle is installed succesfully.You will need to create a user called cognos for content store

Below are commands


-------create user cognos identified by cognos

you need to provide all the permission to this user otherwise you will get errors

--------grant all privileges to cognos

9) Please understand what is a Listener and What is tnsnames file .Visit below link in case you get any errors due to Listener .You will be 100% able to solve it .with below link.Not by me

edstevensdba-Explanation on Listener and Tnsnames

10) Some errors that I faced

ORA-12514, TNS:listener does not currently know of service requested in connect descriptor

Preety self explainatory . Listener does not know of service .

Solution 
1)Go to command prompt.Type tnsping ABC (where ABC is your tnsalias.)

Example Below


ABC =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = ADMIN-PC)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = SHARED)
      (SERVICE_NAME =orcl)
    )
  )

Note -tnsping only tells you that the listener is listening on the host and port .It does not tell you anything about the service .It does not even tell you that the service exists .service in above example is orcl.so you need to do below command in command prompt.

lsnrctl status . 


when you do this check what is the service name and what is its status .Is it showing as ready??

unknown status means because you have made entry in listener.ora file its showing that service.it does not have idea if that database instance is running or not.once you make a request then listener will try to find that out. so use only those services which have their status as ready in your cognos connection string for database you will definately make a connection.

Below is how it looks 


Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.2.7)(PORT=1521)))
Services Summary...
Service "ORCL" has 1 instance(s).
  Instance "ORCL", status UNKNOWN, has 1 handler(s) for this service...


So this was the issue that i had .The listener did not know if the instance was there or not and whether the instance was ready.

I followed below steps to resolve the issue
Loging to system as sysdba and do

-----select * from v$instance

.this will give you the instace name of oracle running.

Please put the same host name , service name shown in this command in both listener.ora and tnsnames.ora . In my files it was differnet and that cost me 2 days to search for the error.If ADMIN-PC IS THERE be sure to put ADMIN-PC as host name in listener and tnsnames.ora file.


11) Try Creating a ODBC connection to content store it will help you check if there is any issue from oracle side or from cognos side.If you able to connect using ODBC the issue of connectivity is from cognos side.

Below are my tnsnames and listner files .Notice the difference in service name .Whatever name you give in listener that service will be shown as unknow because of reason i have explained above.

Below is tnsnames.ora file


ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = ADMIN-PC)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME =orcl.168.2.7)
    )
  )

-------------------------------------------------------------------------------


Below is listener.ora file



SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = orcl)
      (ORACLE_HOME = E:\app1\ADMIN\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app1\ADMIN\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )






12)Below command might be helpful


netstat -ao

It will give you which pid is using which port .

so first you need to go to task manager and get teh pid of a service and then you need to go to netstat -ao and the port number that service is using to check if oracle listener is actually using 1521 as a port.

ORA-12520 -TNS:listener could not find available handler for requested type of server

Below is my listener configuration.Notice that when i do lsnrctl status i get status for instance orcl.168.2.7 as unknown ,because its manually hardcoded into my listener file


SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = orcl.168.2.7)
      (ORACLE_HOME = E:\app1\ADMIN\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app1\ADMIN\product

\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )





------------------------------------------------------------------------------------------------------------

Java Run time Environment (JRE)


You need java 1.5 or java 1.6 for cognos install .If you are having a new laptop these things might not be there . so please install them first .

Please download JRE -- Java run time environment.You  do not need JDK.that is java development kit.

Right Click on My computer .Go to Properties .then click on Advanced . Set environment Variable path to.

C:\Program Files\Java\jre6\bin

------------------------------------------------------------------------------------------------------------

Installing Apache Web Server 


Do not get confused with apache and apache tomcat . both are different .We need Apache and not apache tomcat . 

please download apache zip file with .msi extension for windows .most apache that are availabel will be for unix . so cant run it on windows . windows will have a single install file available to install apache.

Go to config folder , in http.conf file .Copy paste the below


ScriptAlias /cognos10/cgi-bin "C:\Program Files\Cognos_Server\ibm\cognos\c10\cgi-bin"
<Directory "C:\Program Files\Cognos_Server\ibm\cognos\c10\cgi-bin">
    Options FollowSymLinks
    AllowOverride FileInfo
    Order Allow,Deny
    Allow from All
</Directory>
Alias /cognos10 "C:\Program Files\Cognos_Server\ibm\cognos\c10\webcontent"
<Directory "C:\Program Files\Cognos_Server\ibm\cognos\c10\webcontent">
    Options FollowSymLinks
    AllowOverride FileInfo
    Order Allow,Deny
    Allow from All
</Directory>

------------------------------------------------------------------------------------------------------------

Firewall setting .

Please have a look ,Just in case it was not automatically set up during Cognos server install.