private static void processOrderBy(final DB db, final DatabaseMap dbMap, final Criteria crit, final Query query)
    throws TorqueException {
    UniqueList orderByClause = query.getOrderByClause();
    UniqueList selectClause = query.getSelectClause();

    UniqueList orderBy = crit.getOrderByColumns();

    if (orderBy != null && orderBy.size() > 0) {
      // Check for each String/Character column and apply
      // toUpperCase().
      for (int i = 0; i < orderBy.size(); i++) {
        String orderByColumn = (String) orderBy.get(i);

        String strippedColumnName = removeSQLFunction(orderByColumn);
        int dotPos = strippedColumnName.lastIndexOf('.');
        if (dotPos == -1) {
          // We are not able to look up the table in the
          // tableMap, as no table name is given. Simply add
          // the orderBy and hope the user knows what he is
          // doing.
          orderByClause.add(orderByColumn);
          continue;
        }

        String tableName = strippedColumnName.substring(0, dotPos);
        String table = crit.getTableForAlias(tableName);
        if (table == null) {
          table = tableName;
        }

        // See if there's a space (between the column list and sort
        // order in ORDER BY table.column DESC).
        int spacePos = strippedColumnName.indexOf(' ');
        String columnName;
        if (spacePos == -1) {
          columnName = strippedColumnName.substring(dotPos + 1);
        } else {
          columnName = strippedColumnName.substring(dotPos + 1, spacePos);
        }
        ColumnMap column = dbMap.getTable(table).getColumn(columnName);

        // only ignore case in order by for string columns
        // which do not have a function around them
        if (column.getType() instanceof String && orderByColumn.indexOf('(') == -1) {
          // find space pos relative to orderByColumn
          spacePos = orderByColumn.indexOf(' ');
          if (spacePos == -1) {
            orderByClause.add(db.ignoreCaseInOrderBy(orderByColumn));
          } else {
            orderByClause.add(db.ignoreCaseInOrderBy(orderByColumn.substring(0, spacePos)) + orderByColumn.substring(spacePos));
          }
          selectClause.add(db.ignoreCaseInOrderBy(tableName + '.' + columnName));
        } else {
          orderByClause.add(orderByColumn);
        }
      }
    }
  }