Query hint

Also known as: optimizer hint

On this page 7

A query hint, also called an optimizer hint, is an instruction written into a SQL statement that tells the query optimizer to use a specific access path, join method, join order or resource setting instead of the plan it would choose on its own. In database performance work, hints are a targeted override: they change how one statement executes without changing its result, and they are usually applied when the cost-based optimizer repeatedly picks a poor plan.

Hints sit at the boundary between declarative SQL and procedural control. SQL describes what data to return, while a hint describes how to fetch it. That makes hints powerful for emergency fixes in Databases of every major vendor, but it also makes them brittle, because a hint that is correct for today’s data volume can become harmful after the data, the schema or the engine version changes.

How a query hint changes the execution plan

A query hint works by constraining the plan search space that the optimizer explores. Normally a cost-based optimizer enumerates candidate plans, estimates the cost of each from optimizer statistics such as row counts, histograms and index selectivity, and keeps the cheapest one. A hint removes some alternatives or forces one, so the final plan reflects the developer’s knowledge rather than the optimizer’s estimate.

The engine parses the hint together with the statement. If the hint is syntactically valid and applicable, the optimizer honors it; if it refers to an index that no longer exists or conflicts with another hint, most engines silently ignore it. That silent behavior is a key operational detail: a broken hint rarely raises an error, so the only evidence is a changed execution plan and a slower query.

The following table shows the main categories of hints and what each one constrains.

Hint categoryWhat it controlsTypical use
Access pathIndex or full table scanForce a selective index the optimizer ignores
Join methodNested loop, hash or merge joinAvoid a hash join on a tiny driving set
Join orderSequence in which tables are joinedStart from the most selective table
ParallelismDegree of parallel executionCap or raise worker count for one query
CardinalityEstimated row countsCorrect a badly skewed estimate
Plan cachingRecompilation and parameter handlingAvoid a plan built for an atypical parameter
LockingLock type and granularityChange isolation behavior for one table
Common categories of query hints

Hint syntax across database engines

Hint syntax is not standardized by ISO SQL, so every engine uses its own form. Oracle and MySQL place hints in a special comment directly after the SELECT keyword, which means an engine that does not understand the hint treats it as an ordinary comment. SQL Server uses the WITH and OPTION clauses, which are part of the grammar and fail loudly if misspelled.

PostgreSQL is the notable exception: the core engine has no built-in hint syntax by design. Its developers argue that hints hide planner bugs and statistics problems. PostgreSQL users who need hints install the pg_hint_plan extension or adjust session-level planner settings such as enable_nestloop. The table below summarizes the main differences.

EngineHint formExampleBehavior if invalid
OracleComment after SELECT/*+ INDEX(o orders_ix) */Ignored silently
MySQLComment or index hint clause/*+ NO_HASH_JOIN(t1) */Warning, then ignored
SQL ServerTable hint or OPTION clauseOPTION (RECOMPILE)Error for most hints
PostgreSQLExtension or planner settingsSET enable_seqscan = offNot applicable in core
Db2Optimization profilesProfile file bound to statementDiagnostic message
Hint mechanisms by database engine

Query hints compared with other tuning tools

A query hint is only one of several ways to influence performance, and experienced engineers treat it as a last resort rather than a first step. Most plan problems come from stale statistics, missing indexes or poorly written predicates, and fixing those root causes helps every query, while a hint helps one statement only.

TechniqueScopeDurabilityMain risk
Query hintSingle statementFixed until code changesBecomes wrong as data grows
Updated statisticsAll queries on the tableAdapts automaticallySampling may miss skew
New indexAll matching queriesPermanentSlower writes, more storage
Plan guide or baselineStatement without code changeManaged centrallyHidden from developers
Query rewriteSingle statementPermanentRequires code release
Database tuning parametersWhole instancePermanentSide effects on other workloads
Hints versus related tuning techniques

Plan guides in SQL Server, SQL plan baselines in Oracle and Query Store forced plans apply a similar effect without editing application code. They are often preferable to inline hints because database administrators can review and remove them centrally, whereas hints scattered through application code are easy to forget.

When a query hint is justified

A hint is justified when the engineer has verified the root cause and knows why the optimizer is wrong, for example a correlated predicate that statistics cannot capture. It is also reasonable as a temporary production fix while a proper solution, such as extended statistics or a schema change, goes through testing.

Before adding a hint, compare the actual execution plan with and without it, measure elapsed time and logical reads on realistic data volumes, and record the reason in a comment next to the hint. The decision table summarizes typical cases.

SituationRecommended actionReason
Stale or missing statisticsRefresh statistics firstFixes the estimate for all queries
Parameter sniffing on skewed dataRecompile or optimize-for hintPrevents one atypical plan being reused
Correlated columns misestimatedExtended statistics, then hint if neededOptimizer assumes column independence
Urgent regression after upgradeTemporary hint or forced planRestores service while root cause is studied
Vendor bug in plan selectionDocumented hint with ticket referenceNo other workaround available
Deciding whether to use a hint

Risks and common mistakes with optimizer hints

The central risk is that a hint freezes a decision that should stay adaptive. Data distributions change, tables grow by orders of magnitude, and new engine versions add better join algorithms, yet the hinted statement keeps using the old path. Teams that rely on hints often discover performance regressions months later with no obvious cause.

  • Forcing an index by name: renaming or dropping the index makes the hint void, often without any error.
  • Over-specifying the plan: combining many hints leaves the optimizer no room to adapt to new data.
  • Testing on small datasets: a nested loop that wins on 1,000 rows can lose badly on 10 million rows.
  • Masking statistics problems: the hint hides a stale histogram that also hurts other queries.
  • Missing documentation: without a comment, nobody knows whether the hint is still needed.

A good practice is to review every hint after each major upgrade and after significant data growth, removing hints that no longer improve the plan. Tools such as the slow query log or pg_stat_statements help identify which hinted statements still deserve attention.

Explained without jargon

A database has a built-in planner that decides the fastest route to collect the data a question needs. Usually it chooses well. Sometimes it guesses wrong, because its picture of the data is outdated or incomplete.

A query hint is a note to that planner saying which route to take. It is like telling a navigation app to use a particular road because you know a bridge is closed. The note helps today, but if the road changes later, the fixed instruction can send you the slow way, so hints should be used sparingly and checked regularly.

A typical use case

An online retailer runs a reporting query that joins an orders table of about 80 million rows with a customers table, filtered by a rarely used region code. After a monthly data load, the optimizer underestimates the rows for one region and switches to a nested loop join. The report, which normally finishes in 4 seconds, now takes more than 6 minutes and blocks a nightly batch.

The database engineer confirms from the execution plan that the estimate is wrong by a factor of 500. As an immediate fix, she adds a hash join hint with a comment referencing the incident, and the report returns to about 5 seconds. In the following sprint, the team creates extended statistics on the correlated region and country columns, verifies that the optimizer now picks the hash join by itself, and removes the hint so the query can adapt again.