Course contentsShow
← Databases & SQL
Lesson 615 of 1,9536. Query Performance and IndexingFree lesson

Forced Indexing and Optimizer Hints

Use optimizer hints as a last-resort to override faulty execution path selections.

In this lesson, you will learn how to manually instruct the database engine to use a specific index when the query optimizer makes an incorrect decision about your execution plan.

When the Optimizer Gets it Wrong

Under normal circumstances, the database query optimizer is remarkably smart. It analyzes your query, checks the table statistics, and calculates the "cost" of different ways to retrieve your data. However, sometimes the optimizer relies on stale statistics or misjudges data distribution, choosing a slow Full Table Scan when a perfectly good index exists.

Before you consider manual intervention, remember that hints are a last resort. First, ensure your statistics are updated and your indexes are properly maintained. If the performance remains sub-optimal, you can use an optimizer hint to force the engine’s hand.

Applying the Hint

Optimizer hints are comments injected into your SQL statement that provide direct instructions to the engine. While the syntax varies by database (e.g., Oracle, SQL Server, or MySQL), the concept is the same: you are overriding the automatic selection process.

For example, imagine you have an index named idx_customer_status. If the optimizer decides to ignore it, you might write:

-- Forcing the use of a specific index (syntax example)
SELECT /*+ INDEX(orders idx_customer_status) */ *
FROM orders
WHERE status = 'pending';

By adding this hint, you tell the engine: "Ignore your cost-based math; I know this index is the fastest way to get these rows."

The Danger of Hints

While hints solve immediate performance problems, they are "hard-coded" into your application. If you drop the index or rename it later, the query might fail or perform even worse because the hint is no longer valid. Furthermore, as your data grows, the path that was optimal today might become inefficient tomorrow, but your hint will continue to force the engine to use that path regardless of the reality on the ground. Always monitor queries with hints closely after major data migrations or schema changes.

Key Takeaway: Optimizer hints are a temporary "surgical strike" to bypass faulty execution plans; they should be used sparingly because they bypass the optimizer's ability to adapt to changing data distributions.