Quick revision
The short answer
A catch-all predicate such as (:status IS NULL OR status = :status) forces one plan to work whether each parameter is null or not, and with prepared statements and generic or cached plans the planner cannot know which, so it often falls back to scanning much of the 50 million row table. The fix is to build the SQL dynamically with only the filters that are present, using JPA Criteria, Spring Data Specifications or jOOQ, so each combination gets its own plan that can use the right index, while keeping the number of shapes bounded and parameterised and adding indexes for the combinations real traffic uses.
What to remember
In this answer, we saw that a catch-all predicate like (:status IS NULL OR status = :status) makes one plan serve both null and non-null parameters, and with prepared statements and generic or cached plans that plan cannot use the indexes, so 50 million rows are scanned. We rewrote it with Spring Data Specifications so only the present filters reach the SQL and each shape gets its own plan, kept the shapes bounded and parameterised to protect the plan cache and pg_stat_statements, and chose composite indexes from the combinations that real traffic uses.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A catch-all predicate such as (:status IS NULL OR status = :status) forces one plan to work whether each parameter is null or not, and with prepared statements and generic or cached plans the planner cannot know which, so it often falls back to scanning much of the 50 million row table. The fix is to build the SQL dynamically with only the filters that are present, using JPA Criteria, Spring Data Specifications or jOOQ, so each combination gets its own plan that can use the right index, while keeping the number of shapes bounded and parameterised and adding indexes for the combinations real traffic uses.
Why this question is asked
Search screens with many optional filters are in almost every business application, and the one-query-for-all-cases trick is very tempting because it keeps the repository method short. It also behaves well in development and then becomes a full table scan in production. Interviewers ask this to see whether we understand how plans are cached and why a predicate that is logically correct can still defeat indexes. In this answer, we will recap the pattern, see why the planner struggles with it, rewrite it dynamically in Spring with Specifications, keep the number of query shapes under control, and choose indexes from real traffic.
1A Quick Recap of the Catch-All Pattern
The idea is to write one query that handles every combination of optional filters. If a filter's parameter is null, its OR branch is always true, so the filter disappears; if it has a value, the second branch applies.
Logically this is correct, and on a table with 10,000 rows in development it is fast. On 50 million rows, a request with status = 'FAILED', which matches 20,000 rows, takes seconds instead of milliseconds.
2Why the Planner Cannot Use the Indexes
An index on status can answer status = 'FAILED'. But the condition here is status = 'FAILED' OR 'FAILED' IS NULL, and whether the second branch is true depends on a parameter value. If the planner must produce one plan that works for any value, including null, it cannot plan an index lookup on status, because for a null parameter the query must return every row. So it plans a scan that evaluates the whole expression row by row.
The decisive factor is when the plan is made. A Java application sends this query as a prepared statement with placeholders. In PostgreSQL the first executions get custom plans, planned with the actual values, and the planner can then simplify a known 'FAILED' IS NULL to false and use the index. After five executions it may switch to a generic plan, which must be valid for every value, and the indexes are out of reach. Other databases cache one plan per statement text too. So the query is fast for a while after deployment and then becomes slow, which makes the problem confusing to diagnose. Even with custom plans, a single shape must serve very different selectivities, such as no filter at all versus one rare status.
- Request arrives with some filters null
- Same SQL text, prepared statementstatus IS NULL OR status = $1
- Generic or cached plan?YesPlan must work for null too: scanNoCustom plan may simplify the ORs
- 50M rows evaluated row by rowseconds per request
4 steps in order. Play them, or step through them one at a time.
3Rewriting It: Only the Filters That Are Present
The fix is to build the WHERE clause from the filters that the request actually contains. Then a request with only status sends WHERE status = ?, and a request with status and date sends WHERE status = ? AND created_at >= ?. Each of these query shapes is planned on its own, and each can use the index that fits. In Spring Data JPA, Specifications are a clean way to do this.
Notice that a Specification returning null adds no condition, so absent filters vanish from the SQL instead of becoming OR branches. The values are still bound as parameters, never concatenated into the text. jOOQ with a list of Conditions, the JPA Criteria API directly, or Querydsl do the same thing. Check your Spring Data version for the exact Specification helper methods; older versions use where(...).and(...).
4Keeping the Number of Shapes Bounded
Dynamic SQL brings its own risk. If we build each query by pasting values into the text, every request creates a unique statement: the database cannot reuse plans, pg_stat_statements fills with thousands of near-identical entries, and we open the door to SQL injection. So the rule is that the shape varies only by which filters are present, and the values are always bind parameters.
With 2 optional filters there are at most 4 shapes; with 6 there are 64, which is still fine for the database's plan caches and for monitoring. If a form has many more optional fields, we group rare ones or limit which combinations the API accepts, for example requiring a date range for any free-text search. A fixed order of conditions also helps, so that status then date and date then status do not count as two different statements.
5Indexes for the Combinations People Actually Use
Dynamic shapes make indexes usable, but we still need the right indexes. Guessing is wasteful, because 64 combinations cannot all have their own index. Instead we measure: each shape appears as a separate normalised statement in pg_stat_statements with its call count and total time, or we log which filters each request uses. Typically a few combinations carry most traffic, for example status alone and status with a date range for the operations team.
| Filters present | Generated WHERE | Index used |
|---|---|---|
| none | no condition, paginated | index on created_at for the ORDER BY |
| status | status = ? | (status, created_at) |
| status and from | status = ? AND created_at >= ? | (status, created_at) |
| from | created_at >= ? | (created_at) |
A composite index on (status, created_at) serves both of those shapes, because status is the leading column. A date-only search needs an index whose leading column is created_at. CONCURRENTLY builds the index without blocking writes on the large table.
6Follow-up questions
How would you find which combinations are common?
Because each shape is a distinct normalised statement, pg_stat_statements already shows calls, total and mean time per combination; sorting by total time shows which shapes matter. In addition, the application can log or count the set of filters used per request, for example as a metric tagged with the filter names, which also shows combinations that are rare but slow. I would review that after a week of real traffic before adding indexes.
Can I keep the single query and just force custom plans?
In PostgreSQL, setting plan_cache_mode = force_custom_plan for that role or session makes the planner see the real values each time and simplify the null branches, which often helps. But it costs planning time on every execution and still gives one SQL shape the job of every combination, so it is a stopgap; the dynamic query is the cleaner fix.
Is this a problem in MySQL too?
Yes. MySQL's optimizer also struggles with OR conditions that mix parameters and columns, and it may not simplify them reliably, so building the query with only the present filters is the recommended approach there as well.
7Conclusion
In this answer, we saw that a catch-all predicate like (:status IS NULL OR status = :status) makes one plan serve both null and non-null parameters, and with prepared statements and generic or cached plans that plan cannot use the indexes, so 50 million rows are scanned. We rewrote it with Spring Data Specifications so only the present filters reach the SQL and each shape gets its own plan, kept the shapes bounded and parameterised to protect the plan cache and pg_stat_statements, and chose composite indexes from the combinations that real traffic uses.
Open with
The problem is that one SQL text has to serve every combination of filters. For an index on status to be used, the planner needs to know that the condition is really status equals some value, but here it is status equals the parameter or the parameter is null, and for a null parameter it has to return every row.
Then, if they want more
The application sends this as a prepared statement, and once PostgreSQL switches to a generic plan, or any database caches one plan for the text, that plan must work for null too, so it ends up scanning and evaluating the ORs row by row across 50 million rows.
It can even be fast just after a deployment, while custom plans are used, and then degrade. I would rewrite it so the SQL only contains the filters that are present.
In Spring Data JPA that is a Specification per filter that returns null when the value is absent, combined with allOf; jOOQ conditions or the Criteria API work the same way. Then status only and status with a date are different shapes, each with its own plan that can use an index.
The values stay bind parameters, never concatenated, so the number of shapes is bounded, at most two to the number of filters, and pg_stat_statements and the plan cache are not flooded.
Finally, I would look at which shapes real traffic uses and add indexes for those, for example a composite index on status and created_at, which serves both status alone and status with a date range.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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 "A search endpoint builds WHERE (:status IS NULL OR status = :status) AND (:from IS NULL...": https://scrivio-interview-library.netlify.app/databases/query-optimization/aec198ac61/