Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does indexes work with group function in oracle?

I am running following query.

SELECT Table_1.Field_1,
           Table_1.Field_2,
           SUM(Table_1.Field_5) BALANCE_AMOUNT
      FROM Table_1, Table_2
     WHERE Table_1.Field_3 NOT IN (1, 3)
       AND Table_2.Field_2 <> 2
       AND Table_2.Field_3 = 'Y'
       AND Table_1.Field_1 = Table_2.Field_1
       AND Table_1.Field_4 = '31-oct-2011'
     GROUP BY Table_1.Field_1, Table_1.Field_2;

I have created index for columns (Field_1,Field_2,Field_3,Field_4) of Table_1 but the index is not getting used.

If I remove the SUM(Table_1.Field_5) from select clause then index is getting used.

I am confused if optimizer is not using this index or its because of SUM() function I have used in query.

Please share your explaination on the same.

like image 675
Anup Gadve Avatar asked Oct 17 '11 06:10

Anup Gadve


People also ask

Do indexes help with GROUP BY?

The most efficient way to process GROUP BY is when an index is used to directly retrieve the grouping columns. With this access method, MySQL uses the property of some index types that the keys are ordered (for example, BTREE ).

Does a GROUP BY require an index?

Not always. Often a GROUP BY will require Oracle to perform a sort (but not always); and you can eliminate the sort operation by providing a suitable index on the column(s) to be sorted. Whether you actually need to worry about the GROUP BY performance, however, is an important question for you to think about.

In which of the following scenarios indexes should be avoided?

Indexes should not be used on tables containing few records. Tables that have frequent, large batch updates or insert operations. Indexes should not be used on columns that contain a high number of NULL values. Indexes should not be used on the columns that are frequently manipulated.


1 Answers

When you remove the SUM you also remove field_5 from the query. All the data needed to answer the query can then be found in the index, which may be quicker than scanning the table. If you added field_5 to the index the query with SUM might use the index.

like image 50
Tony Andrews Avatar answered Oct 15 '22 19:10

Tony Andrews