Quick revision
The short answer
The serious issue is SQL injection: formatted() is plain string formatting, so inserting user values into the SQL lets a crafted value change the statement. Text blocks are good for the static SQL text, but values must go in as bind parameters through PreparedStatement or named parameters, with identifiers such as sort columns chosen from an allowlist. I would also point out that formatted values make every statement text unique, which defeats plan and statement caches, that text blocks keep newlines that affect logs, and that very long SQL may belong in versioned resource files where DBAs can review it.
What to remember
In this answer, we saw that formatted() on a SQL text block is plain string formatting, so user values inserted into it allow SQL injection, as a crafted name that removed the tenant filter showed. We kept the text block for the static SQL and moved values to bind parameters with PreparedStatement or named parameters, used allowlists for identifiers and sort orders, and remembered that a literal % must be doubled in formatted(). We also saw that inlined values defeat statement and plan caches, that multi-line SQL needs care in logs, and that long queries may belong in versioned resource files.
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.
The serious issue is SQL injection: formatted() is plain string formatting, so inserting user values into the SQL lets a crafted value change the statement. Text blocks are good for the static SQL text, but values must go in as bind parameters through PreparedStatement or named parameters, with identifiers such as sort columns chosen from an allowlist. I would also point out that formatted values make every statement text unique, which defeats plan and statement caches, that text blocks keep newlines that affect logs, and that very long SQL may belong in versioned resource files where DBAs can review it.
Why this question is asked
Text blocks made long SQL in Java code pleasant to read, and formatted() makes it tempting to drop values straight in. The combination looks modern and tidy, which is exactly why it passes casual review. Interviewers ask this scenario to see whether we spot that the new syntax has not changed the old rules about building SQL from strings. In this answer, we will reproduce the injection, fix it with bind parameters, deal with the parts of SQL that cannot be parameters, look at the effect on caches and logs, and discuss where long SQL should live.
1A Quick Recap: What formatted() Does
String.formatted(args) is the instance-method form of String.format, added in Java 15 together with text blocks. It replaces %s, %d and other specifiers with the arguments' text. It knows nothing about SQL: it does not quote, escape or check anything. So the database receives one finished string, and it cannot tell which parts we wrote and which came from the user.
A text block is just a String literal. Writing the SQL as a text block changes how readable the source is, not how safe the query is.
2Reproducing the Injection
Here is the pattern from the review, with a search by customer name.
The value closes the quote, adds a condition that is always true and comments out the rest, including the tenant filter. In a multi-tenant system this leaks every tenant's data, and with stacked statements or other techniques, it can be worse. Escaping quotes by hand is not a fix; there are too many edge cases across databases and encodings.
3Fix: Keep the Text Block, Bind the Values
The fix keeps everything good about the text block, the readable static SQL, and moves the values out of the text into bind parameters. The database receives the SQL with placeholders and the values separately, so a value can never become SQL syntax.
6 messages in order. Play them, or step through them one at a time.
The statement text is identical for every user, so it can also be cached.
With the malicious name, the query now looks for a customer literally named x' OR '1'='1' -- and finds none. NamedParameterJdbcTemplate, JPA's setParameter and jOOQ all offer the same protection. The rule for review is simple: formatted() and + may build SQL only from constant text, never from values.
4What Cannot Be a Parameter
Bind parameters work for values, not for parts of the SQL structure. Table names, column names, sort directions and ORDER BY columns cannot be bound, which is often why people reach for formatted() in the first place. For those, the safe approach is an allowlist: map the user's choice to one of a fixed set of SQL fragments that we wrote.
Notice that formatted() is acceptable here precisely because the inserted text is one of our own constants. A second, smaller trap: in formatted() and String.format, a literal % must be written %%, so LIKE patterns written into the text such as '%abc%' break or fail; bind the pattern as a parameter instead, for example ps.setString(1, "%" + term + "%").
5Caches, Logs and Where Long SQL Should Live
Inlined values have a performance cost even without an attacker. Databases and drivers cache statements and execution plans keyed by the statement text. If every call produces different text because the values are part of it, nothing is reused: each query is parsed and planned again, and the cache fills with one-off entries. Bind parameters keep the text constant, so a statement is parsed once and its plan can be reused.
Text blocks also keep their newlines, which is fine for the database but means the SQL appears in logs, error messages and monitoring as many lines. Multi-line log entries can be split by log shippers, and some tools group queries by their exact text including whitespace, so we should log the statement name or a normalised form rather than the raw block.
Finally, very long SQL, such as a 200-line reporting query, may be better kept in a versioned .sql resource file, loaded at startup, or managed in a migration or query library. DBAs can then review it with SQL tooling, syntax highlighting and explain plans, and the change history of the query is separate from Java refactorings. Short and medium queries next to the code that uses them are fine as text blocks.
6Follow-up questions
Is it enough to validate the input with a regex instead of binding?
No. Validation is a useful extra layer, but it is easy to get wrong, it breaks when requirements change, and it has to be repeated for every query. Binding makes injection impossible by construction, so validation should only be defence in depth.
What about IN lists with a variable number of values?
Generate the right number of placeholders from the list size, such as String.join(",", Collections.nCopies(ids.size(), "?")), and bind each value, or use named parameters with a collection, which NamedParameterJdbcTemplate and JPA expand for us. On PostgreSQL, binding one array with = ANY(?) keeps the statement text constant.
Should we ban formatted() on SQL entirely?
A static analysis rule that flags formatted() or + producing an argument to execute or prepareStatement is a good default, with an explicit suppression for the allowlist case. That makes the safe pattern the easy one and leaves a visible trail for the rare exception.
7Conclusion
In this answer, we saw that formatted() on a SQL text block is plain string formatting, so user values inserted into it allow SQL injection, as a crafted name that removed the tenant filter showed. We kept the text block for the static SQL and moved values to bind parameters with PreparedStatement or named parameters, used allowlists for identifiers and sort orders, and remembered that a literal % must be doubled in formatted(). We also saw that inlined values defeat statement and plan caches, that multi-line SQL needs care in logs, and that long queries may belong in versioned resource files.
Open with
The first thing I would raise is SQL injection. formatted is just String.format: it pastes the user's value into the SQL text without any escaping, so a name like x quote OR one equals one dash dash closes the quote, adds an always-true condition and comments out the rest, which in their query would remove the tenant filter.
Then, if they want more
The text block itself is fine and I would keep it for the static SQL, but the values have to be bind parameters, question marks with a PreparedStatement, or named parameters with NamedParameterJdbcTemplate or the newer JdbcClient. Then the database gets values as data, and they can never become SQL.
For the parts that cannot be parameters, like a sort column or direction, I would map the request value to one of our own constant fragments through an allowlist, and only then insert it. I would also mention the side effects.
Inlining values makes every statement text unique, so the driver's statement cache and the database's plan cache cannot reuse anything and every call is parsed and planned again. A literal percent sign in formatted has to be doubled, which breaks LIKE patterns, another reason to bind them.
Text blocks keep their newlines, which is fine for the database but makes multi-line log entries, so I would log a query name or normalised text. And for the really long reporting queries, I would ask whether they belong in versioned SQL resource files where DBAs can review them with their own tools.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 15
- 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
- The Java Language Specification, Java SE 21, Java SE 21 API 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 team embeds large SQL statements as text blocks and inserts user values with...": https://scrivio-interview-library.netlify.app/java/strings/df9d00c5f8/