/Drupal 8

public function SelectExtender::orderBy

public SelectExtender::orderBy($field, $direction = 'ASC')

Orders the result set by a given field.

If called multiple times, the query will order by each specified field in the order this method is called.

If the query uses DISTINCT or GROUP BY conditions, fields or expressions that are used for the order must be selected to be compatible with some databases like PostgreSQL. The PostgreSQL driver can handle simple cases automatically but it is suggested to explicitly specify them. Additionally, when ordering on an alias, the alias must be added before orderBy() is called.


$field: The field on which to order. The field is escaped for security so only valid field and alias names are possible. To order by an expression, add the expression with addExpression() first and then use the alias to order on.

Example: <code> $query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field'); $query->orderBy('order_field', 'ASC'); </code>

$direction: The direction to sort. Legal values are "ASC" and "DESC". Any other value will be converted to "ASC".

Return value

\Drupal\Core\Database\Query\SelectInterface The called object.

Overrides SelectInterface::orderBy


core/lib/Drupal/Core/Database/Query/SelectExtender.php, line 388


The base extender class for Select queries.




public function orderBy($field, $direction = 'ASC') {
  $this->query->orderBy($field, $direction);
  return $this;

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.