On this page
Ordering and limiting
This documentation needs review. See "Help improve this page" in the sidebar.
Ordering
To add an order to the dynamic query, use the orderBy() method:
$query->orderBy('timestamp');
By default, this creates an ascending order on the given field. To add a descending order, specify the second parameter:
$query->orderBy('timestamp', 'DESC');
If called multiple times, the query will order by each specified field in the order this method is called. To order by an expression, add the expression with addExpression() first and then use the alias to order on.
To get the results in a random order, use the orderRandom() method:
$query->orderRandom();
EntityStorageInterface Queries
The order() and orderRandom() methods may not be available in queries generated from EntityTypeManager. Use sort() instead.
$storage = $this->entityTypeManager->getStorage('node');
$query = $storage->getQuery();
$query->condition('type', 'page')
->condition('status', 1)
->sort('title', 'ASC');
Limiting
By using the range() method, you can control the range of selectable records. The method has two parameters: the first is the start position of the range, and the second is the number of selectable records from the beginning of the range.
// Limit the result to 10 records
// where 0 is offset and 10 is limit
$query->range(0, 10);
The following example will instruct the result set to start at the 6th record found (the count starts at 0) rather than the first and to return only 10 records.
$query->range(5, 10);
Calling the range() method a second time will overwrite previous values. Calling it with no parameters will remove all range restrictions on the query.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.