Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

An admin search screen builds WHERE clauses from up to 12 optional filters and sorts by any column the user clicks. Queries are fast for some combinations and take 30 seconds for others on a 200 million row table. How do you approach this as the service owner?

I would start by measuring which filter and sort combinations are slow, using pg_stat_statements or the slow query log and EXPLAIN (ANALYZE, BUFFERS). Then I would index the common, selective combinations and restrict the rest: sort only on indexed columns or require a selective filter. In the code, I would build only the predicates that are present instead of catch-all (:p IS NULL OR col = :p) conditions, whitelist the sort column and direction, and protect the database with keyset pagination, statement timeouts and a row cap, moving free-text and faceted search to a search engine if users need it.

Why this question is asked

Admin search screens with many optional filters are a classic way to bring a database to its knees. They start small, someone adds a filter every quarter, and one day a support agent clicks a column header on a 200 million row table and waits 30 seconds while every other query slows down. Interviewers ask this because there is no single trick that fixes it: the answer combines measurement, index design, query building, security and product limits. In this answer, we will see why some combinations are fast and others slow, how to find the slow ones, why catch-all predicates make things worse, how to handle sorting safely, and which guardrails keep the screen from hurting the rest of the system.

1Why Some Combinations Are Fast and Others Take 30 Seconds

An index helps when it lets the database read a small part of the table. If an agent filters by customer_id, and there is an index on customer_id, PostgreSQL reads perhaps 50 rows. If the agent filters only by country = 'US' and sorts by last_name, the filter matches 80 million rows, and unless an index happens to deliver rows in last_name order, the database must read all of them and sort them before it can return the first 50.

With 12 optional filters there are 4,096 possible combinations of filters, and each can be sorted by any column in two directions. No team can create an index for each. So the goal is not to make every combination fast; it is to make the common ones fast and to stop the expensive ones from running unbounded.

2Measuring Which Combinations Are Slow

Before changing anything, I would find out what users actually do. In PostgreSQL the extension pg_stat_statements groups queries by their shape and records how often each runs and how long it takes. In MySQL the slow query log and the performance_schema digest tables do the same job. It also helps to log, from the application, which filters and sort were used for each search, because that gives the product view: perhaps 90 percent of searches use customer, order number or date range.

For the slow shapes, EXPLAIN (ANALYZE, BUFFERS) shows the real plan: which index was used, how many rows were read and thrown away, whether a sort spilled to disk, and how many pages came from cache or disk.

SQL
-- Top query shapes by total time (PostgreSQL)
SELECT calls, round(mean_exec_time) AS mean_ms, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
-- Inspect one slow combination
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, last_name, status FROM customers
WHERE country = 'US'
ORDER BY last_name
LIMIT 50;
-- Sort Method: external merge Disk: 1843200kB <- reads all US rows and sorts on disk
-- Execution Time: 29876 ms

That plan tells us exactly what is wrong: the filter is not selective and the sort has no supporting index, so 80 million rows are sorted to return 50.

3Indexing the Common Cases and Restricting the Rest

With the usage data in hand, I would create indexes for the frequent and selective filters, often composite indexes that also cover the default sort, such as (status, created_at). Rare filters on unselective columns do not get an index. Instead, the product rules change: sorting is offered only on columns that have an index, and a search that uses only unselective filters must include at least one selective filter, such as a date range of at most 90 days, before it runs.

These rules are a conversation with the product owner, not a unilateral decision. I would bring the numbers: these 6 combinations cover 95 percent of searches and will be under 200 milliseconds, and these others cost 30 seconds and slow down checkout while they run.

4Avoiding Catch-All Predicates

A popular way to write a dynamic search is one fixed query that handles every filter with an IS NULL test. It looks tidy, but it hurts performance.

SQL
-- Catch-all: one query for every combination
SELECT * FROM orders
WHERE (:customerId IS NULL OR customer_id = :customerId)
AND (:status IS NULL OR status = :status)
AND (:fromDate IS NULL OR created_at >= :fromDate);
Step throughBuilding the search query safely
  1. Read the filters from the requestonly non-empty ones
  2. Add one predicate per present filtervalues as bind parameters
  3. Is a selective filter present?
    YesContinueNoReject with a helpful message
  4. Map sort key through a whitelistfor example lastName -> last_name
  5. Add keyset condition and LIMIT 50plus id as tiebreaker
  6. Run with a statement timeoutfor example 5 seconds

6 steps in order. Play them, or step through them one at a time.

The problem is the plan. A prepared statement may be planned once and reused, and a single plan must work whether customerId is given or not, so it often cannot use the customer_id index. PostgreSQL may switch to a generic plan after a few executions, and then every combination gets the same mediocre plan. So the better pattern is to build only the predicates that are present, still with bind parameters for the values. Spring Data JPA Specifications, the Criteria API, jOOQ or a small query builder all do this. Each combination then has its own SQL text and gets a plan suited to it.

5Sorting Safely: Why ORDER BY Needs a Whitelist

Bind parameters protect values, but a column name in ORDER BY cannot be a bind parameter. If we write ORDER BY :column, the database treats it as a constant and sorts by nothing useful. So developers are tempted to concatenate the sort column from the request into the SQL, and that opens the door to SQL injection through the sort parameter.

Java
// Unsafe: the request controls raw SQL
String sql = "SELECT ... ORDER BY " + request.sort(); // sort=(SELECT pg_sleep(30))
// Safe: map public names to known columns
private static final Map<String, String> SORTS = Map.of(
"created", "created_at",
"total", "total",
"status", "status");
String column = SORTS.get(request.sort());
if (column == null) throw new BadRequestException("unknown sort");
String direction = request.desc() ? "DESC" : "ASC";
String orderBy = " ORDER BY " + column + " " + direction + ", id " + direction;

Notice that only strings from our own map ever reach the SQL. The whitelist also doubles as the product rule from the previous section: it lists exactly the sortable columns, which are the indexed ones.

6Guardrails: Keyset Pagination, Timeouts and a Search Engine

Even with good indexes, I would protect the database. Keyset pagination, where the next page starts after the last seen (sort value, id), keeps deep pages cheap; OFFSET 100000 makes the database read and discard 100,000 rows. A statement timeout for the admin role, such as SET statement_timeout = '5s' or a JDBC query timeout, means a bad combination fails fast instead of holding resources. A row cap stops anyone from paging through millions of rows; for that, there should be an export job. Running the admin search against a read replica keeps it away from the checkout traffic.

Finally, if users really need free text, partial matching on names and counts per facet, that is what search engines such as OpenSearch or Elasticsearch are built for. We would feed them from the database with change data capture and keep PostgreSQL for the transactional work.

7Follow-up questions

How does a prepared statement's generic plan affect this in PostgreSQL?

PostgreSQL plans the first five executions of a prepared statement with the actual parameter values, a custom plan each time. After that it compares costs, and if a generic plan, made without knowing the values, looks no worse on average, it keeps using the generic one. For a catch-all query, the generic plan cannot know which filters are active, so it often picks a sequential scan that is fine for some combinations and terrible for others. The PostgreSQL JDBC driver uses server-side prepared statements after prepareThreshold executions (5 by default), so this really happens from Java. Building only the present predicates avoids the problem, and plan_cache_mode = force_custom_plan is a narrower fix when we cannot change the query.

8Conclusion

In this answer, we saw that the slow combinations are those where unselective filters meet a sort with no supporting index. The service owner measures real usage with pg_stat_statements and EXPLAIN (ANALYZE, BUFFERS), indexes the common selective cases, agrees product limits for the rest, builds only the predicates that are present, whitelists sort columns because ORDER BY cannot be bound, and adds keyset pagination, timeouts and row caps, moving free-text and faceted search to a search engine when needed.

What to say in the interviewAbout 80 seconds aloud

Open with

First I would measure instead of guessing. I would use pg_stat_statements or the slow query log to find the slow query shapes, log which filters and sorts users actually choose, and run EXPLAIN ANALYZE with BUFFERS on the slow ones.

Then, if they want more

Usually the slow cases are unselective filters combined with a sort on an unindexed column, so the database sorts millions of rows to return fifty.

With 12 filters there are thousands of combinations, so I would index the common selective ones, often a composite index that also covers the default sort, and agree with product that sorting is only allowed on indexed columns and that broad searches need a selective filter such as a bounded date range.

In the code I would avoid catch-all predicates like parameter IS NULL OR column equals parameter, because a prepared statement's generic plan can't use the right index; instead I build only the predicates that are present with Specifications or jOOQ. ORDER BY cannot be bound, so I would whitelist sort columns and directions to prevent SQL injection.

Then I add keyset pagination, a statement timeout, a row cap, a read replica for admin traffic, and if they need free text and facets, a search engine fed by CDC.

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 "An admin search screen builds WHERE clauses from up to 12 optional filters and sorts by...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/3442582c05/