[Solved] Query does not use index when used as a view

EverSQL Database Performance Knowledge Base

Query does not use index when used as a view

I wrote a query that when executed on several values - uses the table's index and returns results quickly.

When I created a view using the very same syntax, the index sometimes remain unused.

For example: when querying the following query, the index DEP_IDX is used, and the query takes a few seconds to return results:

Select /*+INDEX (s DEP_IDX) */ department, avg(salary) as dep_avg
From salaries s
Where department in (1,4,7,8)
Group by department

When I create a view using the same syntax, like this:

Create or replace view Departments_Avg_Salary as
  Select /*+INDEX (s DEP_IDX)*/ department, avg(salary) as dep_avg
  From salaries s
  Group by department

And then use the view in a query:

Select e.Employee_Name, e.Employee_Salary, d.dep_avg
From Employees​ e Left join
     Departments_Avg_Salary d
     On d.department = e.Employees_Department
Where e.Employee_Name in ('Michael', 'Nittai', 'Jack')

The Index is not used and the query takes a lifetime to return!

As you can see, using the INDEX hint made no difference...

As it turns out, given the table's​ huge size, there will be no scenario in which using table access storage full will be the efficient way, so I am really looking for a solution that will force the DB to use the index.

Any ideas?

Thanks in advance.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `salaries` ADD INDEX `salaries_idx_department` (`department`);
The optimized query:
        avg(s.salary) AS dep_avg 
        salaries s 
        s.department IN (
            1, 4, 7, 8

Related Articles

* original question posted on StackOverflow here.