---
title: "Sort Query Results"
url: "https://docs.ravendb.net/6.2/client-api/session/querying/sort-query-results"
version: "6.2"
language: "php"
---

# Sort Query Results

> Client language: PHP. Also available for [C#](https://docs.ravendb.net/6.2/client-api/session/querying/sort-query-results.md), [Python](https://docs.ravendb.net/6.2/client-api/session/querying/sort-query-results.python.md), [Node.js](https://docs.ravendb.net/6.2/client-api/session/querying/sort-query-results.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - When making a query, the server will return the results **sorted** only if explicitly requested by the query.  
>   If no sorting method is specified when issuing the query then results will not be sorted.
>
>   - Note: An exception to the above rule is when [Boosting](https://docs.ravendb.net/6.2/indexes/boosting.php.md) is involved in the query.  
>     Learn more in [Automatic score-based ordering](https://docs.ravendb.net/6.2/indexes/boosting.php.md#automatic-score-based-ordering).
>
> - Sorting is applied by the server after the query filtering stage.  
>   Applying filtering is recommended as it reduces the number of results RavenDB needs to sort  
>   when querying a large dataset.
>
> - Multiple sorting actions can be chained.
>
> - This article provides examples of sorting query results when making a **dynamic-query**.  
>   For sorting results when querying a **static-index** see [sort index query results](https://docs.ravendb.net/6.2/indexes/querying/sorting.php.md).
>
> - In this page:
>   - [Order by field value](#order-by-field-value)
>   - [Order by score](#order-by-score)
>     - [Get resulting score](#get-resulting-score)
>   - [Order by random](#order-by-random)
>   - [Order by spatial](#order-by-spatial)
>   - [Order by count (aggregation query)](#order-by-count-aggregation-query)
>   - [Order by sum (aggregation query)](#order-by-sum-aggregation-query)
>   - [Force ordering type](#force-ordering-type)
>   - [Chain ordering](#chain-ordering)
>   - [Custom sorters](#custom-sorters)
>   - [Syntax](#syntax)

## Order by field value

- Use `orderBy` or `orderByDescending` (see below) to order the results by the specified document field.

- The query is served by an auto-index that includes the sorted field, even when no filtering is applied.  
  For example, `from Employees order by FirstName` uses an auto-index that includes `FirstName`, creating one if needed.  
  Learn more in [Query a collection - with filtering or sorting](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.php.md#dynamicQuery).

### Query

```php
/** @var array<Product> $products */
$products = $session
  // Make a dynamic query on the Products collection
  ->query(Product::class)
  // Apply filtering (optional)
  ->whereGreaterThan("UnitsInStock", 10)
  // Call 'OrderBy', pass the document-field by which to order the results
  ->orderBy("UnitsInStock")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value in ascending order,
// with smaller values listed first.
```

### DocumentQuery

```php
/** @var array<Product> $products */
$products = $session->advanced()
  // Make a DocumentQuery on the Products collection
  ->documentQuery(Product::class)
  // Apply filtering (optional)
  ->whereGreaterThan("UnitsInStock", 10)
  // Call 'OrderBy', pass the document-field by which to order the results
  ->orderBy("UnitsInStock")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value in ascending order,
// with smaller values listed first.
```

### RQL

```sql
from "Products"
where UnitsInStock > 10
order by UnitsInStock as long
```

> **Info**
>
> **Ordering Type**:
>
> - By default, the `orderBy` methods will determine the `OrderingType` from the property path expression  
>   and specify that ordering type in the generated RQL that is sent to the server.
>
> - E.g. in the above example, ordering by `UnitsInStock` will result in `OrderingType::long`  
>   because this property's data type is integer.
>
> - Different ordering can be forced - see [Force ordering type](#force-ordering-type) below.

## Order by score

- When querying with some filtering conditions, a basic score is calculated for each item in the results  
  by the underlying indexing engine. (Read more about Lucene scoring [here](https://lucene.apache.org/core/3_3_0/scoring.html)).

- The higher the score value the better the match.

- Use `orderByScore` to order the query results by this score.

### Query

```php
/** @var array<Product> $products */
$products = $session
  ->query(Product::class)
  // Apply filtering
  ->whereLessThan("UnitsInStock", 5)
  ->orElse()
  ->whereEquals("Discontinued", true)
  // Call 'orderByScore'
  ->orderByScore()
  ->toList();

// Results will be sorted by the score value
// with best matching documents (higher score values) listed first.
```

### DocumentQuery

```php
/** @var array<Product> $products */
$products = $session->advanced()
  ->documentQuery(Product::class)
  // Apply filtering
  ->whereLessThan("UnitsInStock", 5)
  ->orElse()
  ->whereEquals("Discontinued", true)
  // Call 'orderByScore'
  ->orderByScore()
  ->toList();

// Results will be sorted by the score value
// with best matching documents (higher score values) listed first.
```

### RQL

```sql
from "Products"
where UnitsInStock < 5 or Discontinued == true
order by score()
```

> **Info**
>
> #### Get resulting score:
>
> The score details can be retrieved by either:
>
> - **Request to include explanations**:  
>   You can get the score details and see how it was calculated by requesting to include explanations in the query.
>   Currently, this is only available when using Lucene as the underlying indexing engine.  
>   Learn more in [Include query explanations](https://docs.ravendb.net/6.2/client-api/session/querying/debugging/include-explanations.php.md).
>
> - **Get score from metadata**:  
>   The score is available in the `INDEX_SCORE` metadata property within each result.  
>   The following example shows how to get the score from the metadata of the resulting entities that were loaded to the session:
>
> ```php
> // Make a query:
> // =============
>
> $employees = $session
>   ->query(Employee::class)
>   ->search("Notes", "English")
>   ->search("Notes", "Italian")
>   ->boost(10)
>   ->toList();
>
> // Get the score:
> // ==============
>
> // Call 'GetMetadataFor', pass an entity from the resulting employees list
> $metadata = $session->advanced()->getMetadataFor($employees[0]);
>
> // Score is available in the 'INDEX_SCORE' metadata property
> $score = $metadata[DocumentsMetadata::INDEX_SCORE];
> ```

## Order by random

- Use `randomOrdering` to randomize the order of the query results.

- An optional seed parameter can be passed.

### Query

```php
/** @var array<Product> $products */
$products = $session->query(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Call 'randomOrdering'
  ->randomOrdering()
  // An optional seed can be passed, e.g.:
  // ->randomOrdering('someSeed')
  ->toList();

// Results will be randomly ordered.
```

### DocumentQuery

```php
/** @var array<Product> $products */
$products = $session->advanced()
  ->documentQuery(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Call 'randomOrdering'
  ->randomOrdering()
  // An optional seed can be passed, e.g.:
  // ->randomOrdering('someSeed')
  ->toList();

// Results will be randomly ordered.
```

### RQL

```sql
from "Products"
where UnitsInStock > 10
order by random()
// order by random(someSeed)
```

## Order by spatial

- If your data contains geographical locations,  
  spatial query results can be sorted based on their distance from a specific point.

- See detailed explanation in [Spatial Sorting](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#spatial-sorting).

## Order by count (aggregation query)

- The results of a [group-by query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-group-by-query.php.md) can be sorted by the `Count` aggregation operation used in the query.

### Query

```php
$numberOfProductsPerCategory = $session
  ->query(Product::class)
  // Make an aggregation query
  ->groupBy("Category")
  ->selectKey("Category")
  // Count the number of product documents per category
  ->selectCount()
  // Order by the Count value
  // Here you need to specify the ordering type explicitly
  ->orderBy("Count", OrderingType::long())
  ->toList();

// Results will contain the number of Product documents per category
// ordered by that count in ascending order.
```

### DocumentQuery

```php
$numberOfProductsPerCategory = $session->advanced()
  ->documentQuery(Product::class)
  // Group by Category
  ->groupBy("Category")
  ->selectKey("Category")
  // Count the number of product documents per category
  ->selectCount()
  // Order by the Count value
  // Here you need to specify the ordering type explicitly
  ->orderBy("Count", OrderingType::long())
  ->toList();

// Results will contain the number of Product documents per category
// ordered by that count in ascending order.
```

### RQL

```sql
from "Products"
group by Category
order by count() as long
select key() as "Category", count()
```

## Order by sum (aggregation query)

- The results of a [group-by query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-group-by-query.php.md) can be sorted by the `Sum` aggregation operation used in the query.

### Query

```php
$numberOfUnitsInStockPerCategory = $session
  ->query(Product::class)
  // Make an aggregation query
  // Group by Category
  ->groupBy("Category")
  // Order by the Sum value
  ->selectKey("Category")
  ->selectSum(new GroupByField("UnitsInStock", "Sum"))
  ->orderBy("Sum")
  ->toList();

// Results will contain the total number of units in stock per category
// ordered by that number in ascending order.
```

### DocumentQuery

```php
$numberOfUnitsInStockPerCategory = $session->advanced()
  ->documentQuery(Product::class)
  // Group by Category
  ->groupBy("Category")
  ->selectKey("Category")
  // Sum the number of units in stock per category
  ->selectSum(new GroupByField("UnitsInStock", "Sum"))
  // Order by the Sum value
  // Here you need to specify the ordering type explicitly
  ->orderBy("Sum", OrderingType::long())
  ->toList();

// Results will contain the total number of units in stock per category
// ordered by that number in ascending order.
```

### RQL

```sql
from "Products"
group by Category
order by Sum as long
select key() as 'Category', sum(UnitsInStock) as Sum
```

## Force ordering type

- By default, the `orderBy` methods will determine the `OrderingType` from the property path expression  
  and specify that ordering type in the generated RQL that is sent to the server.

- A different ordering can be forced by passing the ordering type explicitly to `orderBy` or `orderByDescending`.

- The following ordering types are available:

  - `OrderingType::long`
  - `OrderingType::double`
  - `OrderingType::alphaNumeric`
  - `OrderingType::string` (lexicographic ordering)

- When using RQL directly, if no ordering type is specified, then the server defaults to lexicographic ordering.

> **Note**
>
> **Using alphanumeric ordering example**:
>
> - When ordering mixed-character strings by the default lexicographical ordering  
>   then comparison is done character by character based on the Unicode values.  
>   For example, "Abc9" will come after "Abc10" since 9 is greater than 1.
>
> - If you want the digit characters to be ordered as numbers then use alphanumeric ordering  
>   where "Abc10" will result after "Abc9".
>
> ### Query
>
> ```php
> /** @var array<Product> $products */
> $products = $session
>   ->query(Product::class)
>   // Call 'OrderBy', order by field 'QuantityPerUnit'
>   // Pass a second param, requesting to order the text alphanumerically
>   ->orderBy("QuantityPerUnit", OrderingType::alphaNumeric())
>   ->toList();
> ```
>
> ### DocumentQuery
>
> ```php
> /** @var array<Product> $products */
> $products = $session->advanced()
>   ->documentQuery(Product::class)
>   // Call 'OrderBy', order by field 'QuantityPerUnit'
>   // Pass a second param, requesting to order the text alphanumerically
>   ->orderBy("QuantityPerUnit", OrderingType::alphaNumeric())
>   ->toList();
> ```
>
> ### RQL
>
> ```sql
> from "Products"
> order by QuantityPerUnit as alphanumeric
> ```

## Chain ordering

- It is possible to chain multiple orderings in the query.  
  Any combination of secondary sorting is possible as the fields are indexed independently of one another.

- **When using the Lucene search engine** -  
  there is no limit on the number of sorting actions that can be chained in a query.

  **When using the Corax search engine** -  
  a maximum of `16` *order by* clauses is allowed per query. If this limit is exceeded, an exception will be thrown.  
  To resolve this, simplify your query or switch to the Lucene engine. See [Selecting the search engine](https://docs.ravendb.net/6.2/indexes/search-engine/corax.md#selecting-the-search-engine).

### Query

```php
/** @var array<Product> $products */
$products = $session
  ->query(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Apply the primary sort by 'UnitsInStock'
  ->orderByDescending("UnitsInStock")
  // Apply a secondary sort by the score (for products with the same # of units in stock)
  ->orderByScore()
  // Apply another sort by 'Name' (for products with same # of units in stock and same score)
  ->orderBy("Name")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value (descending),
// then by score,
// and then by 'Name' (ascending).
```

### DocumentQuery

```php
/** @var array<Product> $products */
$products = $session->advanced()
  ->documentQuery(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Apply the primary sort by 'UnitsInStock'
  ->orderByDescending("UnitsInStock")
  // Apply a secondary sort by the score
  ->orderByScore()
  // Apply another sort by 'Name'
  ->orderBy("Name")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value (descending),
// then by score,
// and then by 'Name' (ascending).
```

### RQL

```sql
from "Products"
where UnitsInStock > 10
order by UnitsInStock as long desc, score(), Name
```

## Custom sorters

- The Lucene indexing engine allows you to create your own custom sorters.  
  Custom sorters can be deployed to the server by either:

  - Sending the [Put Sorters Operation](https://docs.ravendb.net/6.2/client-api/operations/maintenance/sorters/put-sorter.md) from your code.

  - Uploading a custom sorter from Studio, see [Custom Sorters View](https://docs.ravendb.net/6.2/studio/database/settings/custom-sorters.md).

- Once the custom sorter is deployed, you can sort the query results with it.

### Query

```php
/** @var array<Product> $products */
$products = $session
  ->query(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Order by field 'UnitsInStock', pass the name of your custom sorter class
  ->orderBy("UnitsInStock", "MySorter")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value
// according to the logic from 'MySorter' class
```

### DocumentQuery

```php
/** @var array<Product> $products */
$products = $session->advanced()
  ->documentQuery(Product::class)
  ->whereGreaterThan("UnitsInStock", 10)
  // Order by field 'UnitsInStock', pass the name of your custom sorter class
  ->orderBy("UnitsInStock", "MySorter")
  ->toList();

// Results will be sorted by the 'UnitsInStock' value
// according to the logic from 'MySorter' class
```

### RQL

```sql
from "Products"
where UnitsInStock > 10
order by custom(UnitsInStock, "MySorter")
```

## Syntax

```php
/**
* Usage:
*   - orderBy("lastName"); // same as call: orderBy("lastName", OrderingType::string())
*   - orderBy("lastName", OrderingType::string());
*
*   - orderBy("units_in_stock", "MySorter");
*     // Results will be sorted by the 'units_in_stock' value according to the logic from 'MySorter' class
*/
function orderBy(string $field, $sorterNameOrOrdering = null): DocumentQueryInterface;

/**
* Usage:
*   - orderByDescending("lastName"); // same as call: orderBy("lastName", OrderingType::string())
*   - orderByDescending("lastName", OrderingType::string());
*
*   - orderByDescending("units_in_stock", "MySorter");
*     // Results will be sorted by the 'units_in_stock' value according to the logic from 'MySorter' class
*/
function orderByDescending(string $field, $sorterNameOrOrdering = null): DocumentQueryInterface;
```

| Parameter | Type | Description |
| - | - | - |
| **$field** | `string` | The field to sort by |
| **$sorterNameOrOrdering** | `string` | The ordering type to sort the results by:<br />`OrderingType::long`<br />`OrderingType::double`<br />`OrderingType::alphaNumeric`<br />`OrderingType::string` (default) |

## See also

- [Query Overview](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.php.md)
- [Customize query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-customize-query.php.md)
- [Group by query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-group-by-query.php.md)
- [Spatial query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md)
- [Full-text search](https://docs.ravendb.net/6.2/client-api/session/querying/text-search/full-text-search.php.md)
