Lesson 4 | Overriding the default Optimizer Mode |
Objective | Override the default optimizer mode for a Query |
Using Optimizer Hints (Preferred Approach)
Oracle provides optimizer hints that you can embed within a SQL statement to influence how the optimizer processes the query.
The
/*+ OPTIMIZER_MODE(...) */
hint allows you to override the default optimizer mode.
Example: Changing the Optimizer Mode for a Query
SELECT /*+ OPTIMIZER_MODE(FIRST_ROWS) */ employee_id, first_name, last_name FROM employees WHERE department_id = 10;
ALL_ROWS
: Optimizes for the best throughput (default for cost-based optimizer).FIRST_ROWS(n)
: Optimizes for fast response time, retrieving the first n
rows quickly.RULE
: Uses the rule-based optimizer (deprecated in Oracle 10g and later).Changing the Optimizer Mode at the Session Level
If you want to change the optimizer mode for all queries in a session, you can modify the session parameter using:
ALTER SESSION SET OPTIMIZER_MODE = FIRST_ROWS;
or
ALTER SESSION SET OPTIMIZER_MODE = ALL_ROWS;
This will apply to all queries executed in the session.
Changing the Optimizer Mode for the Entire Database
If you want to set a new default optimizer mode for the entire database, you can modify the system parameter:
ALTER SYSTEM SET OPTIMIZER_MODE = FIRST_ROWS;
However, this change will affect all queries running on the database instance.
Using SQL Profiles or SQL Plan Baselines (Advanced)
If you need more fine-grained control over optimizer behavior, you can use SQL Profiles or SQL Plan Baselines to influence execution plans without modifying the SQL statements.
ALTER SESSION SET OPTIMIZER_GOAL=all_rows, first_rows, or rule
SQL> alter session set optimizer_goal=rule; Session altered.
/*+ all_rows */ /*+ first_rows */ /*+ rule */