builds an order-by clause
3215
def clause(grouped_columns_calculations = nil)
      return nil if sorts_by_method? || default_sorting?

      # unless the sorting is by method, create the sql string
      order = []
      each do |sort_column, sort_direction|
        next if constraint_columns.include? sort_column.name
        sql = grouped_columns_calculations&.dig(sort_column.name) || sort_column.sort[:sql]
        next if sql.blank?
        sql = sql.to_sql if sql.respond_to?(:to_sql)

        parts = Array(sql).map do |column|
          mongoid? ? [column, sort_direction] : "#{column} #{sort_direction}"
        end
        order << parts
      end

      order << @primary_key_order_clause if @sorting_by_primary_key
      order.flatten!(1)
      order unless order.empty?
    end
851904
public function buildSortingSQL(&$joins, &$where, &$sort, $order = 'ASC')
    {
        if ($this->isRandomOrder($order)) {
            $sort = 'ORDER BY RAND()';
        } else {
            $sort = sprintf(
                'ORDER BY (
                    SELECT %s
                    FROM tbl_entries_data_%d AS `ed`
                    WHERE entry_id = e.id
                ) %s, `e`.`id` %s',
                '`ed`.date',
                $this->get('id'),
                $order,
                $order
            );
        }
    }
428720
def order_by_t(func):
    
    return Transformation(
        'order_by({0})'.format(name(func)),
        lambda sequence: sorted(sequence, key=func),
        None
    )
903651
function order($order)
    {
        if (!empty($order))
        {
            self::sql_safe($order);
            $this->order = "order by $order";
        }
        else
        {
            $this->order = '';
        }
    }
66624
protected function buildOrderBy()
    {
        if (count($this->orderBy) === 0) {
            return '';
        }

        $orders = [];
        foreach ($this->orderBy as $orderBy) {
            $key = $this->quoteIdentifier($orderBy['tableName']) . '.' . $this->quoteIdentifier($orderBy['key']);
            $orders[] = $key . ' ' . $orderBy['direction'];
        }
        return 'ORDER BY ' . implode(', ', $orders);
    }
791568
public OqlBuilder<T> orderBy(final int index, final String orderBy) {
    if (null != orders) {
      if (isNotEmpty(statement)) { throw new RuntimeException("cannot add order by to a exists statement."); }
      this.orders.addAll(index, Order.parse(orderBy));
    }
    return this;
  }
323473
protected <T> String buildSql(CpoClass cpoClass, String sql, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeQueries, List<BindAttribute> bindValues) throws CpoException {
    StringBuilder sqlText = new StringBuilder();

    sqlText.append(sql);

    if (wheres != null) {
      for (CpoWhere where : wheres) {
        BindableWhereBuilder<T> jwb = new BindableWhereBuilder<>(cpoClass);
        BindableCpoWhere jcw = (BindableCpoWhere) where;

        // do the where stuff here when ready
        try {
          jcw.acceptDFVisitor(jwb);
        } catch (Exception e) {
          throw new CpoException("Unable to build WHERE clause", e);
        }

        if (sqlText.indexOf(jcw.getName()) == -1) {
          sqlText.append(" ");
          sqlText.append(jwb.getWhereClause());
          bindValues.addAll(jwb.getBindValues());
        } else {
          sqlText = replaceMarker(sqlText, jcw.getName(), jwb, bindValues);
        }
      }
    }

    // do the order by stuff now
    if (orderBy != null) {
      HashMap<String, StringBuilder> mapOrderBy = new HashMap<>();
      try {
        for (CpoOrderBy ob : orderBy) {
          StringBuilder sb = mapOrderBy.get(ob.getMarker());
          if (sb == null) {
            sb = new StringBuilder(" ORDER BY ");
            mapOrderBy.put(ob.getMarker(), sb);
          } else {
            sb.append(",");
          }
          sb.append(ob.toString(cpoClass));
        }
      } catch (CpoException ce) {
        throw new CpoException("Error Processing OrderBy Attribute<" + ExceptionHelper.getLocalizedMessage(ce) + "> not Found. JDBC Expression=<" + sqlText.toString() + ">");
      }

      Set<Entry<String, StringBuilder>> entries = mapOrderBy.entrySet();
      for (Entry<String, StringBuilder> entry : entries) {
        if (sqlText.indexOf(entry.getKey()) == -1) {
          sqlText.append(entry.getValue().toString());
        } else {
          sqlText = replaceMarker(sqlText, entry.getKey(), entry.getValue().toString());
        }
      }
    }

    if (nativeQueries != null) {
      for (CpoNativeFunction cnq : nativeQueries) {
        if (cnq.getMarker() == null || sqlText.indexOf(cnq.getMarker()) == -1) {
          if (cnq.getExpression() != null && cnq.getExpression().length() > 0) {
            sqlText.append(" ");
            sqlText.append(cnq.getExpression());
          }
        } else {
          sqlText = replaceMarker(sqlText, cnq.getMarker(), cnq.getExpression());
        }
      }
    }

    // left for backwards compatibility
    sqlText = replaceMarker(sqlText, WHERE_MARKER, "");
    sqlText = replaceMarker(sqlText, ORDERBY_MARKER, "");

    return sqlText.toString();
  }
696847
def orderBy(self, field, direct="desc"):
        
        if direct == "desc":
            self._query = self._query.order_by(r.desc(field))
        else:
            self._query = self._query.order_by(r.asc(field))

        return self
244977
public function orderBy($order) 
    {
        
        $this->sql .= ' ORDER BY ';
        
        foreach($order as $column) {
            $this->sql .= $this->quoteColumnName($column[0]) .' '. $column[1] . ', ';
        }
        
        $this->sql = trim($this->sql, ', ');
        
        return $this;
    }
1207654
def query_sort(query, options)
      query.order(options[:order]) if options[:order]
      query.order(options[:desc_order], :desc) if options[:desc_order]
      query
    end
249587
def makeSQL(action, table, cols="*", where=(), group="", order=(), limit=(), values=()):
    """"""
    cols  =    cols if isinstance(cols,  basestring) else ", ".join(cols)
    group =   group if isinstance(group, basestring) else ", ".join(group)
    order = [order] if isinstance(order, basestring) else order
    limit = [limit] if isinstance(limit, (basestring, int)) else limit
    sql = "SELECT %s FROM %s" % (cols, table) if "SELECT" == action else ""
    sql = "DELETE FROM %s"    % (table)       if "DELETE" == action else sql
    sql = "INSERT INTO %s"    % (table)       if "INSERT" == action else sql
    sql = "UPDATE %s"         % (table)       if "UPDATE" == action else sql
    args = {}
    if "INSERT" == action:
        args.update(values)
        cols, vals = (", ".join(x + k for k, v in values) for x in ("", ":"))
        sql += " (%s) VALUES (%s)" % (cols, vals)
    if "UPDATE" == action:
        sql += " SET "
        for i, (col, val) in enumerate(values):
            sql += (", " if i else "") + "%s = :%sU%s" % (col, col, i)
            args["%sU%s" % (col, i)] = val
    if where:
        sql += " WHERE "
        for i, (col, val) in enumerate(where):
            key = "%sW%s" % (re.sub("\\W", "_", col), i)
            dbval = val[1] if isinstance(val, (list, tuple)) else val
            args[key] = dbval
            op = "IS" if dbval == val else val[0]
            op = "=" if dbval is not None and "IS" == op else op
            sql += (" AND " if i else "") + "%s %s :%s" % (col, op, key)
    if group:
        sql += " GROUP BY " + group
    if order:
        sql += " ORDER BY "
        for i, col in enumerate(order):
            name = col[0] if isinstance(col, (list, tuple)) else col
            direction = "" if name == col else " " + col[1]
            sql += (", " if i else "") + name + direction
    if limit:
        sql += " LIMIT %s" % (", ".join(map(str, limit)))
    return sql, args
1009544
private function buildOrderByPart($query)
    {
        $conditions = $query->getOrderConditions();
        if (!count($conditions)) {
            return '';
        }

        $result = [];
        foreach ($conditions as $column => $direction) {
            $result[] = $this->quoteIdentifier($column) . ' ' . strtoupper($direction);
        }

        return "\nORDER BY " . implode(", ", $result);
    }
837046
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) {
        boolean isFirst = true;
        String querySortDirection;

        for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) {
            if (isFirst) {
                orderByBuilder.append(" ORDER BY ");
                isFirst = false;
            } else {
                orderByBuilder.append(", ");
            }

            if (sort.getValue().equals(SortDirection.ASCENDING)) {
                querySortDirection = "ASC";
            } else {
                querySortDirection = "DESC";
            }
            orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection);
        }
    }
1281463
private String buildSelectSQL(boolean addOrderBy) {
        SQLParams sqlParams = SQLParams.builder()
                .modelClass(this.modelClass)
                .selectColumns(this.selectColumns)
                .tableName(this.tableName)
                .pkName(this.primaryKeyColumn)
                .conditionSQL(this.conditionSQL)
                .excludedColumns(this.excludedColumns)
                .isSQLLimit(isSQLLimit)
                .build();

        ifThen(addOrderBy, () -> sqlParams.setOrderBy(this.orderBySQL.toString()));

        return Anima.of().dialect().select(sqlParams);
    }
510306
def _prepare_order_bys(self):
        
        order_bys = OrderedSet()
        if self._order_bys:
            for ingredient in self._order_bys:
                if isinstance(ingredient, Dimension):
                    # Reverse the ordering columns so that dimensions
                    # order by their label rather than their id
                    columns = reversed(ingredient.columns)
                else:
                    columns = ingredient.columns
                for c in columns:
                    order_by = c.desc() if ingredient.ordering == 'desc' else c
                    if str(order_by) not in [str(o) for o in order_bys]:
                        order_bys.add(order_by)

        return list(order_bys)
1016436
def _make_order(field_path, direction):
        """"""
        return query_pb2.StructuredQuery.Order(
            field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
            direction=_enum_from_direction(direction),
        )
685521
public void buildOrderByClause(StringBuilder builder, String field, Object orderType, boolean useToken)
    {
        builder.append(SPACE_STRING);
        builder.append(SORT_CLAUSE);
        builder = ensureCase(builder, field, useToken);
        builder.append(SPACE_STRING);
        builder.append(orderType);
    }