Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

This Spring Data repository code uses parameters, yet a penetration test still finds SQL injection. Where is the hole and how do you fix it?

Java
String sql = "SELECT * FROM orders WHERE customer_id = ? ORDER BY " + sortColumn + " " + direction;
jdbcTemplate.query(sql, mapper, customerId);

The customer id is bound safely, but sortColumn and direction are pasted into the SQL text, and bind parameters can only carry values, never column names or keywords. Anyone who controls sortColumn can add their own SQL to the ORDER BY clause. The fix is an allow-list that maps the public sort names to real column names, plus an enum or check that accepts only ASC or DESC, so user input never becomes SQL text.

Why this question is asked

Teams that learned to always use PreparedStatement often believe their code is immune to SQL injection, so a penetration test finding in parameterised code is a surprise. The hole is almost always in the parts of a query that cannot be parameters: sort columns, directions, table names and lists. Interviewers like this question because it checks whether we know what a bind parameter actually does, not just the rule to use one. In this answer, we will recap how bind parameters work, show how the ORDER BY hole is exploited, fix it with an allow-list, look at what Spring Data's Sort does and does not protect, and list the related places with the same risk.

1A Quick Recap of Bind Parameters

A bind parameter is the question mark in a SQL statement. The driver sends the SQL text and the values separately, so the database parses the statement first and only then plugs in the values. Whatever the value contains, even quotes and SQL keywords, it can only ever be data in that position. That is why WHERE customer_id = ? is safe no matter what customerId holds.

But the database must know the shape of the statement, meaning which tables, columns and keywords it uses, before it can parse it. So the shape cannot come from a parameter. ORDER BY ? is legal in some databases, but it sorts by a constant value, not by the column whose name we passed, so it silently does nothing useful. That is why developers fall back to string concatenation for sorting, and that is where the hole opens.

2Reproducing the Problem

Here is the code from the question, called from a controller that takes sort and dir as request parameters.

Java
String sql = "SELECT * FROM orders WHERE customer_id = ? ORDER BY " + sortColumn + " " + direction;
jdbcTemplate.query(sql, mapper, customerId);
// normal request: ?sort=created_at&dir=DESC
// SELECT * FROM orders WHERE customer_id = ? ORDER BY created_at DESC
// attack: ?sort=(CASE WHEN (SELECT substr(password_hash,1,1) FROM users WHERE id=1)='$' THEN id ELSE total END)&dir=
// SELECT * FROM orders WHERE customer_id = ? ORDER BY (CASE WHEN (SELECT ...)='$' THEN id ELSE total END)
// the order of the rows now reveals one character of another table's data
What a bind parameter can and cannot carry
Part of the queryCan be a ? parameterSafe approach
Values in WHERE, VALUES, SETyesbind it
Column in ORDER BYnoallow-list map to a column name
ASC or DESCnoenum or exact check
Table or schema namenoallow-list, never user text
LIKE patternyes, but % and _ stay specialbind and escape wildcards
IN listone ? per elementnamed parameter list expansion

Notice that the attacker does not need to see an error or extra columns. The query is still valid, and the attacker only watches whether the rows come back sorted by id or by total. By repeating the request with different characters, they read another table one character at a time. This is called blind injection, and automated tools do it in minutes. Depending on the database and driver, the same hole can also cause errors that leak information or heavy queries that slow the database down.

So the problem is not that the query is unparameterised. The problem is that two pieces of user input become part of the SQL text.

3Fixing It With an Allow-List

The fix is to stop treating sortColumn as SQL. The client sends a public sort name, and the server looks it up in a fixed map of names it knows. The SQL text only ever contains strings written by us.

Java
private static final Map<String, String> SORT_COLUMNS = Map.of(
"date", "created_at",
"total", "total_amount",
"status", "status");
List<Order> findOrders(long customerId, String sort, String dir) {
String column = SORT_COLUMNS.get(sort);
if (column == null) throw new IllegalArgumentException("unknown sort: " + sort); // -> 400
String direction = "desc".equalsIgnoreCase(dir) ? "DESC" : "ASC";
String sql = "SELECT * FROM orders WHERE customer_id = ? ORDER BY " + column + " " + direction;
return jdbcTemplate.query(sql, mapper, customerId);
}
findOrders(7, "date", "desc"); // ORDER BY created_at DESC
findOrders(7, "(CASE WHEN ...)", ""); // IllegalArgumentException, nothing reaches the database

What changed is that the concatenated pieces now come from our own constants. The direction can only be one of two literals, whatever the client sent. The map also decouples the API from the schema: if we rename created_at, the public name date stays the same. A nice side effect is that we can index exactly the sort columns we allow, instead of letting clients sort by anything.

4What Spring Data Sort Protects, and What It Does Not

Spring Data repositories accept a Pageable or Sort parameter. For derived query methods such as findByCustomerId(id, pageable), Spring Data resolves each sort property against the entity's attributes, so an unknown property like (CASE WHEN ...) fails with an exception before any SQL runs. For JPQL @Query methods, Spring Data appends the order clause and rejects expressions it does not recognise as properties or aliases, and JpaSort.unsafe exists precisely for the cases where we deliberately want a raw expression.

Native queries are different. With nativeQuery = true, Spring Data cannot check the sort against an entity, and how it handles Sort depends on the version, so we should treat a client-supplied sort on a native query with the same allow-list as plain JDBC. Check your version, and in any case never pass a sort string from the request into JpaSort.unsafe.

5The Same Risk in Other Places

The ORDER BY case is one example of a general rule: anything in the SQL shape that comes from input is a hole. Table names chosen from a request parameter, for example for per-tenant tables, need the same allow-list. LIKE patterns are safely bound, but % and _ keep their wildcard meaning, so a search for 100% matches everything starting with 100; we escape them before binding. IN lists built by joining ids into a string are injectable, while NamedParameterJdbcTemplate with a collection parameter expands it into one placeholder per element. And JPQL built by concatenation has the same problem as SQL, just in a different language.

Java
String escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
jdbc.query("SELECT * FROM products WHERE name LIKE ? ESCAPE '\\'", mapper, escaped + "%");
namedJdbc.query("SELECT * FROM orders WHERE id IN (:ids)",
Map.of("ids", List.of(4L, 8L, 15L)), mapper); // IN (?, ?, ?)

6Keeping It From Coming Back

A fix in one method does not stop the next developer from writing the same concatenation. So we add a test that sends typical attack strings to every endpoint with a sort parameter and expects a 400 response, and a static analysis rule that flags SQL strings built with + or String.format, for example Find Security Bugs for SpotBugs or a Semgrep rule. Reviewers then only need to look at the flagged lines, which are rare once the allow-list pattern is the norm.

7Follow-up questions

Why not just escape quotes in sortColumn?

Because an ORDER BY expression does not need quotes at all. The attack above uses parentheses, CASE and a subquery, none of which an escaping function for string literals would touch. Escaping helps only inside a quoted literal, and identifiers are not literals, so an allow-list is the only robust answer.

Could we validate sortColumn with a regular expression instead of a map?

A strict pattern such as letters and underscores only would block this payload, but it still lets the client sort by any existing column, including ones we did not mean to expose or index, and it ties the API to the schema. The map is simpler, safer and better for the API design.

Is the same code safe if we switch to an ORM?

Only if we stop concatenating. JPQL or HQL built with + is just as injectable, and native queries are plain SQL. The ORM helps when we use its parameter binding and its validated Sort, not when we build query strings ourselves.

8Conclusion

In this answer, we saw that bind parameters protect values but not the shape of a statement, so the concatenated sortColumn and direction let an attacker inject SQL into ORDER BY and read data blindly. We fixed it with an allow-list map from public names to columns and a fixed ASC or DESC, saw that Spring Data's Sort validates properties for derived and JPQL queries but needs care with native ones, covered the same risk in table names, LIKE patterns, IN lists and concatenated JPQL, and added tests and static analysis to keep it fixed.

What to say in the interviewAbout 80 seconds aloud

Open with

The customer id is safe because it is a bind parameter, but sortColumn and direction are concatenated into the SQL text, and bind parameters can only carry values, not identifiers or keywords.

Then, if they want more

So an attacker can send something like a CASE expression with a subquery as the sort column. The query stays valid and the row order leaks data from other tables, which is blind injection.

The fix is an allow-list: the client sends a public sort name like date or total, I look it up in a fixed map to get the real column name, reject anything unknown with a 400, and accept only ASC or DESC by mapping the input to one of two constants.

Then everything concatenated into the SQL comes from my code. If we use Spring Data with Pageable, derived queries validate sort properties against the entity, and JPQL queries reject unknown expressions unless someone uses JpaSort.unsafe, but native queries still need the allow-list.

The same risk exists for table names from input, LIKE patterns where percent and underscore need escaping, IN lists built by joining strings, and JPQL built by concatenation. To keep it fixed, I would add tests with malicious sort values and a static analysis rule that flags string-built SQL.

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 "This Spring Data repository code uses parameters, yet a penetration test still finds SQL...": https://scrivio-interview-library.netlify.app/databases/database-security/c09c1f3593/