ORDER BY clause for the passed order option.

 Uses column aliases as defined by {#distinct}.
324319
def add_order_by_for_association_limiting!(sql, options)
      return sql if options[:order].blank?

      order_columns = extract_order_columns(options[:order]) do |columns|
        columns.map! { |s| $1 if s =~ / (.*)/ }; columns
      end
      order = order_columns.map { |s, i| "alias_#{i}__ #{s}" } # @see {#distinct}

      sql << "ORDER BY #{order.join(', ')}"
    end
187270
function distinct() {
    this._statements.push({
      grouping: 'columns',
      value: normalizeArr.apply(null, arguments),
      distinct: true
    });
    return this;
  }
354807
def _sort2sql(self, sort):
        
        if not sort:
            return ""
        return SQL_ORDERBY + sql_list([quote_column(o.field) + (" DESC" if o.sort == -1 else "") for o in sort])
1010768
def apply_ordering_to_scope(scope, user_params)
      sort_name, direction = calculate_sort_name_and_direction(user_params)
      order = configuration[:sort_orders].fetch(sort_name, {})[:value]

      ordered_scope = case order
        when Proc
          fresh_helper_instance.instance_exec(scope, direction, &order)
        when nil
          scope
        else
          scope.reorder(order.to_s + " " + direction)
      end

      fallback_deterministic_sort = assemble_primary_key_sort(scope)
      # Chain on a tiebreaker sort to ensure deterministic ordering of multiple pages of data

      if fallback_deterministic_sort
        ordered_scope.order(fallback_deterministic_sort)
      else
        ordered_scope
      end
    end
620354
def order(*ordering)
      @order = ordering.map do |c|
        if c.kind_of?(String)
          {:column => c, :ascending => true}
        else
          c.symbolize_keys!
        end
      end
      self
    end
102410
function createSOQL(query) {
  var soql = [
    "SELECT ",
    createFieldsClause(query.fields, query.includes),
    " FROM ",
    query.table
  ].join("");
  var cond = createConditionClause(query.conditions);
  if (cond) {
    soql += " WHERE " + cond;
  }
  var orderby = createOrderByClause(query.sort);
  if (orderby) {
    soql += " ORDER BY " + orderby;
  }
  if (query.limit) {
    soql += " LIMIT " + query.limit;
  }
  if (query.offset) {
    soql += " OFFSET " + query.offset;
  }
  return soql;
}
315761
def order(self, order):
    '''

    '''
    order = order if isinstance(order, Order) else Order(order)

    # ensure order gets attr values the same way the rest of the query does.
    order.object_getattr = self.object_getattr
    self.orders.append(order)
    return self
1361118
public function groupConcatSet( $expr, $alias=null, $separator=null, $distinct=null, $order=null )
	{
		debug_assert(
			is_string($expr) || is_array($expr) || (is_object($expr) && $expr instanceof Zend_Db_Expr),
			"Invalid expression value `".var_dump_human_compact($expr)."`"
		);
		debug_assert(
			is_null($alias) || is_string($alias),
			"Invalid alias value `".var_dump_human_compact($alias)."`"
		);
		debug_assert(
			is_null($separator) || is_string($separator),
			"Invalid separator value `".var_dump_human_compact($separator)."`"
		);
		debug_assert(
			is_null($distinct) || is_bool($distinct),
			"Invalid distinct value `".var_dump_human_compact($distinct)."`"
		);
		debug_assert(
			is_null($order) || is_array($order) || is_int($order) || is_string($order) || (is_object($order) && $order instanceof Zend_Db_Expr),
			"Invalid order value `".var_dump_human_compact($order)."`"
		);
		$convertToString = function($expr)
		{
			if( is_object($expr) )
			{
				$expr = strval($expr);
			}
			else
			{
				if( array_key_exists( $expr, $this->schemaColumnsGet() ) )
				{
					$expr = str_wrap($this->getAlias(),'`').'.'.str_wrap( $expr, '`' );
				}
				elseif( is_string($expr) )
				{
					$expr = str_wrap( $expr, '\'' );
				}
			}
			return $expr;
		};
		if( is_array($expr) )
		{
			$expr = array_chain(
				$expr,
				array_map_val_dg( tuple_get( 0, $convertToString ) ),
				array_implode_dg(',')
			);
		}
		else
		{
			$expr = $convertToString( strval($expr) );
		}
		if( $distinct!==null )
		{
			$expr = "DISTINCT {$expr}";
		}
		if( $order!==null )
		{
			if( is_array($order) )
			{
				$order = array_chain(
					$expr,
					array_map_val_dg( tuple_get( 0, $convertToString ) ),
					array_implode_dg(',')
				);
			}
			else
			{
				$order = $convertToString( strval($order) );
			}
			$expr = "{$expr} ORDER BY {$order}";
		}
		if( $separator!==null )
		{
			$expr = "{$expr} SEPARATOR '{$separator}'";
		}
		$expr = "GROUP_CONCAT({$expr})";
		if( $alias!==null )
		{
			$expr = [$alias=>$expr];
		}
		return $this->setColumns( $expr, $this->getAlias() );
	}
692865
def select(first_or_all, sql_params = "", *bindvars)
      case first_or_all
      when :first, :all
        select_sql = "SELECT * "
      when :count
        select_sql = "SELECT COUNT(*) "
      else
        raise ArgumentError, "Only :first, :all or :count are supported"
      end
      select_sql << "FROM \"#{@schema_name}\".\"#{@table_name}\" "
      case sql_params
      when String
        select_sql << sql_params
      when Hash
        raise ArgumentError, "Cannot specify bind variables when passing WHERE conditions as Hash" unless bindvars.empty?
        where_sqls = []
        order_by_sql = nil
        sql_params.each do |k, v|
          if k == :order_by
            order_by_sql = " ORDER BY #{v} "
          elsif v.nil? || v == :is_null
            where_sqls << "#{k} IS NULL"
          elsif v == :is_not_null
            where_sqls << "#{k} IS NOT NULL"
          else
            where_sqls << "#{k} = :#{k}"
            bindvars << v
          end
        end
        select_sql << "WHERE " << where_sqls.join(" AND ") unless where_sqls.empty?
        select_sql << order_by_sql if order_by_sql
      else
        raise ArgumentError, "Only String or Hash can be provided as SQL condition argument"
      end
      if first_or_all == :count
        @schema.select_one(select_sql, *bindvars)
      else
        @schema.select(first_or_all, select_sql, *bindvars)
      end
    end
916280
public final function FetchByField($distinct, $field, $value, Sql\OrderList $orderBy = null, Sql\GroupList $groupBy = null, $offset = 0, $count = null)
    {
        $where = $this->FieldCondition($field, $value);        
        return $this->Fetch($distinct, $where, $orderBy, $groupBy, $offset, $count);
    }
618059
public function buildSelect($columns, &$params, $distinct = false, $selectOption = null, $query)
    {
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';

        if ($selectOption !== null) {
            $select .= ' ' . $selectOption;
        }

        if (empty($columns)) {
            return $select . ' *';
        }

        $columns = is_array($columns) ? $columns : [$columns];

        foreach ($columns as $i => $column) {
            if ($column instanceof Expression) {
                if (is_int($i)) {
                    $columns[$i] = $column->expression;
                }
                else {
                    $columns[$i] = $column->expression . ' AS ' . $this->db->quoteColumnName($i);
                }

                $params = array_merge($params, $column->params);
            }
            elseif ($column instanceof Query) {
                list($sql, $params) = $this->build($column, $params);

                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
            }
            elseif (is_string($i)) {
                if (strpos($column, '(') === false) {
                    $column = $this->db->quoteColumnName($column);
                }

                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
            }
            elseif (strpos($column, '(') === false) {
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
                    $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
                }
                else {
                    $columns[$i] = $this->db->quoteColumnName($column);
                }
            }
        }

        return $select . ' ' . implode(', ', $columns);
    }
986015
public function select($select, $distinct = null)
    {
        if (null !== $distinct) {
            $this->distinct($distinct);
        }

        if (empty($select)) {
            return $this;
        }

        $builder = $this->getLookupBuilder();
        $parts = [];
        if (is_array($select)) {
            foreach ($select as $key => $part) {
                if (is_string($part)) {
                    $newSelect = $builder->buildJoin($this, $part);
                    if ($newSelect) {
                        list($alias, $column) = $newSelect;
                        $parts[$key] = $alias.'.'.$column;
                    } else {
                        $parts[$key] = $part;
                    }
                } else {
                    $parts[$key] = $part;
                }
            }
        } elseif (is_string($select)) {
            $newSelect = $builder->buildJoin($this, $select);
            if ($newSelect) {
                list($alias, $column) = $newSelect;
                $parts[$alias] = $column;
            } else {
                $parts[] = $select;
            }
        } else {
            $parts[] = $select;
        }

        $this->sqlParts['select'] = $parts;

        return $this;
    }
1105776
def distinct_values_for_column(column)  #:nodoc:
      column.model.select("distinct #{column.name}").order("#{column.name} asc").collect do|ar|
        ar[column.name]
      end.reject(&:blank?).map { |i| [i, i] }
    end
720850
def add_order_by_for_association_limiting!(sql, options)
      return sql if options[:order].blank?

      order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
      order.map! {|s| $1 if s =~ / (.*)/}
      order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ')

      sql << "ORDER BY #{order}"
    end
418101
def order_by(self, field, orientation='ASC'):
        
        if isinstance(field, list):
            self.raw_order_by.append(field)
        else:
            self.raw_order_by.append([field, orientation])

        return self
143452
function selectColumnSql (model, column, spec, alias, as) {
    // if alias is not registered then this should be a table name
    if (!this.aliases[alias]) {
        // create alias from table anme
        alias = this.getAlias(alias)
    }
    // base sql is alias.`column`
    var sql = alias+'.'+this.quoteName(column)
    // if column type is id then select HEX(alias.`column`) AS `column`
    if (spec.type === 'id' && model.binaryIds) {
        sql = 'LOWER(HEX('+sql+')) as '+this.quoteName(typeof as === 'string' ? as : column)
    }
    // if column type is data and compression then select
    // BASE_64(alias.`column`) AS `column`
    else if (spec.type === 'data' && model.compression) {
        sql = 'TO_BASE64('+sql+') as '+this.quoteName(typeof as === 'string' ? as : column)
    }
    // return column sql
    return sql
}
1314335
function _parse_select_order(ObjType, document_type, order, q, traits) {

	debug.assert(ObjType).is('function');
	debug.assert(document_type).ignore(undefined).is('object');
	debug.assert(order).is('array');

	return ARRAY(order).map(function(o) {
		var key, type, rest;
		if(is.array(o)) {
			key = parse_operator_name(o[0]);
			type = parse_operator_type(o[0], 'text');
			rest = o.slice(1);
		} else {
			key = parse_operator_name(o);
			type = parse_operator_type(o, 'text');
			rest = [];
		}

		if(key === 'BIND') {
			return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
		}

		//debug.log('key = ', key);
		var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
		//debug.log('parsed_key = ', parsed_key);
		var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
		//debug.log('pgcast = ', pgcast);

		return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
	}).valueOf();
}