Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

You are writing data access guidelines for many teams. Which SQL patterns that defeat indexes would you forbid or flag automatically, and how would you enforce the rules?

I would flag a short list of patterns that defeat indexes: functions or arithmetic on indexed columns without a matching expression index, implicit casts, leading-wildcard LIKE, OR across different columns, catch-all optional filters, NOT IN over nullable subqueries, and SELECT * on wide tables where a covering index matters. The rules are enforced with SQL linters in CI, review of the SQL that ORMs actually generate, and plan checks on production-like data, then kept honest by monitoring pg_stat_statements and slow logs. The list stays short and every rule explains why, so teams follow it rather than treat it as arbitrary.

Why this question is asked

When many teams write SQL, the same few mistakes appear again and again, and each one costs an incident or a slow page somewhere. A guideline can prevent most of them, but only if it is specific, enforced by tools rather than memory, and easy to accept. Interviewers ask this design question to see which patterns we consider truly harmful, how we would automate the checks, and how we keep the rules from turning into bureaucracy. In this answer, we will go through the patterns with the reason each one hurts, sort them into forbid and flag, design the enforcement in CI and review, close the loop with production monitoring, and finish with how to write the guideline so people use it.

1Patterns That Stop an Index From Being Used

A B-tree index is only usable when the condition compares the bare indexed column with a value, because the index stores raw column values in sorted order. The first group of patterns breaks this. A function or arithmetic on the column, like DATE(created_at) = ? or amount + 10 > ?, asks about computed values the index does not hold, unless a matching expression index exists. An implicit cast, such as comparing a VARCHAR column with a number in MySQL or a mismatched join key type, is the same thing in disguise. A leading wildcard, LIKE '%son', cannot be searched in sorted order at all.

OR across different columns, such as WHERE email = ? OR phone = ?, is the fourth. Each side could use its own index, and databases can sometimes combine them with a bitmap OR or an index merge, but often the optimizer falls back to a scan. Rewriting as a UNION of two indexed queries, or making sure both indexes exist and checking the plan, is safer.

2Patterns That Mislead the Optimizer or Cost Correctness

The second group is more subtle. Catch-all optional filters, (:p IS NULL OR col = :p), force one cached plan to serve every combination of parameters, so it usually cannot use indexes; the fix is to build the query with only the filters present. NOT IN over a subquery whose column can be NULL is both a performance and a correctness problem: one NULL makes the whole condition unknown, so the query returns no rows, and the planner cannot turn it into an efficient anti-join. NOT EXISTS is the correct rewrite.

SELECT * on wide tables matters where a covering index would otherwise serve the query. If a list endpoint needs id, status and created_at, an index containing those columns allows an index-only scan that never touches the table, but SELECT * forces a table visit for every row and drags large columns over the network. In JPA this often appears as loading full entities for a list view, where a projection would do.

The guideline at a glance
PatternWhy it hurtsPreferred formLevel
Function or math on indexed columnindex holds raw valuesrange on bare column, or expression indexflag
Implicit cast on columnevery row convertedbind the column's own typeforbid
LIKE '%x' on large tableB-tree cannot seek a suffixtrigram index or full-text searchflag
OR across different columnsoften becomes a scanUNION, or check the planflag
Catch-all (:p IS NULL OR col = :p)one plan for every combinationbuild only present filtersforbid
NOT IN (subquery on nullable column)wrong results, no anti-joinNOT EXISTSforbid
SELECT * on wide tablesno covering index, extra I/Oselect needed columns, projectionsflag
Forbid means CI fails without a waiver; flag means a reviewer must look.

3Forbid or Flag

Not every pattern deserves the same treatment. Some are almost always wrong and have a clear alternative: implicit casts, catch-all filters on large tables and NOT IN over nullable subqueries. Those we forbid, meaning a CI check fails unless the author adds a written waiver. Others are fine in some contexts: a function on a column is harmless on a table of 300 rows, and SELECT * is acceptable when the entity really needs every column. Those we flag, meaning a reviewer is asked to look but the build passes.

The distinction matters because a rule that blocks legitimate code teaches people to ignore or disable the tool. Keeping the forbidden list to a few clearly harmful patterns makes failures rare and credible.

4Enforcing the Rules

Enforcement has three layers, each catching what the previous one misses. First, a SQL linter in CI scans handwritten SQL in repositories, migration files and @Query annotations for the forbidden shapes. Linters such as SQLFluff can be extended with custom rules, and simple patterns like LIKE '% or IS NULL OR are easy to match.

Second, the SQL that ORMs generate is reviewed, because much of our SQL is never written by hand. During integration tests we capture the statements Hibernate actually sends, through a statement inspector or a datasource proxy, and run the same rules on them. This is where a Long field mapped onto a VARCHAR column or a list view loading full entities shows up.

Third, plan checks catch what text rules cannot see. On a database seeded with production-like volume and distribution, CI runs EXPLAIN on the captured queries and flags sequential scans on tables above a size threshold or costs above a limit. A linter cannot know that a predicate is sargable but the index is missing; a plan check can.

Step throughLayers of enforcement
  1. SQL linter in CIhandwritten SQL, @Query strings, migrations
  2. Generated SQL capturestatements Hibernate really sends during tests
  3. Plan checks on realistic dataEXPLAIN flags scans on big tables
  4. Production monitoringpg_stat_statements and slow logs find what slipped through

4 layers, from the top down. Step through them one at a time.

5Closing the Loop With Production

Rules written in advance will always miss something. So we monitor pg_stat_statements on PostgreSQL and the slow query log or performance_schema digests on MySQL, sorted by total time, and review the top entries regularly with the owning teams. When a regression turns out to be a pattern the guideline does not cover, we add it, with the incident as the example. When a rule produces mostly waivers, we change or remove it. The guideline becomes a living document fed by real evidence rather than a list someone wrote once.

6Writing the Guideline So People Use It

The most important design decision is length. Seven rules that everyone knows beat forty that nobody reads. Each rule gets three things: one sentence on why it hurts, a before and after example in the team's own stack (SQL, JPA query and Specification), and a link to a real incident if one exists. Explaining the reason lets engineers recognise new variants of the same mistake, which no linter can list in full, and stops the rules feeling arbitrary. Champions in each area answer questions and propose changes, so the guideline has owners close to the code.

7Follow-up questions

How do you stop the linter from producing false positives on small tables?

Text rules cannot know table sizes, so the size-sensitive patterns are only flagged by the linter and confirmed by the plan check, which does know the size. A small configuration file listing large tables lets the linter raise the severity only for those. Waivers with a short reason handle the remaining cases.

Why include NOT IN in a performance guideline?

Because it is both a correctness and a performance trap. With a nullable subquery column it can silently return no rows, and the planner cannot use an efficient anti-join for it. NOT EXISTS is correct in all cases and plans well, so a simple rule to prefer it removes a whole class of bugs.

Should ORMs be forbidden from generating queries?

No. ORMs are productive and their generated SQL is usually fine. The guideline asks teams to check the SQL their ORM really generates for important queries and gives specific advice, such as using projections for list views and matching entity field types to column types.

8Conclusion

In this answer, we designed a data access guideline around a short list of index-defeating patterns: functions or arithmetic on columns, implicit casts, leading wildcards, OR across columns, catch-all filters, NOT IN over nullable subqueries and SELECT * on wide tables. We split them into forbidden and flagged, enforced them with a SQL linter, a review of ORM-generated SQL and plan checks on realistic data, fed production findings from pg_stat_statements and slow logs back into the rules, and kept the guideline short with the reason for every rule.

What to say in the interviewAbout 90 seconds aloud

Open with

I would keep the list short and split it into two levels. Forbidden, meaning CI fails without a written waiver: implicit casts on columns, like binding a number to a VARCHAR column, catch-all optional filters like parameter IS NULL OR column equals parameter on large tables, and NOT IN over a nullable subquery, which can return no rows at all and blocks an anti-join.

Then, if they want more

Flagged, meaning a reviewer has to look: functions or arithmetic on indexed columns without a matching expression index, leading-wildcard LIKE, OR across different columns, and SELECT star on wide tables where a covering index or a projection would help. Each rule says why it hurts and shows the preferred form in our stack. For enforcement I would use three layers.

A SQL linter in CI checks handwritten SQL, @Query strings and migrations. Then, because much of our SQL comes from Hibernate, we capture the generated SQL during integration tests and run the same rules, which catches mapping problems like type mismatches.

Then plan checks run EXPLAIN on those queries against production-like data and flag sequential scans on big tables, which text rules cannot see. Finally, pg_stat_statements and slow logs show what still slips into production, and those findings update the guideline, adding rules that real incidents justify and removing rules that only produce waivers.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You are writing data access guidelines for many teams. Which SQL patterns that defeat...": https://scrivio-interview-library.netlify.app/databases/query-optimization/569c586034/