---
schema_version: "1"
id: 012a7dfbb830b75ab1397548a092303678fb62ca9730f9905ebebbc5bb5b58df
title: Sort Optimization on a Query
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/platform/salesforce-large-data-volumes-bp/guides/cce/ldv-deployments/ldv-deployments-case-studies-sort-optimization.md
canonical_url: https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-case-studies-sort-optimization.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: c86b1695c22a22362d1681ca6cf52cc72ff95d17d582cb6fff845c383f877e9f
products:
  - Best Practices for Deployments with Large Data Volumes
  - Platform Developer Content
---

# Sort Optimization on a Query

## Situation

The customer had the following query.

```soql
SELECT Id,Product_Code__c
FROM Customer_Product__c
WHERE CreatedDate = Last_N_Days:3
```

The query was looking for all the records created in the last three days, but the amount of data in the object exceeded the threshold for standard indexes: 30% of the total records up to one million records. The query performed poorly.

## Solution

The query was rewritten as:

```soql
SELECT Id,Product_Code__c
FROM Customer_Product__c
WHERE CreatedDate = Last_N_Days:3
ORDER BY CreatedDate LIMIT 99999
```

In this query, the threshold checks were not done, and the `CreatedDate` index was used to find the records. This kind of query returns a maximum of 99,999 records in the order that they were created within the last three days, assuming that 99,999 or fewer records were created during the last three days.

**note:** In general, when querying for data that has been added over the `Last_N_Days`, if you specify an `ORDER BY` query on an indexed field with a limit of fewer than 100,000 records, the `ORDER BY` index is used to do the query.

