Course contentsShow
← Databases & SQL
Lesson 1942 of 1,95318. Application Integration PatternsFree lesson

Query Rewriting and Hinting

Evaluate the necessity of database-specific optimizer hints when automated query plans fail to perform.

In this lesson, you will learn how to determine when to manually intervene in the database optimizer’s decision-making process through query rewriting and hinting.

The Limits of Automation

Modern query optimizers are remarkably sophisticated, using cost-based models to choose the most efficient join algorithms and index scans. However, they rely on statistics—such as table cardinality and column distribution—that can become stale or misrepresentative. When the optimizer generates a sub-optimal execution plan that causes query timeouts or excessive I/O, you are faced with a choice: trust the automated system or manually override it.

Strategic Intervention

Before resorting to hints, prioritize Query Rewriting. This involves restructuring the SQL to be more "optimizer-friendly." For example, transforming a correlated subquery into a JOIN or breaking a complex query into Common Table Expressions (CTEs) can provide the engine with clearer relational boundaries.

If rewriting fails, Optimizer Hints serve as a surgical tool. Hints like /*+ INDEX(users idx_created_at) */ or /*+ LEADING(orders customers) */ explicitly instruct the engine on how to execute the request.

Consider this scenario: you have a high-volume orders table where the optimizer incorrectly chooses a Full Table Scan because it believes the data is too dense to benefit from an index.

-- Forced index usage via hint
SELECT /*+ INDEX(orders idx_status_date) */ 
       id, order_total 
FROM orders 
WHERE status = 'PENDING' 
AND created_at > '2023-01-01';

When to Use Hints

Hints should be treated as a last resort because they represent "hard-coded" execution paths. If the underlying data distribution changes significantly, a hint that was once a performance boost can become a bottleneck. Always treat hinting as a temporary patch; if you find yourself needing to hint frequently, it is usually a sign that your database statistics are inaccurate or your schema design requires refactoring.

Always prefer fixing the root cause (like updating statistics or adding missing indexes) before constraining the engine with hints.

Key Takeaway: Use query rewriting to clarify intent for the optimizer, and reserve hints only as a tactical override when automated planning consistently fails to handle specific, high-stakes query patterns.