Ordering

Last updated on
14 October 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Ordering

To add an order by clause to a dynamic query, use the chainable orderBy() method:

$query->orderBy('title', 'DESC')
  ->orderBy('node.created', 'ASC');

The above code will instruct the query to sort by the title field in descending order and then the created field in ascending order. The second parameter may be either "ASC" or "DESC" for ascending or descending, respectively, and defaults to "ASC". The field name here should be the alias created by the addField() or addExpression() methods, so you may want to use the return value from those methods here to guarantee the correct alias is used. To order by multiple fields, simply call orderBy() multiple times in the order desired.

Random ordering

Random ordering of queries requires slightly different syntax on different databases. Therefore, that is best handled by a dynamic query.

To indicate that a given query should order randomly, call the orderRandom() method on it.

$query->orderRandom();

Note that orderRandom() is chainable, and stackable with orderBy(). That is, it is safe to do something like the following:

$query->orderBy('term')->orderRandom()->execute();

The above would order first by the "term" field of the query and then, for records that have the same term, order randomly.

Help improve this page

Page status: No known problems

You can: