DBAtlas · Database operations atlas

Manage bind variables / parameter sniffing

Oracle

-- Use binds instead of literals (for plan sharing):
SELECT * FROM customer WHERE city = :city;
-- Share legacy code that uses literals:
ALTER SESSION SET cursor_sharing = FORCE;

Bind variables reduce hard parses. Adaptive Cursor Sharing mitigates sniffing problems by keeping multiple plans for bind values with skewed distributions. Use cursor_sharing=FORCE with care.

PostgreSQL

-- Parameterize with a prepared statement:
PREPARE q (text) AS SELECT * FROM customer WHERE city = $1;
EXECUTE q('Ankara');
-- Set plan cache behavior:
SET plan_cache_mode = force_custom_plan;

plan_cache_mode=auto chooses between generic and custom plans; force_custom_plan produces a parameter-specific plan on every execution (a fix for sniffing-like problems).

MySQL

-- Server-side prepared statement:
PREPARE stmt FROM 'SELECT * FROM customer WHERE city = ?';
SET @city = 'Ankara';
EXECUTE stmt USING @city;
DEALLOCATE PREPARE stmt;

Prepared statements prevent SQL injection and lower parsing cost. MySQL also supports parameterization at the driver level.

SQL Server

-- Parameterized query (sp_executesql):
EXEC sp_executesql N'SELECT * FROM dbo.customer WHERE city = @city', N'@city nvarchar(50)', @city = N'Ankara';
-- Handle sniffing with a hint:
SELECT ... OPTION (RECOMPILE);
-- or OPTION (OPTIMIZE FOR (@city = 'Ankara'));

OPTION(RECOMPILE) produces a parameter-specific plan on every execution (CPU-expensive). OPTIMIZE FOR pins the plan to a specific/typical value; OPTIMIZE FOR UNKNOWN uses average selectivity.

MongoDB

// The query shape is the key of the plan cache:
db.customer.find({ city: "Ankara" }).explain("queryPlanner")
// Clear a stale plan:
db.customer.getPlanCache().clear()

Queries with the same shape (same fields/operators) share the cached plan; different literal values do not produce a new plan. If the value distribution is highly skewed, reset it with planCacheClear.

Redis

# Not applicable: there is no query planner or parameter sniffing.

Commands execute directly; key design, not parameterization, determines performance.

Elasticsearch

# Reuse the query with a parameterized search template:
POST _scripts/customer_city
{ "script": { "lang": "mustache", "source": { "query": { "term": { "city": "{{city}}" } } } } }
GET <index>/_search/template
{ "id": "customer_city", "params": { "city": "Ankara" } }

A search template (Mustache) parameterizes the query body; the application calls a fixed template with different values, improving query consistency and cache usage.

Open in DBAtlas →