Showing posts with label indexing. Show all posts
Showing posts with label indexing. Show all posts

Sunday, April 3, 2016

Does index compression affect performance in oracle ?

  • https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8806017524595
  • www.aaoug.org/pres/Index%20Compression.ppt
  • https://richardfoote.wordpress.com/2008/02/17/index-compression-part-i-low/
  • https://richardfoote.files.wordpress.com/2008/02/index-compression-part-i.pdf

Wednesday, April 8, 2015

Monday, May 26, 2014

Is my index used ?

This oracle function will help you quickly check if an index is used or not, you have to enable his monitoring before

CREATE OR REPLACE FUNCTION is_index_used (owner         VARCHAR,
                                               table_name    VARCHAR,
                                               index_name    VARCHAR)
   RETURN VARCHAR
IS
   is_used   VARCHAR (3);
   cnt       NUMBER;
BEGIN
   is_used := 'NO';

   SELECT COUNT (*) CNT
     INTO cnt
     FROM SYS."_CURRENT_EDITION_OBJ" io,
          SYS."_CURRENT_EDITION_OBJ" T,
          sys.ind$ i,
          sys.USER$ iu,
          sys.USER$ tu,
          sys.object_usage ou
    WHERE     io.owner# = iu.USER#
          AND i.obj# = io.obj#
          AND io.obj# = ou.obj#(+)
          AND T.obj# = i.bo#
          AND T.owner# = Tu.USER#
          AND i.type# NOT IN (4, 8, 9)
          AND BITAND (io.flags, 128) <> 128
          AND iu.name = owner
          AND io.name = index_name
          AND T.name = table_name
          AND DECODE (BITAND (i.flags, 65536), 0, 'NO', 'YES') = 'YES'
          AND DECODE (BITAND (ou.flags, 1),  0, 'NO',  NULL, NULL,  'YES') =
                 'YES';

   IF cnt > 0
   THEN
      is_used := 'YES';
   ELSE
      is_used := 'NO';
   END IF;

   RETURN is_used;
EXCEPTION
   WHEN NO_DATA_FOUND
   THEN
      RETURN is_used;
   WHEN OTHERS
   THEN
      -- Consider logging the error and then re-raise
      RAISE;
END;
/

I recommend to wait minimum one week after enabling monitoring before you check it with a simple call like this ...

select INDEX_NAME,is_index_used(OWNER,TABLE_NAME,INDEX_NAME)  from dba_indexes where owner = 'FOMI' and table_name = 'ACCOUNTS'

Thursday, August 16, 2012

You should estimate the selectivity of an index before you create it

The ratio of the number of distinct values to the total number of rows is the selectivity of the columns. This method is useful to estimate the selectivity of an index before creating it.

select count (distinct job) "Distinct Values" from emp;

Distinct Values
---------------
              5
select count(*) "Total Number Rows" from emp;

Total Number Rows
-----------------
               14

Selectivity = Distinct Values / Total Number Rows
            = 5 / 14
            = 0.35 

To automatically measure index selectivity you can determine the selectivity of an index by dividing the number of distinct indexed values by the number of rows in the table.

create index idx_emp_job on emp(job);
analyze table emp compute statistics;


select distinct_keys from user_indexes
where table_name = 'EMP'

   and index_name = 'IDX_EMP_JOB';

DISTINCT_KEYS
-------------
            5
select num_rows from user_tables
where table_name = 'EMP';

NUM_ROWS
---------
       14

Selectivity = DISTINCT_KEYS / NUM_ROWS = 0.35 

To investigate the selectivity of each column individually it is also possible to query USER_TAB_COLUMNS

select column_name, num_distinct
from user_tab_columns
where table_name = 'EMP';
 
COLUMN_NAME                     NUM_DISTINCT
------------------------------ ------------
EMPNO                                     14
ENAME                                     14
JOB                                        5
MGR                                        2
HIREDATE                                  13
SAL                                       12
COMM                                       4
DEPTNO                                     3 

Consider creating a composite index on columns that are frequently used together in WHERE clause conditions combined with AND operators, especially if their combined selectivity is better than the selectivity of either column individually. Consider indexing columns that are used frequently to join tables in SQL statements. 

What is the selectivity of an index

The ratio of the number of distinct values in the indexed column / columns to the number of records in the table represents the selectivity of an index. The ideal selectivity is 1. Such a selectivity can be reached only by unique indexes on NOT NULL columns.

B*TREE Indexes improve the performance of queries that select a small percentage of rows from a table. As a general guideline, we should create indexes on tables that are often queried for less than 15% of the table's rows. This value may be higher in situations where all data can be retrieved from an index, or where the indexed columns can be used for joining to other tables. 

Oracle implicitly creates indexes on the columns of all unique and primary keys that you define with integrity constraints. These indexes are the most selective and the most effective in optimizing performance. The selectivity of an index is the percentage of rows in a table having the same value for the indexed column. An index's selectivity is good if few rows have the same value.

A table having 100'000 records and one of its indexed column has 90000 distinct values, then the selectivity of this index is 90'000 / 10'0000 = 0.9.

lf an index on a table of 100'000 records had only 500 distinct values, then the index's selectivity is 500 / 100'000 = 0.005 and in this case a query which uses the limitation of such an index will retum 100'000 / 500 = 200 records for each distinct value. It is evident that a full table scan is more efficient as using such an index where much more I/O is needed to scan repeatedly the index and the table. 

Tuesday, August 14, 2012

Where to obtain informations about indexes

  • DBA_INDEXES: Provides information on the indexes
  • DBA_IND_COLUMNS: Provides information on the columns indexed
  • DBA_IND_EXPRESSIONS: Provides information on function based indexes
  • V$OBJECT_USAGE: Provides information on the usage of an index

When Should Indexes Be Dropped ?

  • An index that is no longer needed by applications can be removed
  • An index may be dropped prior to performing bulk loads. Dropping an index prior to large data loads and re-creating them after the load
  • Indexes that are used only periodically do not need to be maintained unnecessarily, especially if they are based on volatile tables
  • An index may be marked INVALID when there is an instance failure during certain types of operations such as loading. In this case, the index needs to be dropped and re-created
  • The index is corrupt

When to rebuild an index

  • The existing index needs to be moved to a different tablespace. This may be necessary if the index is in the same tablespace as the table or if objects need to be redistributed across disks
  • An index contains many deleted entries
  • An existing normal index needs to be converted into a reverse key index. This may be the case when migrating applications from an earlier release of the Oracle server
  • The table of the index has been moved to another tablespace using the ALTER TABLE ... MOVE TABLESPACE command

Guidelines When Creating Indexes

  • Indexes speed up query performance and slow down DML operations. Always minimize the number of indexes needed on volatile tables
  • Place indexes in a separate tablespace, not in a tablespace that has rollback segments, temporary segments, and tables
  • There could be significant performance gain for large indexes by avoiding redo generation. Consider using the NOLOGGING clause for creating large indexes
  • Because index entries are smaller compared to the rows they index, index blocks tend to have more entries per block. For this reason, INITRANS should generally be higher on indexes than on the corresponding tables

When to create Bitmap Indexes

  • When a table has millions of rows and the key columns have low cardinality—that is, there are very few distinct values for the column. For example, bitmap indexes may be preferable to B-tree indexes for the gender and marital status columns of a table containing passport records
  • When queries often use a combination of multiple WHERE conditions involving the OR operator
  • When there is read-only or low update activity on the key columns

Effect of DML Operations on an Index

The Oracle server maintains all the indexes when DML operations are carried out on the table. Here is an explanation of the effect of a DML command on an index:
  • Insert operations result in the insertion of an index entry in the appropriate block
  • Deleting a row results only in a logical deletion of the index entry. The space used by the deleted row is not available for new entries until all the entries in the block are deleted
  • Updates to the key columns result in a logical delete and an insert to the index. The PCTFREE setting has no effect on the index except at the time of creation. A new entry may be added to an index block even if it has less space than that specified by PCTFREE

Table access by index rowid : what does it means ?

Searching the index is a fast and an efficient operation for Oracle and when Oracle finds the desired value it is looking for, it can also find out the rowid of the record in the corresponding table. Oracle can then use this rowid to fetch further information if requested in query.

All indexes store the rowid of the row indexed as part of the index. That is why an index can speed up access to the table, since typically the index is much smaller than the table, and is stored sorted by the value of the indexed colum

The "TABLE ACCESS BY ROWID" step does not mean that an index is used. It means that data is read from the table using the ROWID which was (in generally) previously read from an index.


Monday, August 13, 2012

Where to get index statistics

  • DBA_INDEXES
          Statistics columns populated by:

           – DBMS_STATS package (preferred)
           – ANALYZE command
          
           BLEVEL: Height of index between root block and leaf pages (0 means there is only a root block)
           LEAF_BLOCKS: Number of leaf blocks in index
           DISTINCT_KEYS: Number of distinct index values
           AVG_LEAF_BLOCKS_PER_KEY: Average number of leaf blocks required to store an
           indexed value.
           AVG_DATA_BLOCKS_PER_KEY: Average number of table blocks that contain rows
           referenced  by indexed key value
           NUM_ROWS: Number of leaf row entries
           CLUSTERING_FACTOR: Indicates how well ordered the rows in the table are in relation to
           the index
  • INDEX_STATS
          Populated by ANALYZE ... VALIDATE STRUCTURE command
          Only stores details of last index analyzed
          HEIGHT: Height of index, beginning at 1 for root only index
          BLOCKS: Number of blocks allocated to the index, not necessarily used
          LF_ROWS: Number of leaf row entries, including deleted row entries
          LF_BLKS: Number of leaf blocks, including empty leaf blocks
          LF_ROWS_LEN: Total size of all leaf row entries, including overhead and deleted entries
          LF_BLK_LEN: Total usable space in all leaf blocks
          BR_ROWS: Number of branch row entries
          BR_BLKS: Number of branch blocks
          BR_ROWS_LEN: Total size of all branch row entries, including overhead
          BR_BLK_LEN: Total usable space in all branch blocks
          DEL_LF_ROWS: Number of deleted leaf row entries not yet cleaned out
          DEL_LF_ROWS_LEN: Total size of all deleted leaf row entries not yet cleaned out
          DISTINCT_KEYS: Number of distinct index entries, including deleted entries
          MOST_REPEATED_KEY: The number of key entries for the most repeated index value
          BTREE_SPACE: Total size of the entire index, including deleted entries
          USED_SPACE: Total space currently used (not free) within the index, including deleted entries
          PCT_USED: Percentage of space currently used (not free) within the index, including deleted entries
          ROWS_PER_KEY: Average number of leaf row entries per distinct key value
          BLKS_GETS_PER_ACCESS: Average number of block reads required to access specific
          index   entry (the fewer rows_per_key and the lower the CF, the lower this value). EG:
          For a unique index with a HEIGHT of 3, this value would be 4 (3 for the index block reads and
          one  for the table block read).

  •  INDEX_HISTOGRAMS
  •  V$SEGMENT_STATISTICS

Why oracle does not use my index ?

  • An index is unlikely to be used if the clustering factor is close to the number of rows unless the selectivity is very strong
  • The clustering of an index will not change if you rebuild the index
  • The clustering factor of an index will change if you rebuild the table so that the data is physicaly ordered by the index key
  • You cannot have a low clustering factor for two independent indexes of the same table

Friday, August 10, 2012

Methods of index lookup

  • Index unique scan
Method for looking up a single key value via a unique index. Always returns a single value You must supply AT LEAST the leading column of the index to access data via the index, However this may return > 1 row as the uniqueness will not be guaranteed.
  • Index range scan
Method for accessing multiple column values You must supply AT LEAST the leading column of the index to access data via the index Can be used for range operations (e.g. > < <> >= <= between) 
  • Index Full Scan
In certain circumstances it is possible for the whole index to be scanned as opposed to a range scan (i.e. where no constraining predicates are provided for a table). Full index scans are  only available in the CBO as otherwise we are unable to determine whether a full scan would be a good idea or not. We choose an index Full Scan when we have statistics that indicate that it is going to be more efficient than a Full table scan and a sort.
For example we may do a Full index scan when we do an unbounded scan of an index and want the data to be ordered in the index order. The optimizer may decide that selecting all the information from the index and not sorting is more efficient than doing a FTS or a Fast Full Index Scan and then sorting.
An Index full scan will perform single block i/o's and so it may prove to be inefficient. 
  • Index Fast Full Scan
Scans all the block in the index Rows are not returned in sorted order Introduced in 7.3 and requires V733_PLANS_ENABLED=TRUE and CBO may be hinted using INDEX_FFS hint uses multiblock i/o can be executed in parallel can be used to access second column of concatenated indexes. This is because we are selecting all of the index.
Note that INDEX FAST FULL SCAN is the mechinism behind fast index create and recreate.
  • Rowid
This is the quickest access method available Oracle simply retrieves the block specified and extracts the rows it is interested in. Most frequently seen in explain plans as Table access by Rowid 
  • Joins
A Join is a predicate that attempts to combine 2 row sources We only ever join 2 row sources together Join steps are always performed serially even though underlying row sources may have been accessed in parallel. Join order - order in which joins are performed
The join order makes a significant difference to the way in which the query is executed. By accessing particular row sources first, certain predicates may be satisfied that are not satisfied by with other join orders. This may prevent certain access paths from being taken.




How to avoid sort using index

This one is not so well known, largely because it is so poorly documented (and in many cases, unpredicatably implemented by the Optimizer as well). Oracle performs a sort for many reasons: ORDER BY, GROUP BY, DISTINCT, Set operations (eg. UNION), Sort-Merge Joins, uncorrelated IN-subqueries, Analytic Functions). If a sort operation requires rows in the same order as the index, then Oracle may read the table rows via the index. A sort operation is not necessary since the rows are returned in sorted order.
Despite all of the instances listed above where a sort is performed, I have only seen three cases where a sort is actually avoided.
  1. GROUP BY
      1  select src_sys, sum(actl_expns_amt), count(*)
      2  from ef_actl_expns
      3  where src_sys = 'CDW'
      4  and actl_expns_amt > 0
      5* group by src_sys
    
    -------------------------------------------------------------
    | Id  | Operation                           | Name          |
    -------------------------------------------------------------
    |   0 | SELECT STATEMENT                    |               |
    |   1 |  SORT GROUP BY NOSORT               |               |
    |*  2 |   TABLE ACCESS BY GLOBAL INDEX ROWID| EF_ACTL_EXPNS |
    |*  3 |    INDEX RANGE SCAN                 | EF_AEXP_PK    |
    -------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       2 - filter("ACTL_EXPNS_AMT">0)
       3 - access("SRC_SYS"='CDW')
    Note the NOSORT qualifier in Step 1.

  2. ORDER BY
      1  select *
      2  from ef_actl_expns
      3  where src_sys = 'CDW'
      4  and actl_expns_amt > 0
      5* order by src_sys
    
    ------------------------------------------------------------
    | Id  | Operation                          | Name          |
    ------------------------------------------------------------
    |   0 | SELECT STATEMENT                   |               |
    |*  1 |  TABLE ACCESS BY GLOBAL INDEX ROWID| EF_ACTL_EXPNS |
    |*  2 |   INDEX RANGE SCAN                 | EF_AEXP_PK    |
    ------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       1 - filter("ACTL_EXPNS_AMT">0)
       2 - access("SRC_SYS"='CDW')
    
    Note that there is no SORT operation, despite the ORDER BY clause. Compare this to the following:
      1  select *
      2  from ef_actl_expns
      3  where src_sys = 'CDW'
      4  and actl_expns_amt > 0
      5* order by actl_expns_amt
    
    -------------------------------------------------------------
    | Id  | Operation                           | Name          |
    -------------------------------------------------------------
    |   0 | SELECT STATEMENT                    |               |
    |   1 |  SORT ORDER BY                      |               |
    |*  2 |   TABLE ACCESS BY GLOBAL INDEX ROWID| EF_ACTL_EXPNS |
    |*  3 |    INDEX RANGE SCAN                 | EF_AEXP_PK    |
    -------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       2 - filter("ACTL_EXPNS_AMT">0)
       3 - access("SRC_SYS"='CDW')
     
  3. DISTINCT
      1  select distinct src_sys
      2  from ef_actl_expns
      3  where src_sys = 'CDW'
      4* and actl_expns_amt > 0
    
    -------------------------------------------------------------
    | Id  | Operation                           | Name          |
    -------------------------------------------------------------
    |   0 | SELECT STATEMENT                    |               |
    |   1 |  SORT UNIQUE NOSORT                 |               |
    |*  2 |   TABLE ACCESS BY GLOBAL INDEX ROWID| EF_ACTL_EXPNS |
    |*  3 |    INDEX RANGE SCAN                 | EF_AEXP_PK    |
    -------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       2 - filter("ACTL_EXPNS_AMT">0)
       3 - access("SRC_SYS"='CDW')
    Again, note the NOSORT qualifier.
This is an extraordinary tuning technique in OLTP systems. A SQL with a DISTINCT, GROUP BY, or ORDER BY that uses an index to sort can return just the first page of matching rows without having to fetch the entire result set for a sort. This can be the difference between sub-second response time and several minutes or hours.

Thursday, August 2, 2012

Generate monitoring scripts for all indexes

select 'alter index '||index_name||' monitoring usage' from user_indexes where
      index_type=’NORMAL’;

Saturday, July 14, 2012

Best way to specify columns order in an Oracle concatened index


If I have a table called Test contains 5 columns a, b, c, d and e.
1. What is the deference between index_1, and index_2 if they are defined as:-
  Index_1.
    Create index_1 on test (a, b);
  Index_2.
    Create index_2 on test (b, a).
  Is the order in columns making difference? What is the deference and how it effect.
 
 
The order of the columns can make a difference.  index_1 would be most useful if you ask 
queries such as:

select * from t where a = :a and b = :b;
select * from t where a = :a;
 
Index_2 would be most useful if you ask queries such as:

select * from t where a = :a and b = :b;
select * from t where b = :b;

(in 9i, there is a new "index skip scan" -- search for that there to read about that.  It 
makes the index (a,b) OR (b,a) useful in both of the above cases sometimes!)

So, the order of columns in your index depends on HOW YOUR QUERIES are written.  You want 
to be able to use the index for as many queries as you can (so as to cut down on the over 
all number of indexes you have) -- that will drive the order of the columns.  Nothing 
else (selectivity of a or b does not count at all)
 
An Index Skip Scan can only actually be used and considered by the CBO 
in very specific scenarios and is often an indicator there’s either 
a missing index or an exisiting index has the columns in the wrong 
order.
 
If the leading column of an index is missing, it basically means the 
values in subsequently referenced columns in the index can potentially 
appear anywhere within the index structure as the index entries are 
sorted primarily on the leading indexed column. So if we have column A 
with 100,000 distinct values and column B with 100,000 distinct values 
and an index based on (A,B), all index entries are sorted primarily on 
column A and within a specific value of column A, sorted by column B. 
Therefore if we attempt a search on just Column B = 42, these values 
could potentially appear anywhere within the index structure and so the 
index can not generally be effectively used.
 
However, what if the leading column actually contained very few distinct
 values ? Yes, the subsequent column(s) values could appear anywhere 
within the index structure BUT if these subsequent columns have 
relatively high cardinality, once we’ve referenced the required index 
entries for a specific occurrence of a leading column value, we can 
ignore all subsequent index row entries with the same leading column 
value. If the leading column has few distinct values, this means we can 
potentially “skip” several/many leaf blocks until the leading column 
value changes again, where we can again ”probe” the index looking for 
the subsequent indexed column values of interest.
 
So if we have a leading column with few distinct values, we may be able 
to use the index “relatively” efficiently by probing the index as many 
times as we have distinct leading column values.
 
 

Friday, July 13, 2012

how to determine the optimal column order for a composite index

What is the secret for creating a composite index with the columns in the proper sequence?


  • In general, when using a multi-column index, you want to put the most restrictive column value first (the column with the highest unique values) because this will trim-down the result set.
  • Because Oracle can only access one index, your job is to examine your historical SQL workload and build a single composite index that satisfies the majority of the SQL queries.
  • The Oracle optimizer may try to make single column  indexes behave as-if they were a single composite index.  Prior to 10g, this could be done with the "and_equal" hint.
  • Beware that indexes have overhead
  • You can run scripts to monitor the invocation count for each column in a multiple column composite index

Tuesday, July 10, 2012

When Not to Use Indexes in Oracle

There are some circumstances where indexes can be detrimental to performance and sometimes those indexes should not exist. The Optimizer will occasionally ignore indexes and consider reading the entire table a faster option.
  • A table with a small number of columns may not benefit from an index if a large percentage of its rows are always retrieved from it.
  • NULL values are generally not included in indexes. Do not index columns containing many NULL values unless there is a specific use for it such as filtering the column as NOT NULL, thus only scanning the index and the rows without NULL values.
  • Indexes should usually be created on a small percentage of the columns in a table. Large composite indexes may be relatively large compared with the table. The relative size between index and table is important. The larger the ratio of index to table physical size then the less helpful the index will be in terms of decreasing physical space to be read. Also many columns not in the index may contain NULL values. It may be faster to read the entire table. Why create indexes?
  • Small static data tables may be so small that the Optimizer will simply read those tables as a full table scan and ignore indexes altogether. In some cases the Optimizer may use an index on a small table where it should not since a full table scan would be faster. An exception to this rule will be in mutable joins where unique index hits are often used, even on small tables. If full table scans are faster than index reads in those mutable joins you might want to remove indexes from the small tables altogether or override with hints. Examine your small static data tables. Do they really need indexing ?