// SQL snippet

Find queries that put functions on indexed columns in PostgreSQL

UPPER(col) in a WHERE clause quietly disables the index on col. This finds the hot queries doing it.

Main statement
PostgreSQL
Deckt außerdem ab
SQL Server MySQL

The task

A sargable predicate lets the planner seek an index directly: col = 'x'. Wrapping the column in a function, as in UPPER(col), DATE_TRUNC('day', col) or CAST(col AS date), makes it non-sargable: a plain B-tree index on col stores col's values, not the function's results, so the planner cannot seek it and falls back to a sequential scan or a full index scan. There are two fixes. Rewrite the predicate so the column stands alone (col >= DATE '2026-01-01' AND col < DATE '2026-01-02'), or create an index on the expression itself.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT calls,
       ROUND(mean_exec_time::numeric, 1) AS mean_ms,
       ROUND(total_exec_time::numeric, 0) AS total_ms,
       LEFT(query, 140) AS query
FROM pg_stat_statements
WHERE query ~* '(WHERE|JOIN|ON)[^(]*(UPPER\s*\(|LOWER\s*\(|SUBSTRING\s*\(|TRIM\s*\(|DATE_TRUNC\s*\(|CAST\s*\()'
  AND calls > 100
ORDER BY total_exec_time DESC
LIMIT 20;

So funktioniert es

pg_stat_statements stores normalized query text (constants replaced by $1, $2), so a case-insensitive regular expression (~*) over it finds statements where a function call follows WHERE, JOIN or ON with no opening parenthesis in between. It is a text heuristic. It flags harmless calls such as UPPER($1) on a parameter, misses functions used later in a long WHERE clause after another parenthesis, and only sees the outer statement text (statements inside functions appear only when pg_stat_statements.track = all). Ordering by total_exec_time puts the candidates that cost the most first. Confirm each one with EXPLAIN before rewriting: the plan shows whether the index was actually skipped. The view exists only once pg_stat_statements is preloaded and created; the most-expensive-queries recipe has the setup.

Variations

MySQL: find digest statements with functions on columns

MySQL
SELECT COUNT_STAR,
       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,
       LEFT(DIGEST_TEXT, 140) AS digest
FROM performance_schema.events_statements_summary_by_digest
WHERE DIGEST_TEXT REGEXP '(WHERE|JOIN|ON)[^()]*((UPPER|LOWER|SUBSTRING|TRIM|CAST|DATE)[[:space:]]*\\()'
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 20;

SQL Server: scan the plan cache for implicit conversions

SQL Server
SELECT TOP 20
    qs.execution_count,
    CAST(qs.total_logical_reads / 1000.0 AS DECIMAL(18,1)) AS reads_k,
    st.text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE qp.query_plan.exist('declare namespace p="http://schemas.microsoft.com/sqlserver/2004/07/showplan";
    //p:PlanAffectingConvert') = 1
ORDER BY qs.total_logical_reads DESC;

Questions that come up

What is the standard rewrite for a date-range filter?

Instead of WHERE CAST(updated_at AS date) = '2026-01-01', write WHERE updated_at >= DATE '2026-01-01' AND updated_at < DATE '2026-01-02'. The column stays bare, the index applies, and midnight-to-midnight semantics are exact even with fractional seconds.

Can I keep the function and still use an index?

Yes, by indexing the expression. In PostgreSQL, CREATE INDEX ON users (lower(email)) serves WHERE lower(email) = $1, as long as the query uses exactly the same expression. MySQL 8.0.13 and later support functional key parts: CREATE INDEX ix_email_lower ON users ((LOWER(email))). In SQL Server, add a computed column for the expression and index it; the optimizer can match the expression in the query to the indexed computed column.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.