Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 134/ 160
07. Indexing, Query Optimization & Performance Tuning

Common Anti-Patterns That Break Indexes (Functions on Columns, Implicit Casts, Leading %)

Avoid wrapping indexed columns, bad casts, and leading-wildcard LIKE patterns.

IntermediateFunction on Column · Implicit Cast3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

If you change the column before comparing it, or compare it with the wrong kind of value, the index can't find the match.

Think of it like…

A library catalogue sorted by surname: it can't help if you search by "surname spelled backwards", or by "surnames ending in -son", or if you write the name in a different alphabet than the catalogue uses. The catalogue exists, but your question doesn't match how it's sorted.

Where you’ve seen it

A MySQL customers table has phone VARCHAR(15) with an index. The app queries WHERE phone = 9876543210 with a number, so MySQL converts every phone string to a number before comparing and scans 8 million rows in 4 seconds. Quoting the value, WHERE phone = '9876543210', uses the index and returns in 1 ms.

Words you’ll hear

Function on column
lower(email) = 'x' can't use an index on email; it needs an index on lower(email).
Implicit cast
The database converts the column to match the value's type, so the index on the original type is skipped.
Leading wildcard
LIKE '%son' can't use a B-tree; trigram GIN indexes can.
Collation mismatch
Comparing under a different collation than the index was built with.

Visual diagram

Loading interactive diagram

Theory & example queries

Type and collation mismatches

When types differ, the database converts one side. In MySQL, comparing a string column with a number converts every row's string to a number, so the index on the string can't be used; quote the value. In SQL Server, a varchar column compared with an nvarchar parameter (the default for many drivers) adds CONVERT_IMPLICIT and can turn an index seek into a scan; set the parameter type to varchar or the driver's sendStringParametersAsUnicode option to false. PostgreSQL usually raises an error for text = integer, but a numeric parameter against a bigint column still casts the column and prevents index use.

Collation matters for text. A PostgreSQL B-tree built under a non-C collation can't serve LIKE 'abc%' prefix searches; create it with text_pattern_ops (or use a C-collated column) for that. Comparing with a different COLLATE than the index's also stops it being used, and MySQL tables or columns with different collations joined together can force conversions on every row.

Spotting an implicit conversionQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1EXPLAIN2SELECT3  *4FROM5  customers6WHERE7  phone = 9876543210;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative MySQL plans
numeric literal -> type: ALL, key: NULL string literal -> type: ref, key: phone_idx

Note: EXPLAIN rows, keys and warnings vary by MySQL version, table statistics and available indexes; the contrast assumes phone is indexed text.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

In MySQL,

shows type: ALL (a full scan) and a warning about the conversion; WHERE phone = '9876543210' shows type: ref using the phone index.

Key takeaway: Match types and collations exactly, including what the driver sends.

Wildcards, expressions and OR

B-trees support prefix matches (LIKE 'Sha%') but not '%son' or '%ar%'. For substring search in PostgreSQL, CREATE INDEX … USING gin (name gin_trgm_ops) with pg_trgm supports both; for suffix-only search, an index on reverse(name) with LIKE reverse('son') || '%' works anywhere. Functions and arithmetic on the column, such as lower(email), price * 1.18 or date_trunc('day', created_at), need either an expression index that matches exactly or a rewrite that leaves the column bare.

WHERE email = $1 OR phone = $2 can't use one composite index; PostgreSQL may combine two indexes with BitmapOr, but other engines or complex ORs may scan. Rewriting as SELECT … WHERE email = $1 UNION SELECT … WHERE phone = $2 lets each branch use its own index. Finally, remember the planner may skip a perfectly usable index on purpose when a condition matches a large share of the table; that's not an anti-pattern.

Substring search with trigramsQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE EXTENSION IF NOT EXISTS pg_trgm;23CREATE INDEX customers_name_trgm ON customers USING gin (name gin_trgm_ops);45SELECT6  id,7  name8FROM9  customers10WHERE11  name ILIKE '%sharma%';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative setup and matches
CREATE EXTENSION CREATE INDEX id | name 1042 | Riya Sharma 2187 | Sharma Textiles 90431 | K. SHARMAN

Note: Assumes the pg_trgm extension is available and these illustrative names satisfy the case-insensitive substring. Actual command tags and matches depend on permissions and data.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Trigram indexes for wildcards; expression indexes or rewrites for functions; UNION for OR.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1EXPLAIN

Confirm the index is skipped

Check whether the plan shows Seq Scan, or uses the index with the condition only as a Filter.

Focus at this step

Seq Scan on customers · Filter: ((phone)::numeric = …)

What to watch at this step
Look for
casts in Filter
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

An index only helps when the query compares the indexed column itself, with the same type and collation, using an operator the index supports. Common ways to break that: wrapping the column in a function (lower(email)), an implicit cast (a text phone column compared with a number), a leading wildcard (LIKE '%son'), arithmetic on the column, OR across different columns, and mismatched collations or parameter types from an ORM. Each forces a scan even though the index exists.

Why it matters: "We have an index, so why is it scanning?" is one of the most common performance questions, and the answer is almost always one of these patterns. Some are invisible in the SQL text, such as an ORM sending a parameter as the wrong type. Recognising them quickly saves hours and is a staple of database interviews.

When to reach for it

  • Diagnosing "the index exists but isn't used"
  • Reviewing ORM-generated queries
  • Designing search on names, emails and codes

When to avoid or be careful

  • Comparing string columns with numbers
  • LIKE '%term%' on large tables with only a B-tree
  • Functions on indexed columns in WHERE

Fixing a predicate vs adding a special index

Rewrite the predicate
Best for: Casts, arithmetic, date functions on the column

Strengths: Uses the existing index; no extra write cost.

Watch out: Needs a code change in every query.

Expression index
Best for: Functions that must stay, like lower(email)

Strengths: Queries stay as written.

Watch out: Only matches that exact expression; another index to maintain.

Trigram GIN index
Best for: Leading or middle wildcards

Strengths: Supports LIKE/ILIKE '%x%' and similarity.

Watch out: Large and slower to update.

Interview signals & numbers to know

When this topic comes up

  • “There's an index on phone, but it does a full scan”
  • “Search by name contains is slow”
  • “The same query is fast in SQL but slow from the app”
  • Implicit conversions
  • LIKE performance

Benchmarks & rules of thumb

1 cast -
enough to skip an index
0 -
B-tree support for LIKE '%x'
text_pattern_ops -
PostgreSQL prefix LIKE under non-C collations

Common mistakes & follow-ups

Common interview mistakes

  • Querying a VARCHAR phone column with an unquoted number in MySQL.
  • Letting a JDBC driver send every string as nvarchar against varchar columns in SQL Server.
  • Creating an index on email while the login query uses lower(email) = lower($1).

Likely interviewer follow-ups

  • Why isn't my index used for WHERE phone = 9876543210?
  • How would you speed up name LIKE '%sharma%'?
  • How can the same query be fast in a SQL client and slow from the application?
Interview tip: Go through the checklist out loud: function, cast, collation, wildcard, OR. Naming implicit casts from ORM parameters stands out because many candidates miss it.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Common Anti-Patterns That Break Indexes (Functions on Columns, Implicit Casts, Leading %) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
SARGable Queries (Writing Index-Friendly WHERE Clauses)
Next topic
Optimizing Slow GROUP BY, DISTINCT & ORDER BY Operations