Quick revision
The short answer
We build the query from fixed SQL fragments that we wrote, add a fragment only when its filter is present, and bind every value, never concatenating input. For LIKE we bind the whole pattern and escape % and _ in the user's text if they should match literally; for IN lists, NamedParameterJdbcTemplate or JdbcClient expands a collection parameter into the right number of placeholders. For more complex searches, the JPA Criteria API, Spring Data Specifications, jOOQ or Querydsl build dynamic queries safely, and we back it all with tests that send malicious input and a database user with minimal privileges.
What to remember
In this answer, we saw that a dynamic search is safe when its SQL text comes only from fixed fragments in our code and every value is bound. We handled LIKE by binding the pattern and escaping % and _ when they should be literal, used NamedParameterJdbcTemplate's collection expansion for IN lists and noted the limits of long lists, considered Specifications, jOOQ and Querydsl for larger searches, and finished with tests that send malicious input and a least-privilege database user.
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.
We build the query from fixed SQL fragments that we wrote, add a fragment only when its filter is present, and bind every value, never concatenating input. For LIKE we bind the whole pattern and escape % and _ in the user's text if they should match literally; for IN lists, NamedParameterJdbcTemplate or JdbcClient expands a collection parameter into the right number of placeholders. For more complex searches, the JPA Criteria API, Spring Data Specifications, jOOQ or Querydsl build dynamic queries safely, and we back it all with tests that send malicious input and a database user with minimal privileges.
Why this question is asked
Search screens are where SQL injection survives longest, because the query genuinely has to change shape with the user's choices, and the quickest way to do that is string building. A scanner finding one is a good moment to fix the pattern rather than the single line. Interviewers ask this to see whether we know how to keep dynamic SQL safe, including the awkward parts such as LIKE wildcards and IN lists. In this answer, we will look at the vulnerable shape, rebuild it from fixed fragments with bound values, handle LIKE and IN correctly, consider query builders, and add the tests and privileges that keep it safe.
1The Vulnerable Shape
A typical search method looks like this. Each optional filter appends text, and the user's values go straight into that text.
Notice that the dynamic structure is fine; the problem is only that values are pasted in as text. So the fix keeps the structure and changes how values travel.
2Rebuild From Fixed Fragments and Bound Values
The rule is simple: every piece of SQL text comes from a string literal in our code, and every value goes into a parameter map. With NamedParameterJdbcTemplate, or JdbcClient in Spring Framework 6.1 and later, we can use named parameters, which keeps the fragments readable.
- Start with fixed base SQLselect ... where true
- Filter present?name, city, statuses, datesYesAppend its fixed fragmentNoSkip it
- Add the value to the parameter mapnever to the SQL text
- Sort or column choice?user picks a fieldYesMap it through an allow-listNoUse the default order
- Run with bound parameters
NamedParameterJdbcTemplateorJdbcClient
5 steps in order. Play them, or step through them one at a time.
Input decides which fragments we use, never what the fragments say.
Notice that we still append strings, but only constants. The only things that vary with input are which constants we append and the values in the map. The attack text is now a literal search term. The limit is bound as a value too and capped, so a user cannot ask for a million rows. The ilike operator is PostgreSQL's case-insensitive LIKE; on other databases we would use lower(name) like lower(:name).
3Getting LIKE Right
Binding protects LIKE from injection, but there is a second, quieter issue: % and _ are wildcards inside the pattern. If a user searches for 50%, binding alone would treat the % as match anything. If the characters should be literal, we escape them before adding our own wildcards, and declare the escape character in the query.
The order matters: we escape the escape character itself first. Also notice that a leading % prevents a normal B-tree index from being used, so a contains search over a large table is slow however safe it is; PostgreSQL's trigram indexes (pg_trgm) or a search engine are the usual answers there. Escape rules differ slightly between databases, so check yours, for example how MySQL treats backslashes in string literals.
4IN Lists and Their Limits
JDBC has no placeholder for a list. NamedParameterJdbcTemplate solves that: when a named parameter's value is a Collection, it rewrites :statuses into as many question marks as there are elements and binds each one. JdbcClient does the same. An empty collection would produce in (), which is invalid SQL, so we skip the filter when the list is empty, as the code does.
Very long lists cause two problems: each distinct length is a new SQL text, which defeats statement caching, and databases have limits on parameters (Oracle allows 1000 elements in an IN list, and PostgreSQL's protocol limits one statement to 65,535 parameters). On PostgreSQL, binding an array with status = any(:statuses) keeps one SQL text for every length; elsewhere, a temporary table or a join to a values list helps for very large sets.
5Using a Query Builder Instead
When the search grows to dozens of filters, joins and sort options, hand-built strings get hard to review. Typed query builders keep values bound by design. With Spring Data JPA, Specifications combine small predicates built with the JPA Criteria API; jOOQ and Querydsl give a fluent, type-checked SQL builder that binds values automatically.
A null predicate is ignored, so absent filters simply drop out. These tools are not magic: they become unsafe again if we pass raw strings into their plain-SQL escape hatches, such as jOOQ's DSL.condition(String) with concatenated input. The rule about fixed fragments still applies.
6Tests and Least Privilege
Finally we make the fix stay fixed. We add integration tests, against a real database with Testcontainers, that call the search with classic payloads such as ' or '1'='1' --, a quote alone, a semicolon followed by a second statement, % and _, and a very long list, and we assert that results are empty or correct and that no SQL error occurs. A SQL syntax error in such a test is a red flag, because it means input reached the parser.
We also limit what an attacker could do if a mistake slips through. The application's database user should be able to read and write only the tables it needs, never own the schema, and never hold rights such as creating functions or reading system files. A search endpoint can even use a read-only user. Then an injection cannot drop tables or read other services' data.
7Follow-up questions
Is it safe to concatenate a value after validating it with a regular expression?
It is much safer than raw input, and for identifiers mapped through an allow-list it is the right approach, but for values it is the wrong tool. Validation rules drift, break legitimate data such as names with apostrophes, and are easy to get subtly wrong. Binding is always correct for values, so we bind them and keep validation for business rules.
Why does the scanner still complain after we switched to NamedParameterJdbcTemplate?
Static scanners often flag any SQL built with a StringBuilder, because they cannot always prove that every appended piece is a constant. We review the finding, and if every fragment is a literal, we mark it as a false positive with a note, or restructure the code so the scanner can see it, for example by keeping fragments in constants or moving to a query builder.
How do you handle a user-selected sort column in the same search?
The same way as any identifier: through an allow-list map from the sort keys the UI offers to fixed column expressions, with a default for anything unknown, and ASC or DESC chosen from a boolean or enum. Bind parameters cannot stand for column names, so the mapping is what keeps it safe.
8Conclusion
In this answer, we saw that a dynamic search is safe when its SQL text comes only from fixed fragments in our code and every value is bound. We handled LIKE by binding the pattern and escaping % and _ when they should be literal, used NamedParameterJdbcTemplate's collection expansion for IN lists and noted the limits of long lists, considered Specifications, jOOQ and Querydsl for larger searches, and finished with tests that send malicious input and a least-privilege database user.
Open with
I would keep the dynamic structure but change how values travel. The rule is that every piece of SQL text comes from a literal in our code, and every value goes into a parameter.
Then, if they want more
So I start with a fixed base query, and for each filter that is present I append its fixed fragment, like and city = :city, and put the value into a MapSqlParameterSource. NamedParameterJdbcTemplate or JdbcClient then binds them.
For LIKE, I bind the whole pattern, and if the user's % and _ should be literal, I escape them, backslash first, and declare the escape character in the query.
For IN lists, NamedParameterJdbcTemplate expands a collection into the right number of placeholders; I skip the filter when the list is empty, and for very long lists on PostgreSQL I would bind an array with = any instead. Sort columns go through an allow-list.
If the search keeps growing, I would move to a query builder, Spring Data Specifications with the Criteria API, or jOOQ or Querydsl, which bind values by design, as long as nobody uses their raw-string escape hatches with input.
Then two safety nets: integration tests against a real database with classic injection payloads, quotes, wildcards and long lists, where any SQL syntax error is treated as a failure, and a database user with only the privileges the service needs, read-only for search if possible, so a missed mistake cannot do much damage.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- 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
- java.sql, package documentation
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 security scan reports SQL injection in a search feature that builds dynamic WHERE...": https://scrivio-interview-library.netlify.app/databases/jdbc/10c31cebd4/