CVE-2026-65874: ORDER BY strikes again!
Instead of writing just another “Look, we found this” blog post, I decided to talk a bit more about the tricky ORDER BY clause, and why it is so hard to defend against injection attacks targeting it.
The short version is that the standard advice for SQL injection has a blind spot, and it comes down to the order in which a database reads your query. The long version takes us through lexers, parsers, state machines and a research project from the 1970s. Grab a coffee, and let’s dive in!
The problem
CVE-2026-65874 is an SQL injection in Apache Fineract 1.15.0 and earlier, fixed in 1.16.0. Fineract is an open-source core banking platform. Three of its read endpoints let the caller choose how results are sorted, and pasted that choice straight into the SQL query.
The same vulnerability was found independently and was responsibly disclosed by Abdullah Kareem. Lateran received reporting credit, and Abdullah received finder credit in the advisory.
One of them reads datatables. A datatable is a table that an administrator adds to hold extra fields for a client, loan or other record, and the endpoint returns the rows that belong to one parent record. It accepts an order query parameter, and this is how the query was built.
String sql = "select * from " + sqlGenerator.escape(dataTableName) + " where " + getFKField(entityTable) + " = ?";
...
if (StringUtils.isNotBlank(order)) {
columnValidator.validateSqlInjection(sql, order);
sql = sql + " order by " + order;
}The caller is expected to send a column name such as ?order=created_at, which produces order by created_at. SQL does not require a column name after ORDER BY, though. It accepts any expression, including a subquery. A caller who sends ?order=(SELECT 1 FROM pg_sleep(3)) gets the following query, and the response arrives three seconds late.
select * from "dt_notes" where client_id = ? order by (SELECT 1 FROM pg_sleep(3))The response body is the same either way, so the attacker cannot see the result of their subquery directly. What they can see is time. If the delay depends on a condition, each request answers one yes or no question about the data. This query sleeps for two seconds only if the first letter of the first user’s username is m.
SELECT id, name FROM accounts
ORDER BY (SELECT 1 FROM pg_sleep(
CASE WHEN (SELECT substr(username, 1, 1) FROM users WHERE id = 1) = 'm'
THEN 2 ELSE 0 END));An attacker who repeats this for each letter and each position can read any value the database user can read, one character at a time. It is slow, but a script does not get bored. This is called blind SQL injection. In Fineract the only permission needed was read access to one datatable, or to centres for the Center endpoint.
Fineract did try to stop this. validateSqlInjection checked the input against a list of suspicious patterns, and looked for column names next to comparison operators such as = and <. A subquery without a comparison operator, or one that used an operator not on the list, passed.
The solution
Parameterisation you might cry!
The usual fix for SQL injection is a parameterised query, also called a prepared statement. The SQL text holds a placeholder, and the value is sent to the database separately.
// Vulnerable: the name becomes part of the SQL text.
String sql = "select id, name from accounts where name = '" + name + "'";
// Parameterised: the SQL text is fixed and the name is sent as a value.
PreparedStatement ps = conn.prepareStatement("select id, name from accounts where name = ?");
ps.setString(1, name);In the first form, a name of ' OR '1'='1 closes the string early and adds a condition that is always true. In the second form, the database compares the name column with the text ' OR '1'='1, finds no match and returns nothing.
The query in the Fineract listing already does this for the parent ID, which is the ? after where. So why not do the same for the sort column? Surely that is a one-line fix.
A curiosity
Binding the sort column the same way looks like it should work.
PreparedStatement ps = conn.prepareStatement("select id, name from accounts order by ?");
ps.setString(1, "name");It runs without an error, but the rows come back unsorted.
Pause here, and think. Why might that be?
The PostgreSQL JDBC driver sends each ? to the server as a numbered placeholder ($1, $2 and so on), and the same thing can be done by hand in psql with PREPARE and EXECUTE. The listing below compares three ways of naming the sort column.
SELECT id, name FROM accounts ORDER BY name;
id | name
----+--------
2 | Adam
3 | Mpho
1 | Thandi
SELECT id, name FROM accounts ORDER BY 'name';
ERROR: non-integer constant in ORDER BY
PREPARE sorted(text) AS SELECT id, name FROM accounts ORDER BY $1;
EXECUTE sorted('name');
id | name
----+--------
1 | Thandi
2 | Adam
3 | MphoWriting the column name works. Writing it in quotes is an error. Sending it as a parameter is accepted and ignored, and the rows come back in the order they were inserted. The three versions differ by a few characters, yet the database treats them in three different ways.
To see why, we need to follow a query from the moment it arrives as text to the moment rows come back. It is a short trip through some of the oldest ideas in computer science, and it explains a lot more than this one bug.
Parsers
A database cannot run SQL text directly, in the same way that a CPU cannot run source code. The text is first turned into a data structure, a tree that says which tables to read, which columns to return and what to sort by. Turning text into that tree is called parsing.
Most backend developers parse text every day without thinking about it. JSON.parse('{"ids": [1, 2]}') takes a string and returns an object with an array inside it. A JSON parser has to notice that { starts an object, that "ids" is a key, that [ starts an array, and that the array ends before the object does. An SQL parser does the same job for a much larger language.
A database runs every query through the same five stages.
- The lexer splits the text into words, called tokens.
- The parser checks that the tokens form a valid statement, and builds a tree from them.
- Analysis looks up every name in the tree and replaces it with the real table or column.
- The planner decides how to run the query, such as which index to use and whether a sort is needed.
- The executor runs the plan and produces rows.
If you want the punchline now, it is already in the diagram. The first three stages decide what the query means. Parameter values only arrive at the fourth. The rest of this post explains how each stage works, and why that order cannot change.
State machines
Parsing usually happens in two steps, a lexer followed by a parser. Each one is a state machine (more precisely an automaton, or, to be even nerdier, a finite or pushdown automaton), a program that is always in one of a fixed set of states and moves to another state based on what it reads next. Writing these state machines by hand is slow and error-prone, so most language implementations generate them from a description of the language. PostgreSQL generates its lexer with Flex and its parser with Bison, two standard tools that also show up in compilers and interpreters.
If the term is unfamiliar, the idea is not. An order in an online shop is usually modelled as a state machine. It starts as pending, moves to paid when payment succeeds, then to shipped and delivered. Some moves are allowed and others are not. A pending order cannot become delivered without passing through the states in between, and code that tries is rejected.
A finite-state machine works the same way, except that the events are characters or tokens instead of payments and parcels. It has a start state, a set of states, and a table that says, for each state and each possible input, which state comes next. Some states are marked as accepting, which means the input read so far is complete and valid. If the machine reads an input for which its table has no entry, the input is invalid.
The important property of a finite-state machine is that its current state is all it remembers. It does not keep a list of what it has read. Remember that, because it comes back to bite when brackets show up.
Step 1. The lexer
The lexer reads the text one character at a time and groups the characters into words, called tokens. This is called lexical analysis. A lexer generator such as Flex takes a list of regular expressions, one for each kind of token, and compiles them into a deterministic finite automaton. This is a state machine that moves from state to state as it reads each character and emits a token when a word ends.
To show the process, I wrote a small lexer for a subset of SQL. These are its rules.
[ \t\n]+ ; /* skip spaces */
select return SELECT;
from return FROM;
order return ORDER;
by return BY;
\$[0-9]+ return PARAM; /* $1, $2, ... */
'[^']*' return SCONST; /* 'a string' */
[a-z_][a-z0-9_]* return IDENT; /* a name */Each line is a regular expression and the token it produces. Flex combines all of them into one state machine. The diagram shows the part of that machine that handles names, parameters and strings.
When the lexer reads $1, the $ moves it into a state where only digits can follow, the 1 keeps it there, and the space after it ends the word. The rule that matched was the parameter rule, so the lexer emits a PARAM token. When it reads name, the identifier rule matches and it emits IDENT. When it reads 'name', the opening quote leads to the string rule, and it emits SCONST. The word is the same in all three cases. The surrounding context decides which token comes out.
The string path is worth a second look. After the opening quote, the lexer is in a state that accepts any character except a quote. A space, a comma or the word SELECT is just more text in the string. Only another quote moves the lexer out of that state. Hold on to that idea, because it is the whole of classic SQL injection.
Keywords and names
The machine in the diagram treats order and orders the same way, as a sequence of letters. Flex resolves this with two rules.
- Longest match. The lexer keeps reading as long as the characters could still be part of a token, and uses the longest one it can make.
- First rule wins. If two rules match the same length of text, the one listed first in the rules file is used.
A small program built from the same rules, extended to print each token, shows both rules at work.
IDENT(orders) IDENT(ordering) ORDERorders is longer than order, so the identifier rule wins on length. order on its own matches both the order rule and the identifier rule at the same length, and the order rule is listed first, so it becomes the keyword. PostgreSQL’s real lexer does it slightly differently. It matches every word with an identifier rule and then looks the word up in a list of keywords. The outcome is the same.
The token stream
The lexer turns SELECT name FROM accounts ORDER BY ? into these tokens.
tokens[0]=SELECT
tokens[1]=IDENT(name)
tokens[2]=FROM
tokens[3]=IDENT(accounts)
tokens[4]=ORDER
tokens[5]=BY
tokens[6]=PARAMname is an identifier, 'name' in quotes would be a string constant, and ? (written $1 in PostgreSQL) is a parameter. The lexer does not know what any of these mean yet. That’s where the parser comes in.
Where injection actually happens
Here is the part that every classic SQL injection comes down to. Take the vulnerable query from the solution section, "... where name = '" + name + "'", and run two values through the toy lexer, extended with WHERE, OR and =.
name = Adam
SELECT IDENT(id) FROM IDENT(accounts) WHERE IDENT(name) '=' SCONST('Adam')
name = ' OR '1'='1
SELECT IDENT(id) FROM IDENT(accounts) WHERE IDENT(name) '=' SCONST('') OR SCONST('1') '=' SCONST('1')With Adam, the user’s text sits between two quotes and becomes one string token. With ' OR '1'='1, the user’s first quote ends the string early. The lexer drops back to its start state, where OR is a keyword and = is an operator. The user’s text has become five tokens, and three of them are SQL.
This is why the traditional defence against SQL injection was escaping. Escaping a value doubles every quote inside it, so ' becomes '', which the lexer reads as a quote character inside the string and not as the end of it. The lexer never leaves the string state, and the whole value stays one token.
Now look at the Fineract query again.
select * from "dt_notes" where client_id = ? order by (SELECT 1 FROM pg_sleep(3))There are no quotes around the user’s value. It is pasted in where the lexer is already in its start state, ready to read keywords, names and brackets. The attacker does not need to break out of anything, so escaping quotes does nothing. The only thing that would help is for the value never to reach the lexer at all, which is exactly what parameters do. So why can a parameter not hold a column name? For that, we need the parser.
Step 2. The parser
The parser takes the tokens and checks them against the grammar of SQL. A grammar is a set of rules that say which sequences of tokens make a valid statement. A parser generator such as GNU Bison turns a grammar into a look-ahead, left-to-right, rightmost derivation parser (LALR(1)). This is another state machine, larger than the lexer’s. PostgreSQL 18.7’s grammar has 3 434 rules and compiles to 6 502 states for context.
Why the lexer is not enough
If the lexer is a state machine and the parser is a state machine, why not use one machine for everything? The answer is brackets. Yes, really.
SQL lets expressions nest. A sort key can be (a + b), or ((a + b) * c), or a subquery that contains its own brackets and its own ORDER BY. To check that every ) matches an earlier (, a machine has to know how many brackets are open. It has to count.
A finite-state machine can only remember its current state, and it has a fixed number of states. A machine with ten states could track up to ten open brackets, and the eleventh would break it. No finite number of states can handle every depth, and SQL puts no limit on depth.
The fix is to give the machine a stack. Every ( pushes something, and every ) pops it. If a ) arrives and the stack is empty, the brackets do not match. A state machine with a stack is called a pushdown automaton, and an LALR parser is one.
This difference has a practical consequence. Regular expressions, in the textbook sense, are equivalent to finite-state machines, and Java’s regular expressions cannot match nested brackets of any depth either. They are the right tool for recognising words, which is why lexers are built from them. They cannot recognise the structure of SQL, because SQL needs a stack (also the reason why regex can’t be used to properly match all sorts of things). Fineract’s validateSqlInjection tried to decide whether a piece of SQL was safe by matching it against regular expressions. Whatever patterns it used, it was trying to answer a question about structure with a tool that cannot see structure. That is a fight a validator cannot win.
The toy grammar
This is the grammar for the toy SQL.
query: SELECT IDENT FROM IDENT sort_clause ;
sort_clause: %empty | ORDER BY expr ;
expr: IDENT | PARAM | SCONST ;Each rule has a name on the left and what it is made of on the right. | separates alternatives, and %empty means nothing at all. Read as plain language, the rules say the following.
- A query is
SELECT, a name (IDENT),FROM, a name (IDENT), and a sort clause. - A sort clause is either nothing, or
ORDER BYfollowed by an expression. - An expression is a name, a parameter or a string.
The names on the left, such as query and expr, are called nonterminals, because they can be broken down further. The token names, such as SELECT and IDENT, are called terminals, because they cannot. A real SQL grammar has the same shape with far more rules. In PostgreSQL’s grammar, the rule for one item of an ORDER BY clause starts with a_expr, which is the rule for any expression at all, including arithmetic, function calls and subqueries. That is why the Fineract payload is valid SQL.
Shift and reduce
An LALR parser keeps a stack of states and looks at one token at a time. For each token it does one of two things, which is why it is also called a shift-reduce parser.
- Shift. Push the token onto the stack and move to a new state.
- Reduce. When the top of the stack matches the right-hand side of a grammar rule, replace those items with the rule’s name.
An analogy helps. Imagine reading the expression (1 + 2) * 3 aloud and writing down only what you need. You read (, 1, + and 2 and keep them in mind. When you reach ), you know that 1 + 2 is complete, so you replace those four items with one item, “a sum”. Keeping items in mind is shifting. Replacing a finished group with its name is reducing. The parser does the same thing, with grammar rules telling it which groups count as finished.
The parser’s state machine
Bison compiles the toy grammar into 14 states. The diagram shows all of them.
The solid arrows are shifts, where the parser reads a token and moves on. The dashed arrows are reduces. Strictly, a reduce pops states off the stack and then moves from whichever state is uncovered, so the dashed arrows show the overall effect and not a single move.
Bison also writes a report of every state in the machine it built. This is the state the parser is in after it has read ORDER BY.
State 9
3 sort_clause: ORDER BY • expr
IDENT shift, and go to state 10
PARAM shift, and go to state 11
SCONST shift, and go to state 12The dot marks how far into the rule the parser is. It has seen ORDER BY and is waiting for an expression. In this state it accepts three kinds of token and moves to a different state for each one. Any other token is a syntax error.
State 9 is the fork in the road, where the three versions of the curiosity query part ways. Up to this point, the parser has done exactly the same work for all three. After this point, each one is on its own path, and the paths never meet again until the parser has decided what kind of thing sits in the sort clause.
Looking ahead
State 6 shows what the “(1)” in LALR(1) means. The parser has read SELECT name FROM accounts, and the next part of the query is a sort clause, which may be empty.
State 6
1 query: SELECT IDENT FROM IDENT • sort_clause
ORDER shift, and go to state 7
$default reduce using rule 2 (sort_clause)The parser cannot decide what to do in state 6 without peeking at the next token. If it is ORDER, it shifts and reads the sort clause. If it is anything else, it reduces an empty sort clause and moves on. That peek is the look-ahead. For SELECT name FROM accounts with no sort clause, the trace shows the empty reduce.
Entering state 6
Now at end of input.
Reducing stack by rule 2 (line 10):
-> $$ = nterm sort_clause ()
Entering state 8A full trace
Running the toy parser with tracing turned on shows every step for SELECT name FROM accounts ORDER BY $1.
| Step | Token | Action | Stack afterwards |
|---|---|---|---|
| 1 | SELECT | Shift, go to state 1 | 0 1 |
| 2 | IDENT | Shift, go to state 3 | 0 1 3 |
| 3 | FROM | Shift, go to state 5 | 0 1 3 5 |
| 4 | IDENT | Shift, go to state 6 | 0 1 3 5 6 |
| 5 | ORDER | Shift, go to state 7 | 0 1 3 5 6 7 |
| 6 | BY | Shift, go to state 9 | 0 1 3 5 6 7 9 |
| 7 | PARAM | Shift, go to state 11 | 0 1 3 5 6 7 9 11 |
| 8 | Reduce PARAM to expr | 0 1 3 5 6 7 9 13 | |
| 9 | Reduce ORDER BY expr to sort_clause | 0 1 3 5 6 8 | |
| 10 | Reduce the whole statement to query | 0 2 | |
| 11 | end of input | Accept | 0 2 4 |
Steps 1 to 7 read tokens and push them. From step 8 on, the parser recognises finished rules and folds them up, from the innermost outwards, until one query is left.
The stack in the table holds state numbers, which is what the parser stores. The diagram below shows the same stack with the symbol each state stands for, which is easier to follow.
For the other two versions of the query, the trace is identical except for one line. With ORDER BY name, step 7 reads IDENT and goes to state 10. With ORDER BY 'name', it reads SCONST and goes to state 12. The reduce steps that follow are the same.
A token the grammar does not allow stops the parse in its tracks. This is the trace for SELECT name FROM accounts ORDER BY BY.
Entering state 9
Next token is token BY ()
error: syntax errorState 9 has no entry for BY, so the parser stops and reports an error. A statement either fits the grammar or is rejected.
The parse tree
Each reduce step builds a node of the parse tree. The finished tree for this query looks like this.
query
├── SELECT
├── IDENT(name) the column to return
├── FROM
├── IDENT(accounts) the table to read
└── sort_clause
├── ORDER
├── BY
└── expr
└── PARAM(1) a value that will arrive laterThe kind of node at the bottom right depends on which token was shifted in state 9. An IDENT there becomes a column reference, a string becomes a constant, and a PARAM becomes a placeholder node that holds the parameter’s number and nothing else.
The tree is the parser’s whole output. Everything after this point works on the tree and never looks at the SQL text again. That one fact is most of the answer to the curiosity.
Step 3. Analysis
The tree still holds plain names. The next step, called analysis, looks each name up in the database’s catalogue, the internal tables that describe every table and column. It checks that accounts exists, finds its name column and records the column’s type.
The parser and analysis catch different mistakes, and PostgreSQL’s error messages show which stage found the problem.
SELECT id, name FROM accounts ORDER BY (1
ERROR: syntax error at end of input
SELECT id, name FROM accounts ORDER BY nme;
ERROR: column "nme" does not exist
HINT: Perhaps you meant to reference the column "accounts.name".The first query is missing a bracket, so the parser rejects it before any name is looked up. The second is valid SQL with a misspelt column. The parser accepts it, and analysis rejects it when the catalogue has no column called nme.
Analysis also explains the error in the curiosity section. In ORDER BY, SQL treats a whole number as a column position, so ORDER BY 2 sorts by the second column in the select list.
SELECT id, name FROM accounts ORDER BY 2;
id | name
----+--------
2 | Adam
3 | Mpho
1 | ThandiPostgreSQL rejects any other constant there, which is why ORDER BY 'name' fails. A string in that position is almost certainly a mistake, so the database refuses it.
A placeholder is neither a name nor a constant. Analysis treats it as a value whose type is known (text in this case) and whose content is not known yet. The type comes from the application. PREPARE sorted(text) declares it, and the JDBC driver sends a type for each value set with setString or setInt. When no type is given, PostgreSQL works out a type from how the parameter is used.
The result of analysis is called the query tree. It is the parse tree with every name resolved and every type known. For our query it says “read accounts, return id and name, sort by the value of parameter 1”. It does not say “sort by a column chosen later”, because the tree has no node for that. There is simply nowhere to put one.
Step 4. Planning
The planner turns the query tree into a plan. For a simple query against one table there is not much to decide, but the planner still chooses between reading the whole table and using an index, and whether a sort step is needed. For a query that joins several tables, it also chooses the order of the joins and how to perform each one.
The plan depends on the structure of the query. An index on name helps ORDER BY name and is useless for ORDER BY id. A plan made for one sort column cannot be reused for another. Keep that in mind.
A bit of history
Here is a shocker: parameters were not invented to stop SQL injection.
They were invented to avoid parsing the same query over and over.
IBM’s System R, the research project that produced SQL, compiled the SQL inside an application program before the program ran. In “A History and Evaluation of System R” (Communications of the ACM, October 1981), the team describes the benefit.
All the overhead of parsing, validity checking, and access path selection is removed from the path of the executing program and placed in a separate preprocessor step which need not be repeated.
Parsing, validity checking and access path selection are the parser, the analysis step and the planner from the previous section. On the hardware of the 1970s, doing them for every transaction was expensive, so System R did them once, ahead of time.
The compiled routine, called an access module, already knew which tables, columns and indexes it would use. System R recorded those dependencies in its catalogue, and the paper notes that if an index the module relied on was dropped, the module had to be marked invalid and compiled again. The program could pass values into a compiled statement, but the structure of the statement was fixed when it was compiled.
Later interfaces kept the same model. ODBC 1.0, released in September 1992, has SQLPrepare, which takes SQL with ? markers, and SQLExecute, which runs the prepared statement again with new values. JDBC, released with JDK 1.1 in February 1997, carried this into Java as PreparedStatement. In each case the point was to parse and plan once, then run many times.
SQL injection came later. A Phrack article from December 1998 described attacks on web applications that built SQL queries from user input. Parameters turned out to be the right defence, because a value sent separately never passes through the parser. That protection is a side effect of a design built for speed, and it covers only what the original design allowed to vary, which is values. The best-known defence against SQL injection is, in a sense, a happy accident.
Parameterisation
Fast forward to today. A prepared statement still goes through the same three steps. PostgreSQL’s extended query protocol sends each one as a separate message over the connection, and ODBC and JDBC follow the same order.
- Parse. The application sends the SQL text with
$1in it, and optionally the type of each parameter. The database runs the lexer, the parser and analysis, and keeps the resulting tree under a name. - Bind. The application names the prepared statement and sends the value
name. The database converts it to the parameter’s type, stores it with the statement, and chooses a plan. - Execute. The database runs the plan with that value and returns the rows.
The application usually sends all four messages at once, and the database answers them in order. Sync marks the end of the batch, and ReadyForQuery says the database is waiting for the next one.
PostgreSQL can log each message as it handles it. Since version 16, psql can send a query this way with its \bind command, which makes the steps easy to see. With log_min_duration_statement set to 0, the server log shows the three steps for the curiosity query.
LOG: duration: 0.232 ms parse <unnamed>: SELECT id, name FROM accounts ORDER BY $1
LOG: duration: 0.123 ms bind <unnamed>: SELECT id, name FROM accounts ORDER BY $1
DETAIL: Parameters: $1 = 'name'
LOG: duration: 0.009 ms execute <unnamed>: SELECT id, name FROM accounts ORDER BY $1
DETAIL: Parameters: $1 = 'name'Look at where name first appears. It is not in the parse line. By the time the database sees the value, the parse step is over and done. The same happens with the injection value from earlier, which returns no rows.
LOG: duration: 0.077 ms parse <unnamed>: SELECT id, name FROM accounts WHERE name = $1
LOG: duration: 0.024 ms bind <unnamed>: SELECT id, name FROM accounts WHERE name = $1
DETAIL: Parameters: $1 = 'Adam'' OR ''1''=''1'The log escapes the value for display by doubling the quotes in it. The database received the text Adam' OR '1'='1 and compared it with the name column, character for character.
Two paths for the same input
The difference between concatenation and parameters comes down to where the user’s input enters the pipeline.
With concatenation, the input becomes part of the SQL text and passes through every stage, including the lexer, where a quote or a bracket can change the token stream. With a parameter, the input enters after the lexer, the parser and analysis have finished. Those stages are the only parts of the database that turn text into structure, and the input never meets them.
This is what makes parameters safe. A value of ' OR '1'='1 cannot become SQL, because nothing reads it as SQL. By the time it arrives, the parser has already read the placeholder, taken the PARAM path out of state 9, and built a tree in which that slot holds a value.
Why a parameter cannot name a column
It is also the limitation. A column name is part of the query’s structure, and the structure is decided at the Parse step. A value that arrives afterwards can fill a slot in the tree, but it cannot change what kind of node the slot is.
So why not change the rules? Imagine a database that did allow it. When the Bind message arrived with name, it would have to go back to the tree, replace the parameter node with a column reference, and run analysis again to find the column and its type. That is a smaller version of the following steps.
- Put the value into the SQL text.
- Run the lexer and the parser again.
- Run analysis again.
Step 1 is the string concatenation that parameters exist to avoid. If the value is read as SQL, the value can be SQL. A database could restrict the value to a single identifier token, but then it has to lex the value to check it, and the value is no longer kept apart from the lexer. Every new path into the lexer is another place for injection to happen.
It would also undo the reason prepared statements exist. PostgreSQL can reuse a plan across executions of a prepared statement. By default it plans the first five executions with the actual values, and after that it may switch to one generic plan that ignores the values. That only works because no value can change which tables and columns the query uses. A statement whose sort column changed between runs would need a new tree and a new plan every time, which is the cost System R was built to avoid.
What drivers do
Some drivers do not use server-side prepared statements by default and fill in the placeholders themselves before sending the query. MySQL Connector/J is one. These drivers escape the value and wrap it in quotes, so ORDER BY ? with the value name becomes ORDER BY 'name', a string constant. The result is the same. The value is never treated as a column name.
These drivers have to escape correctly, because the value does pass through the database’s lexer. The escaping keeps the lexer inside the string state for the whole value, as described in the lexer section. For a value that is meant to be data, that is enough.
What the database does with ORDER BY $1
So ORDER BY $1 with the value name means “sort every row by the text name”. Every row has the same sort key, so the order does not change. PostgreSQL notices this and leaves the sort out of the plan.
EXPLAIN (COSTS OFF) SELECT id, name FROM accounts ORDER BY name;
Sort
Sort Key: name
-> Seq Scan on accounts
EXPLAIN (COSTS OFF, GENERIC_PLAN) SELECT id, name FROM accounts ORDER BY $1::text;
Seq Scan on accountsThe first plan reads the table and then sorts it by name. The second only reads the table. There is no error to tell the developer that the sort did nothing, which is why this mistake can survive until someone notices the order on screen.
And there is the answer to the curiosity. The three queries differ in one token. The lexer gives each a different token, the parser takes a different path out of state 9, and analysis turns each into a different node. A column reference sorts. A string constant is an error. A parameter is a value, and sorting by one value does nothing.
The same applies to anything else that shapes a query rather than supplying data to it. Table names, column names, ASC and DESC, and SQL keywords cannot be parameters. ORDER BY is where this comes up most, because sorting is the most common feature that asks the caller for a column name.
Identifier helpers in client libraries
Some client libraries offer what looks like a parameter for identifiers. Python’s psycopg has sql.Identifier, PostgreSQL’s format function has %I for building dynamic SQL in PL/pgSQL, and JDBC has enquoteIdentifier on Statement since Java 9. None of these send the name separately. They quote the name as an identifier and put it into the SQL text, which then goes through the lexer and parser as usual.
That is safe for the same reason escaping a string is safe. An identifier in double quotes is another lexer state, and only a closing double quote ends it. Doubling any double quote inside the name keeps the lexer in that state, so the name stays one token.
Quoting does not decide which columns a caller may sort by, though. A caller who can sort by any column can sort by one they cannot see. Sorting a user list by a password hash column and watching where their own account lands tells them something about other users’ hashes. Quoting stops injection. Deciding which columns are allowed is a separate job, and it belongs to the application.
Conclusion
So what should you actually do? Since the database cannot take the sort column as a parameter, the application has to build that part of the query itself. The rule is that the SQL text contains only fragments written by the developer, and input from the caller only chooses between them.
Columns known in advance
When the sortable columns are known when the code is written, map the names the API accepts to fixed column names, and treat the direction as one of two values.
private static final Map<String, String> SORT_COLUMNS = Map.of(
"name", "c.display_name",
"opened", "c.activation_date",
"office", "o.name");
String column = SORT_COLUMNS.get(orderBy);
if (column == null) {
throw new InvalidSortException(orderBy);
}
String direction = "desc".equalsIgnoreCase(sortOrder) ? "DESC" : "ASC";
sql = sql + " order by " + column + " " + direction;The caller’s input is only ever used as a key to look up a string the developer wrote. An unknown key is rejected, so nothing the caller sends reaches the SQL text. This also lets the API use names that differ from the database’s column names, which keeps the schema private, and it limits sorting to columns the caller is meant to see.
Columns known only at run time
Fineract’s datatables are created by administrators, so the code cannot list their columns in advance. In that case, check the requested name against the table’s real columns, and then quote it as an identifier.
Quoting an identifier is different from quoting a string. In PostgreSQL an identifier is quoted with double quotes, and a double quote inside the name is doubled. PostgreSQL’s quote_ident function shows the rules.
SELECT quote_ident('name'), quote_ident('Birth Date'), quote_ident('a"b');
quote_ident | quote_ident | quote_ident
-------------+--------------+-------------
name | "Birth Date" | "a""b"MySQL and MariaDB use backticks instead of double quotes. The check against the real columns comes first, and the quoting makes sure that a column name with a space or a quote in it cannot break the query.
This is what the Fineract fix in 1.16.0 does for datatables. It reads the datatable’s column list, rejects any name that is not on it, accepts only ASC or DESC after the name, and escapes the name for the database in use. The Center fix checks orderBy against a strict pattern and accepts only ASC or DESC for sortOrder.
What does not work
Filtering the input for dangerous SQL does not work. ORDER BY accepts any expression in the grammar, and PostgreSQL’s grammar has thousands of rules. A filter built from regular expressions cannot even match brackets, let alone recognise every way to write a harmful expression. The attacker only needs one the filter missed, and the one in Fineract missed a subquery without a comparison operator.
Escaping the value does not work either. Escaping protects a value inside quotes, and a sort column is not inside quotes.
Fineract deployments on 1.15.0 or earlier should upgrade to 1.16.0 or later. The Apache advisory recommends 1.16.1.
References
- Apache Fineract advisory for CVE-2026-65874
- CVE-2026-65874 record
- apache/fineract#6230 and apache/fineract#6277, the fixes
- D. D. Chamberlin et al., A History and Evaluation of System R, Communications of the ACM 24(10), October 1981
- rain.forest.puppy, NT Web Technology Vulnerabilities, Phrack 54, December 1998
- PostgreSQL extended query protocol
- PostgreSQL
PREPARE, including when plans are reused