Course contentsShow
← Databases & SQL
Lesson 176 of 1,9532. Querying and Data RetrievalFree lesson

Query Plan Hints

Apply manual guidance to the optimizer only when necessary for performance.

In this lesson, you will learn how to manually steer the database engine’s decision-making process when the automatic optimizer fails to find the most efficient path.

The Optimizer's Dilemma

Under normal circumstances, a database uses an "optimizer" to decide exactly how to execute your SQL. It considers your indexes, statistics, and table sizes to choose the best way to fetch your data. Usually, the optimizer is brilliant. However, sometimes the optimizer makes a mistake—perhaps it chooses a slow full-table scan instead of a lightning-fast index scan because it miscalculated the data distribution.

What are Query Plan Hints?

Query Plan Hints are special instructions you embed directly into your SQL statement to "force" the database to follow a specific path. Think of them as a "nudge" (or a direct order) to the engine to ignore its internal logic and do exactly what you say.

For example, if you know that a specific index is always superior for a particular query, but the database refuses to use it, you can add a hint:

SELECT /*+ INDEX(employees idx_emp_dept) */ name 
FROM employees 
WHERE department_id = 5;

In this code, the comment /*+ INDEX(...) */ tells the engine: "I don't care what you calculated; use this specific index."

When to Use (and When to Avoid)

The most important rule of hints is this: They are a last resort.

Because query hints override the optimizer, they can become a maintenance nightmare. If you add a hint today because it makes a query faster, what happens in two years if your data doubles in size or you drop that index? The hint will stay there, potentially forcing the database to use a path that is now incredibly slow.

Only use hints when you have used tools like EXPLAIN to prove the optimizer is consistently choosing a suboptimal plan that creates a performance bottleneck. If the optimizer is doing its job well, stay out of its way!

Key Takeaway: Query Plan Hints allow you to manually override the database's execution strategy, but they should only be used as a last resort when standard optimization fails to provide acceptable performance.