=== modified file 'src/com/goldencode/p2j/persist/FQLExpression.java'
--- old/src/com/goldencode/p2j/persist/FQLExpression.java
+++ new/src/com/goldencode/p2j/persist/FQLExpression.java
@@ -2,7 +2,7 @@
 ** Module   : FQLExpression.java
 ** Abstract : FQL expression with substitution parameters.
 **
-** Copyright (c) 2014-2024, Golden Code Development Corporation.
+** Copyright (c) 2014-2026, Golden Code Development Corporation.
 **
 ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
 ** 001 SVL 20140210 Created initial version.
@@ -13,6 +13,7 @@
 ** 005 OM  20231115 Added multiplexed property to mark the object as already containing the multiplex and
 **                  this constraint into outer FQL is not needed and even illegal.
 ** 006 CA  20240812 Performance improvement - reduce the number of StringBuilder instances.
+** 007 SP  20261110 Added finalLength() and appendFinalExpression(), which writes into a given StringBuilder.
 */
 
 /*
@@ -253,24 +254,79 @@
     */
    public String toFinalExpression(boolean jpaStyle)
    {
-      writeLastPart();
+      StringBuilder sb = new StringBuilder(finalLength(jpaStyle));
+      appendFinalExpression(sb, jpaStyle);
+      return sb.toString();
+   }
+
+   /**
+    * Appends the final form of the FQL expression, as {@link #toFinalExpression(boolean)} returns it, to
+    * the given builder, after what it already holds.
+    *
+    * @param   sb
+    *          The builder to append to.
+    * @param   jpaStyle
+    *          <code>true</code> to emit JPA-style positional parameter placeholders;
+    *          <code>false</code> to emit simple placeholders.
+    */
+   public void appendFinalExpression(StringBuilder sb, boolean jpaStyle)
+   {
+      sb.ensureCapacity(sb.length() + finalLength(jpaStyle));
       int index = 0;
       int len = parts.size();
-      StringBuilder sb = new StringBuilder();
       for (int i = 0; i < len; i++)
       {
          sb.append(parts.get(i));
          boolean last = (i == len - 1);
          if (!last || endsWithSubst)
          {
-            sb.append("?");
+            sb.append('?');
             if (jpaStyle)
             {
                sb.append(index++);
             }
          }
       }
-      return sb.toString();
+   }
+
+   /**
+    * Returns the length of the final form of the FQL expression, as {@link #toFinalExpression(boolean)}
+    * returns it.
+    *
+    * @param   jpaStyle
+    *          <code>true</code> for JPA-style positional parameter placeholders;
+    *          <code>false</code> for simple placeholders.
+    *
+    * @return  The number of characters of the final form.
+    */
+   public int finalLength(boolean jpaStyle)
+   {
+      writeLastPart();
+      int len = parts.size();
+      int placeholders = (len == 0 ? 0 : (endsWithSubst ? len : len - 1));
+      int total = placeholders;
+      for (int i = 0; i < len; i++)
+      {
+         total += parts.get(i).length();
+      }
+
+      if (jpaStyle)
+      {
+         // decimal digits of the indexes 0 .. placeholders - 1: 1 digit below 10, 2 below 100, ...
+         int  done   = 0;
+         int  digits = 1;
+         long limit  = 10;
+         while (done < placeholders)
+         {
+            int upto = (int) Math.min(placeholders, limit);
+            total += (upto - done) * digits;
+            done = upto;
+            digits++;
+            limit *= 10;
+         }
+      }
+
+      return total;
    }
 
    /**
=== modified file 'src/com/goldencode/p2j/persist/PreselectQuery.java'
--- old/src/com/goldencode/p2j/persist/PreselectQuery.java
+++ new/src/com/goldencode/p2j/persist/PreselectQuery.java
@@ -759,6 +759,7 @@
 **                           isBetweenRows. A NO-WAIT lock conflict on current() reads NO-LOCK.
 ** 253 AL2 20241119          Adapt to the switch from dirty context to transactional changes manager.
 **     AL2 20260930          Restored the text of entry 219 and removed trailing whitespace.
+** 254 SP  20261110          Build the inverted FQL only when a backward scroll reads it; fewer FQL copies.
 */
 
 /*
@@ -933,8 +934,8 @@
    /** FQL query string to retrieve primary key ID arrays */
    private String fql = null;
 
-   /** Inverted FQL query string to retrieve primary key ID arrays. */
-   private String invertedFQL = null;
+   /** Text of the last assembled FQL statement, and its inverted form on demand. */
+   private AssembledFql assembled = null;
    
    /** Result set for this query */
    private Results results = null;
@@ -6548,46 +6549,6 @@
    }
    
    /**
-    * Generates the {@code order by} clause starting from the list of criteria, including the "order by"
-    * keyword. Uses the form:
-    * <pre>
-    *   order by {{dmo.property} {asc/desc}} [, ...]
-    * </pre>
-    * <p>
-    *
-    * @param   sortCriteria
-    *          The list of criteria to be added.
-    * @param   buf
-    *          The string builder to add the result.
-    * @param   invert
-    *          {@code true} only if the order by clause should be inverted. (e.g. 'desc' becomes 'asc'
-    *          and 'asc' becomes 'desc').
-    */
-   private void generateOrderBy(ArrayList<SortCriterion> sortCriteria, StringBuilder buf, boolean invert)
-   {
-      if (sortCriteria == null)
-      {
-         return; // quick out
-      }
-      
-      boolean orderBy = true;
-      for (int i = 0; i < sortCriteria.size(); i++)
-      {
-         SortCriterion criterion = sortCriteria.get(i);
-         if (orderBy)
-         {
-            buf.append(" order by ");
-            orderBy = false;
-         }
-         else
-         {
-            buf.append(", ");
-         }
-         buf.append(invert ? criterion.toSortExpression(true) : criterion.toString());
-      }
-   }
-   
-   /**
     * Assemble the {@code order by} clause for an FQL query.
     * <p>
     * Any text-based sort criteria are augmented with the necessary upper() and rtrim() functions.
@@ -8105,13 +8066,14 @@
    }
 
    /**
-    * Get the inverted FQL query.
+    * Get the inverted FQL query of the last assembled statement. The inverted text is built on the first
+    * {@code get()}, so a query which only scrolls forward never builds it.
     *
-    * @return  FQL query or {@code null} if the query has not yet been executed.
+    * @return  Supplier of the inverted FQL query or {@code null} if the query has not yet been executed.
     */
-   protected String getInvertedHQL()
+   protected Supplier<String> getInvertedHQL()
    {
-      return invertedFQL;
+      return assembled;
    }
    
    /**
@@ -8514,8 +8476,8 @@
       {
          assembleFQLImpl(buf);
       }
-      
-      return buf.toString().trim();
+
+      return assembled.text().trim();
    }
    
    /**
@@ -8608,6 +8570,62 @@
    }
 
    /**
+    * Generates the {@code order by} clause starting from the list of criteria, including the "order by"
+    * keyword. Uses the form:
+    * <pre>
+    *   order by {{dmo.property} {asc/desc}} [, ...]
+    * </pre>
+    * The caller sizes {@code buf}; {@link #orderByLength} gives the length appended.
+    *
+    * @param   sortCriteria
+    *          The list of criteria to be added.
+    * @param   buf
+    *          The string builder to add the result.
+    * @param   invert
+    *          {@code true} only if the order by clause should be inverted. (e.g. 'desc' becomes 'asc'
+    *          and 'asc' becomes 'desc').
+    */
+   private static void generateOrderBy(List<SortCriterion> sortCriteria, StringBuilder buf, boolean invert)
+   {
+      if (sortCriteria == null)
+      {
+         return; // quick out
+      }
+      
+      for (int i = 0; i < sortCriteria.size(); i++)
+      {
+         buf.append(i == 0 ? " order by " : ", ");
+         buf.append(sortCriteria.get(i).toSortExpression(invert));
+      }
+   }
+   
+   /**
+    * Get the number of characters {@link #generateOrderBy} appends for the given criteria.
+    *
+    * @param   sortCriteria
+    *          The list of criteria; can be {@code null}.
+    * @param   invert
+    *          {@code true} for the inverted order by clause.
+    *
+    * @return  The length of the order by clause, {@code 0} when there are no criteria.
+    */
+   private static int orderByLength(List<SortCriterion> sortCriteria, boolean invert)
+   {
+      if (sortCriteria == null || sortCriteria.isEmpty())
+      {
+         return 0;
+      }
+      
+      int len = " order by ".length() + 2 * (sortCriteria.size() - 1);
+      for (int i = 0; i < sortCriteria.size(); i++)
+      {
+         len += sortCriteria.get(i).toSortExpression(invert).length();
+      }
+      
+      return len;
+   }
+
+   /**
     * Keep one property of one buffer in both projection maps. A no-op for a buffer this query
     * carries no FIELDS/EXCEPT phrase for, such as the outer buffer of an OF join.
     *
@@ -8682,8 +8700,8 @@
     * the database query underlying this object. The FQL generated uses the
     * theta join style and includes a select clause, a from clause, an
     * optional where clause, and an order by clause (mandatory in all cases
-    * except a unique find). In addition, the inverted FQL will be computed
-    * for optimization purposes.
+    * except a unique find). The result, with what is needed to build the
+    * inverted FQL on demand, is stored in {@link #assembled}.
     *
     * @param   buf
     *          The buffer where to assemble the FQL.
@@ -8707,16 +8725,21 @@
       adjustProjection();
 
       assembleSelectClause(buf);
-      buf.append(fromAndWhere.toFinalExpression());
 
-      StringBuilder inverted = new StringBuilder(buf);
-      if (isOrderByRequired())
+      // reads the preprocessors built above; appending the from and where text has no side effects
+      boolean orderByRequired = isOrderByRequired();
+      buf.ensureCapacity(buf.length() +
+                         fromAndWhere.finalLength(true) +
+                         (orderByRequired ? orderByLength(sortCriteria, false) : 0));
+      fromAndWhere.appendFinalExpression(buf, true);
+
+      int orderByStart = buf.length();
+      if (orderByRequired)
       {
          generateOrderBy(sortCriteria, buf, false);
-         generateOrderBy(sortCriteria, inverted, true);
       }
 
-      invertedFQL = inverted.toString();
+      assembled = new AssembledFql(buf.toString(), orderByStart, orderByRequired ? sortCriteria : null);
    }
    
    /**
@@ -9102,5 +9125,80 @@
          // else cursor is -1 (before), 0 (on single record), 1 (after)
       }
    }
+
+   /**
+    * Text of one assembled FQL statement, and its inverted form, which is built on the first {@link #get()}.
+    * Each assembly creates a new instance, so results which keep it read the inverted text of their own
+    * statement.
+    */
+   private static final class AssembledFql
+   implements Supplier<String>
+   {
+      /** The assembled statement, untrimmed. */
+      private final String text;
+      
+      /** Length of the statement before its order by clause. */
+      private final int orderByStart;
+      
+      /** Sort criteria of the order by clause, or {@code null} when the statement has none. */
+      private final List<SortCriterion> sortCriteria;
+      
+      /** The inverted statement, built on the first {@link #get()}. */
+      private String inverted = null;
+      
+      /**
+       * Create the text of an assembled statement.
+       *
+       * @param   text
+       *          The assembled statement, untrimmed.
+       * @param   orderByStart
+       *          Length of the statement before its order by clause.
+       * @param   sortCriteria
+       *          Sort criteria of the order by clause, or {@code null} when the statement has none.
+       */
+      AssembledFql(String text, int orderByStart, List<SortCriterion> sortCriteria)
+      {
+         this.text = text;
+         this.orderByStart = orderByStart;
+         this.sortCriteria = sortCriteria;
+      }
+      
+      /**
+       * Get the assembled statement.
+       *
+       * @return  The statement, untrimmed.
+       */
+      String text()
+      {
+         return text;
+      }
+      
+      /**
+       * Get the inverted statement: the same statement with each sort direction of its order by clause
+       * reversed. Without an order by clause it is the statement itself.
+       *
+       * @return  The inverted statement, untrimmed.
+       */
+      @Override
+      public String get()
+      {
+         if (inverted == null)
+         {
+            if (sortCriteria == null)
+            {
+               inverted = text;
+            }
+            else
+            {
+               StringBuilder sb = new StringBuilder(orderByStart + orderByLength(sortCriteria, true));
+               sb.append(text, 0, orderByStart);
+               generateOrderBy(sortCriteria, sb, true);
+               inverted = sb.toString();
+            }
+         }
+         
+         return inverted;
+      }
+   }
 }
 
=== modified file 'src/com/goldencode/p2j/persist/ProgressiveResults.java'
--- old/src/com/goldencode/p2j/persist/ProgressiveResults.java
+++ new/src/com/goldencode/p2j/persist/ProgressiveResults.java
@@ -171,6 +171,7 @@
 ** 056 LS  20260128          Reverted DDF 20241211, 20250120 and RNC 20250912 changes, as they are causing
 **                           performance regression.
 ** 057 AL2 20260326          Moved cache to pk-only to avoid large memory consumption.
+** 058 SP  20261110          The inverted HQL is a Supplier, read only when scrolling backward.
 */
 
 /*
@@ -230,6 +231,7 @@
 
 import java.sql.*;
 import java.util.*;
+import java.util.function.*;
 import java.util.logging.*;
 import com.goldencode.p2j.persist.dialect.*;
 import com.goldencode.p2j.persist.event.*;
@@ -322,8 +324,8 @@
    /** HQL query string used to select records */
    private final String hql;
 
-   /** Inverted HQL query string used to select records. */
-   private final String invertedHQL;
+   /** Supplies the inverted HQL query string; read only when scrolling backward. */
+   private final Supplier<String> invertedHQL;
    
    /** Substitution parameters, if any, to be applied to the query */
    private final Object[] args;
@@ -390,7 +392,7 @@
     * @param   hql
     *          HQL query string used to select records.
     * @param   invertedHQL
-    *          Inverted HQL query string used to select records.
+    *          Supplies the inverted HQL query string used to select records when scrolling backward.
     * @param   args
     *          Substitution parameters, if any, to be applied to the query.
     * @param   scrolling
@@ -409,7 +411,7 @@
     */
    ProgressiveResults(Persistence persistence,
                       String hql,
-                      String invertedHQL,
+                      Supplier<String> invertedHQL,
                       Object[] args,
                       boolean scrolling,
                       boolean forwardOnly,
@@ -1317,7 +1319,7 @@
          int start      = locator.getRow() - locator.getOffset();
          int offset     = start > 0 ? start - 1 : start;
          int maxResults = start > 0 ? locator.getSize() + 1 : locator.getSize();
-         String currentHQL = forwardScroll ? hql : invertedHQL;
+         String currentHQL = forwardScroll ? hql : invertedHQL.get();
 
          if (bracket == 0 || (bracket <= 3 && projection))
          {
=== modified file 'src/com/goldencode/p2j/persist/SortCriterion.java'
--- old/src/com/goldencode/p2j/persist/SortCriterion.java
+++ new/src/com/goldencode/p2j/persist/SortCriterion.java
@@ -122,6 +122,7 @@
 ** 047 TG  20260317          Removed coalesce. The FQL is build now depending of the argument.
 ** 048 RNC 20260402          Fixed javadoc warnings.
 ** 049 ES  20261015          Added getPropertyName(), for the FIND cursor's reposition check.
+** 050 SP  20261110          toSortExpression(boolean) builds its text once; the criterion is immutable.
 */
 
 /*
@@ -287,7 +288,13 @@
    
    /** SQL dialect which used this sort criterion; used for rtrim calls on character properties */
    private final Dialect dialect;
-   
+
+   /** Text of {@link #toSortExpression(boolean)} in the original direction, built on first use. */
+   private String sortText = null;
+
+   /** Text of {@link #toSortExpression(boolean)} in the inverted direction, built on first use. */
+   private String invertedSortText = null;
+
    /**
     * Constructor which parses original sort component text, deriving the property name, sort
     * direction, getter method for the property, case sensitivity of the property (character type
@@ -1000,7 +1007,23 @@
     */
    String toSortExpression(boolean invert)
    {
-      return toSortExpression(invert, true, false, true);
+      // criteria are shared between sessions through the cache; String is immutable, so a racing reader
+      // sees either null (and builds an equal string) or the complete value
+      String text = invert ? invertedSortText : sortText;
+      if (text == null)
+      {
+         text = toSortExpression(invert, true, false, true);
+         if (invert)
+         {
+            invertedSortText = text;
+         }
+         else
+         {
+            sortText = text;
+         }
+      }
+
+      return text;
    }
    
    /**
=== added file 'test/com/goldencode/p2j/persist/FQLExpressionTest.java'
--- old/test/com/goldencode/p2j/persist/FQLExpressionTest.java
+++ new/test/com/goldencode/p2j/persist/FQLExpressionTest.java
@@ -0,0 +1,226 @@
+/*
+** Module   : FQLExpressionTest.java
+** Abstract : Tests for the final text of an FQL expression.
+**
+** Copyright (c) 2026, Golden Code Development Corporation.
+**
+** -#- -I- --Date-- ---------------------------------Description---------------------------------
+** 001 SP  20261110 Created initial version.
+*/
+
+/*
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Affero General Public License as
+** published by the Free Software Foundation, either version 3 of the
+** License, or (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+** GNU Affero General Public License for more details.
+**
+** You may find a copy of the GNU Affero GPL version 3 at the following
+** location: https://www.gnu.org/licenses/agpl-3.0.en.html
+**
+** Additional terms under GNU Affero GPL version 3 section 7:
+**
+**   Under Section 7 of the GNU Affero GPL version 3, the following additional
+**   terms apply to the works covered under the License.  These additional terms
+**   are non-permissive additional terms allowed under Section 7 of the GNU
+**   Affero GPL version 3 and may not be removed by you.
+**
+**   0. Attribution Requirement.
+**
+**     You must preserve all legal notices or author attributions in the covered
+**     work or Appropriate Legal Notices displayed by works containing the covered
+**     work.  You may not remove from the covered work any author or developer
+**     credit already included within the covered work.
+**
+**   1. No License To Use Trademarks.
+**
+**     This license does not grant any license or rights to use the trademarks
+**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
+**     of Golden Code Development Corporation. You are not authorized to use the
+**     name Golden Code, FWD, or the names of any author or contributor, for
+**     publicity purposes without written authorization.
+**
+**   2. No Misrepresentation of Affiliation.
+**
+**     You may not represent yourself as Golden Code Development Corporation or FWD.
+**
+**     You may not represent yourself for publicity purposes as associated with
+**     Golden Code Development Corporation, FWD, or any author or contributor to
+**     the covered work, without written authorization.
+**
+**   3. No Misrepresentation of Source or Origin.
+**
+**     You may not represent the covered work as solely your work.  All modified
+**     versions of the covered work must be marked in a reasonable way to make it
+**     clear that the modified work is not originating from Golden Code Development
+**     Corporation or FWD.  All modified versions must contain the notices of
+**     attribution required in this license.
+*/
+
+package com.goldencode.p2j.persist;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link FQLExpression#toFinalExpression(boolean)},
+ * {@link FQLExpression#appendFinalExpression(StringBuilder, boolean)} and
+ * {@link FQLExpression#finalLength(boolean)}: the same text through each, with numbered (JPA-style) and
+ * simple placeholders.
+ */
+public class FQLExpressionTest
+{
+   /**
+    * Placeholders are numbered from 0 in JPA style and plain otherwise.
+    */
+   @Test
+   public void finalExpressionNumbersPlaceholders()
+   {
+      assertText("a = ?0 and b = ?1 order", twoSubstitutions(), true);
+      assertText("a = ? and b = ? order", twoSubstitutions(), false);
+   }
+
+   /**
+    * An expression ending with a substitution ends with its placeholder.
+    */
+   @Test
+   public void finalExpressionEndingWithSubstitution()
+   {
+      assertText("x = ?0", new FQLExpression("x = ", true), true);
+   }
+
+   /**
+    * Text appended to the buffered last part comes out in order.
+    */
+   @Test
+   public void finalExpressionOfBufferedParts()
+   {
+      assertText("from t as t", new FQLExpression("from ").append("t").append(" as t"), true);
+   }
+
+   /**
+    * A nested expression keeps its placeholders and the trailing space.
+    */
+   @Test
+   public void finalExpressionOfNestedExpression()
+   {
+      assertText("from t where t.k = ?0 and t.n = ?1 ", nested(), true);
+   }
+
+   /**
+    * An empty expression gives empty text and appends nothing.
+    */
+   @Test
+   public void emptyExpressionAppendsNothing()
+   {
+      assertText("", new FQLExpression(), true);
+      
+      StringBuilder sb = new StringBuilder("x");
+      new FQLExpression().appendFinalExpression(sb, true);
+      assertEquals("x", sb.toString());
+   }
+
+   /**
+    * Appending keeps what the builder already holds.
+    */
+   @Test
+   public void appendKeepsExistingContent()
+   {
+      StringBuilder sb = new StringBuilder("select t.id ");
+      nested().appendFinalExpression(sb, true);
+      assertEquals("select t.id from t where t.k = ?0 and t.n = ?1 ", sb.toString());
+   }
+
+   /**
+    * Appending changes no state: two appends and a final call give the same text.
+    */
+   @Test
+   public void appendThenToFinalAgree()
+   {
+      FQLExpression e = nested();
+      StringBuilder a = new StringBuilder();
+      StringBuilder b = new StringBuilder();
+      e.appendFinalExpression(a, true);
+      e.appendFinalExpression(b, true);
+      
+      assertEquals(a.toString(), b.toString());
+      assertEquals(a.toString(), e.toFinalExpression());
+   }
+
+   /**
+    * The final length is the length of the final text, also with two-digit placeholder indexes.
+    */
+   @Test
+   public void finalLengthMatchesText()
+   {
+      FQLExpression twelve = new FQLExpression("p0 = ", true);
+      for (int i = 1; i < 12; i++)
+      {
+         twelve.append(" and p" + i + " = ", true);
+      }
+      assertTrue(twelve.toFinalExpression().contains("?11"));
+      
+      FQLExpression[] all =
+      {
+         twoSubstitutions(),
+         new FQLExpression("x = ", true),
+         new FQLExpression("from ").append("t").append(" as t"),
+         nested(),
+         new FQLExpression(),
+         twelve
+      };
+      for (FQLExpression e : all)
+      {
+         for (boolean jpa : new boolean[] { true, false })
+         {
+            assertEquals(e.toFinalExpression(jpa).length(), e.finalLength(jpa), e.toFinalExpression(jpa));
+         }
+      }
+   }
+
+   /**
+    * Check an expression's text through {@code toFinalExpression} and {@code appendFinalExpression}.
+    *
+    * @param    expected
+    *           The expected text.
+    * @param    e
+    *           The expression.
+    * @param    jpaStyle
+    *           {@code true} for numbered placeholders.
+    */
+   private static void assertText(String expected, FQLExpression e, boolean jpaStyle)
+   {
+      assertEquals(expected, e.toFinalExpression(jpaStyle));
+      
+      StringBuilder sb = new StringBuilder();
+      e.appendFinalExpression(sb, jpaStyle);
+      assertEquals(expected, sb.toString());
+   }
+
+   /**
+    * Build an expression with two substitutions followed by plain text.
+    *
+    * @return   {@code a = ? and b = ? order} with two placeholders.
+    */
+   private static FQLExpression twoSubstitutions()
+   {
+      return new FQLExpression("a = ", true).append(" and b = ", true).append(" order");
+   }
+
+   /**
+    * Build an expression holding a nested expression with two substitutions.
+    *
+    * @return   {@code from t where t.k = ? and t.n = ? } with two placeholders.
+    */
+   private static FQLExpression nested()
+   {
+      return new FQLExpression("from t where ").append(new FQLExpression("t.k = ", true)
+                                                          .append(" and t.n = ", true))
+                                               .append(" ");
+   }
+}
=== added file 'test/com/goldencode/p2j/persist/SortCriterionTest.java'
--- old/test/com/goldencode/p2j/persist/SortCriterionTest.java
+++ new/test/com/goldencode/p2j/persist/SortCriterionTest.java
@@ -0,0 +1,225 @@
+/*
+** Module   : SortCriterionTest.java
+** Abstract : Tests for the ORDER BY text of a sort criterion.
+**
+** Copyright (c) 2026, Golden Code Development Corporation.
+**
+** -#- -I- --Date-- ---------------------------------Description---------------------------------
+** 001 SP  20261110 Created initial version.
+*/
+
+/*
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Affero General Public License as
+** published by the Free Software Foundation, either version 3 of the
+** License, or (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+** GNU Affero General Public License for more details.
+**
+** You may find a copy of the GNU Affero GPL version 3 at the following
+** location: https://www.gnu.org/licenses/agpl-3.0.en.html
+**
+** Additional terms under GNU Affero GPL version 3 section 7:
+**
+**   Under Section 7 of the GNU Affero GPL version 3, the following additional
+**   terms apply to the works covered under the License.  These additional terms
+**   are non-permissive additional terms allowed under Section 7 of the GNU
+**   Affero GPL version 3 and may not be removed by you.
+**
+**   0. Attribution Requirement.
+**
+**     You must preserve all legal notices or author attributions in the covered
+**     work or Appropriate Legal Notices displayed by works containing the covered
+**     work.  You may not remove from the covered work any author or developer
+**     credit already included within the covered work.
+**
+**   1. No License To Use Trademarks.
+**
+**     This license does not grant any license or rights to use the trademarks
+**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
+**     of Golden Code Development Corporation. You are not authorized to use the
+**     name Golden Code, FWD, or the names of any author or contributor, for
+**     publicity purposes without written authorization.
+**
+**   2. No Misrepresentation of Affiliation.
+**
+**     You may not represent yourself as Golden Code Development Corporation or FWD.
+**
+**     You may not represent yourself for publicity purposes as associated with
+**     Golden Code Development Corporation, FWD, or any author or contributor to
+**     the covered work, without written authorization.
+**
+**   3. No Misrepresentation of Source or Origin.
+**
+**     You may not represent the covered work as solely your work.  All modified
+**     versions of the covered work must be marked in a reasonable way to make it
+**     clear that the modified work is not originating from Golden Code Development
+**     Corporation or FWD.  All modified versions must contain the notices of
+**     attribution required in this license.
+*/
+
+package com.goldencode.p2j.persist;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.junit.jupiter.api.*;
+
+import com.goldencode.asm.*;
+import com.goldencode.p2j.persist.dialect.*;
+import com.goldencode.p2j.persist.orm.*;
+
+/**
+ * Tests for {@link SortCriterion#toSortExpression(boolean)}: the ORDER BY text for every dialect branch
+ * (upper and rtrim, rtrim only, plain names, computed-column prefixes, a copy with another alias), and
+ * that a criterion builds that text once.
+ * <p>
+ * Registering the test DMO needs FWD's {@code AsmClassLoader} as the system class loader
+ * ({@code -Djava.system.class.loader=com.goldencode.asm.AsmClassLoader}).
+ */
+public class SortCriterionTest
+{
+   /** Metadata of {@link SortCriterionTestDmo}. */
+   private static DmoMeta meta;
+
+   /**
+    * Register the test DMO, or skip the tests when the JVM was not started with FWD's
+    * {@code AsmClassLoader} as the system class loader, which DMO registration needs.
+    */
+   @BeforeAll
+   public static void registerDmo()
+   {
+      Assumptions.assumeTrue(AsmClassLoader.getInstance() != null,
+                             "needs -Djava.system.class.loader=com.goldencode.asm.AsmClassLoader");
+      meta = DmoMetadataManager.registerDmo(SortCriterionTestDmo.class);
+   }
+
+   /**
+    * Each dialect gives the expected text in both directions for a case-insensitive and a case-sensitive
+    * character field, an integer field, the primary key and a copy with another alias.
+    *
+    * @throws   Exception
+    *           If a criterion cannot be built.
+    */
+   @Test
+   public void sortTextMatchesEachDialect()
+   throws Exception
+   {
+      String[] plain = { "spike.nm desc", "spike.code desc", "other.nm asc" };
+      
+      assertDialect(new P2JPostgreSQLDialect(),
+                    "upper(rtrim(spike.nm)) desc", "rtrim(spike.code) desc", "upper(rtrim(other.nm)) asc");
+      assertDialect(new P2JH2Dialect(), plain[0], plain[1], plain[2]);
+      assertDialect(new MariaDbLenientDialect(), plain[0], plain[1], plain[2]);
+      assertDialect(new MariaDbDialect(), plain[0], plain[1], plain[2]);
+      assertDialect(new P2JSQLServer2012Dialect(),
+                    "spike.__inm desc", "spike.__scode desc", "other.__inm asc");
+   }
+
+   /**
+    * A criterion returns the same text instance on every call, for each direction and through
+    * {@code toString()}.
+    *
+    * @throws   Exception
+    *           If the criterion cannot be built.
+    */
+   @Test
+   public void sortTextIsBuiltOnce()
+   throws Exception
+   {
+      SortCriterion c = new SortCriterion(new P2JPostgreSQLDialect(), "spike.nm desc", meta, false);
+      
+      assertSame(c.toSortExpression(false), c.toSortExpression(false));
+      assertSame(c.toSortExpression(true), c.toSortExpression(true));
+      assertSame(c.toString(), c.toSortExpression(false));
+   }
+
+   /**
+    * Threads sharing one fresh criterion all get the complete text.
+    *
+    * @throws   Exception
+    *           If the criterion cannot be built or a thread fails.
+    */
+   @Test
+   public void sortTextIsCorrectFromManyThreads()
+   throws Exception
+   {
+      SortCriterion c = new SortCriterion(new P2JPostgreSQLDialect(), "spike.nm desc", meta, false);
+      ExecutorService pool = Executors.newFixedThreadPool(8);
+      try
+      {
+         List<Future<Boolean>> results = new ArrayList<>();
+         for (int t = 0; t < 8; t++)
+         {
+            results.add(pool.submit(() ->
+            {
+               boolean ok = true;
+               for (int i = 0; i < 10_000; i++)
+               {
+                  ok &= "upper(rtrim(spike.nm)) desc".equals(c.toSortExpression(false));
+                  ok &= "upper(rtrim(spike.nm)) asc".equals(c.toSortExpression(true));
+               }
+               return ok;
+            }));
+         }
+         
+         for (Future<Boolean> f : results)
+         {
+            assertTrue(f.get());
+         }
+      }
+      finally
+      {
+         pool.shutdownNow();
+      }
+   }
+
+   /**
+    * Check the text of one dialect in both directions.
+    *
+    * @param    dialect
+    *           The dialect.
+    * @param    nm
+    *           Expected text of {@code spike.nm desc}.
+    * @param    code
+    *           Expected text of {@code spike.code desc}.
+    * @param    copy
+    *           Expected text of the copy of {@code spike.nm} with alias {@code other}.
+    *
+    * @throws   Exception
+    *           If a criterion cannot be built.
+    */
+   private static void assertDialect(Dialect dialect, String nm, String code, String copy)
+   throws Exception
+   {
+      assertBoth(nm, new SortCriterion(dialect, "spike.nm desc", meta, false));
+      assertBoth(code, new SortCriterion(dialect, "spike.code desc", meta, false));
+      assertBoth("spike.k asc", new SortCriterion(dialect, "spike.k", meta, false));
+      assertBoth("spike.recid asc", new SortCriterion(dialect, "spike.recid asc", meta, false));
+      assertBoth(copy, new SortCriterion(new SortCriterion(dialect, "spike.nm", meta, false), "other"));
+   }
+
+   /**
+    * Check a criterion's text, and that the inverted text swaps only the trailing direction.
+    *
+    * @param    expected
+    *           Expected text in the original direction.
+    * @param    c
+    *           The criterion.
+    */
+   private static void assertBoth(String expected, SortCriterion c)
+   {
+      String inverted = expected.endsWith(" asc")
+                        ? expected.substring(0, expected.length() - 4) + " desc"
+                        : expected.substring(0, expected.length() - 5) + " asc";
+      
+      assertEquals(expected, c.toSortExpression(false));
+      assertEquals(inverted, c.toSortExpression(true));
+      assertEquals(expected, c.toString());
+   }
+}
=== added file 'test/com/goldencode/p2j/persist/SortCriterionTestDmo.java'
--- old/test/com/goldencode/p2j/persist/SortCriterionTestDmo.java
+++ new/test/com/goldencode/p2j/persist/SortCriterionTestDmo.java
@@ -0,0 +1,140 @@
+/*
+** Module   : SortCriterionTestDmo.java
+** Abstract : Data model object for the SortCriterion tests.
+**
+** Copyright (c) 2026, Golden Code Development Corporation.
+**
+** -#- -I- --Date-- ---------------------------------Description---------------------------------
+** 001 SP  20261110 Created initial version.
+*/
+
+/*
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Affero General Public License as
+** published by the Free Software Foundation, either version 3 of the
+** License, or (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+** GNU Affero General Public License for more details.
+**
+** You may find a copy of the GNU Affero GPL version 3 at the following
+** location: https://www.gnu.org/licenses/agpl-3.0.en.html
+**
+** Additional terms under GNU Affero GPL version 3 section 7:
+**
+**   Under Section 7 of the GNU Affero GPL version 3, the following additional
+**   terms apply to the works covered under the License.  These additional terms
+**   are non-permissive additional terms allowed under Section 7 of the GNU
+**   Affero GPL version 3 and may not be removed by you.
+**
+**   0. Attribution Requirement.
+**
+**     You must preserve all legal notices or author attributions in the covered
+**     work or Appropriate Legal Notices displayed by works containing the covered
+**     work.  You may not remove from the covered work any author or developer
+**     credit already included within the covered work.
+**
+**   1. No License To Use Trademarks.
+**
+**     This license does not grant any license or rights to use the trademarks
+**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
+**     of Golden Code Development Corporation. You are not authorized to use the
+**     name Golden Code, FWD, or the names of any author or contributor, for
+**     publicity purposes without written authorization.
+**
+**   2. No Misrepresentation of Affiliation.
+**
+**     You may not represent yourself as Golden Code Development Corporation or FWD.
+**
+**     You may not represent yourself for publicity purposes as associated with
+**     Golden Code Development Corporation, FWD, or any author or contributor to
+**     the covered work, without written authorization.
+**
+**   3. No Misrepresentation of Source or Origin.
+**
+**     You may not represent the covered work as solely your work.  All modified
+**     versions of the covered work must be marked in a reasonable way to make it
+**     clear that the modified work is not originating from Golden Code Development
+**     Corporation or FWD.  All modified versions must contain the notices of
+**     attribution required in this license.
+*/
+
+package com.goldencode.p2j.persist;
+
+import com.goldencode.p2j.persist.annotation.*;
+import com.goldencode.p2j.util.*;
+
+/**
+ * Data model object for {@link SortCriterionTest}: an integer key, a case-insensitive character field
+ * and a case-sensitive character field.
+ */
+@Table(name = "spike", legacy = "spike")
+@Indices(
+{
+   @Index(name = "k", legacy = "k", primary = true, unique = true, components = 
+   {
+      @IndexComponent(name = "k", legacy = "k")
+   }),
+   @Index(name = "nm", legacy = "nm", components = 
+   {
+      @IndexComponent(name = "nm", legacy = "nm")
+   }),
+   @Index(name = "code", legacy = "code", components = 
+   {
+      @IndexComponent(name = "code", legacy = "code")
+   })
+})
+public interface SortCriterionTestDmo
+extends DataModelObject
+{
+   /**
+    * Getter: k
+    *
+    * @return   The integer key.
+    */
+   @Property(id = 1, name = "k", column = "k", legacy = "k", format = ">>>>9", initial = "0", order = 10)
+   public integer getK();
+
+   /**
+    * Setter: k
+    *
+    * @param    k
+    *           The integer key.
+    */
+   public void setK(NumberType k);
+
+   /**
+    * Getter: nm
+    *
+    * @return   The case-insensitive character field.
+    */
+   @Property(id = 2, name = "nm", column = "nm", legacy = "nm", format = "x(30)", order = 20)
+   public character getNm();
+
+   /**
+    * Setter: nm
+    *
+    * @param    nm
+    *           The case-insensitive character field.
+    */
+   public void setNm(Text nm);
+
+   /**
+    * Getter: code
+    *
+    * @return   The case-sensitive character field.
+    */
+   @Property(id = 3, name = "code", column = "code", legacy = "code", format = "x(8)", caseSensitive = true,
+             order = 30)
+   public character getCode();
+
+   /**
+    * Setter: code
+    *
+    * @param    code
+    *           The case-sensitive character field.
+    */
+   public void setCode(Text code);
+}
