Although I see some good answers, a couple of important points are missing here -
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;
Saying that the presence of SUM (Table_1.Field_5) in the select clause causes the index to not be used incorrectly. Your index on (Field_1,Field_2,Field_3,Field_4)
can still be used. But there are problems with your index and sql query.
Since your index is only on (Field_1,Field_2,Field_3,Field_4)
, even if your index is used, the DB will have access to the actual row of the table to get Field_5 to apply the filter. Now it completely depends on the execution plan drawn from the sql optimizer, which is cost-effective. If the SQL optimizer finds out that a full table scan
is less expensive than using an index, it will ignore the index. Saying this, I will now tell you about probable problems with your index -
- As in other countries, you can simply add Field_5 to the index so that there is no need for separate access to the table.
- Your index order is important for performance. E.g. in your case, if you give the order as
(Field_4,Field_1,Field_2,Field_3)
, then it will be faster, since you have equality in Field_4 - Table_1.Field_4 = '31-oct-2011'
. Think about it -
Table_1.Field_4 = '31-oct-2011'
will give you less options for choosing the final result with Table_1.Field_3 NOT IN (1, 3)
. Things can change as you make the connection. It is always better to see the execution plan and compile your / sql index accordingly.
source share