Intermediate 20 min read

Sorting and Limiting Results

By the end of this lesson, you'll be able to:

  • Sort query results using ORDER BY
  • Cap the number of returned records using LIMIT
  • Combine ORDER BY and LIMIT to get "the top N" of something

Prerequisites: "Filtering with WHERE"

Sorting with ORDER BY

List<Opportunity> opportunities = [
    SELECT Id, Name, Amount FROM Opportunity
    ORDER BY Amount DESC
];
  1. List<Opportunity> opportunities = [ — opens the query.
  2. SELECT Id, Name, Amount FROM Opportunity — the fields and object.
  3. ORDER BY Amount DESC — sorts the largest opportunities first; ASC (the default if omitted) sorts smallest first — this is the SOQL-side equivalent of Module 15's sort() method, applied before the data even leaves the database.
  4. ]; — closes the query.

Capping results with LIMIT

List<Opportunity> someOpportunities = [
    SELECT Id, Name FROM Opportunity
    LIMIT 10
];
  1. List<Opportunity> someOpportunities = [ — opens the query.
  2. SELECT Id, Name FROM Opportunity — the fields and object.
  3. LIMIT 10 — caps the query at 10 records, regardless of how many actually match — useful both for genuinely wanting only a few results, and as a safety net against accidentally querying far more data than intended.
  4. ]; — closes the query.

Combining both: "top N"

List<Opportunity> topFiveDeals = [
    SELECT Id, Name, Amount FROM Opportunity
    ORDER BY Amount DESC
    LIMIT 5
];
  1. List<Opportunity> topFiveDeals = [ — opens the query.
  2. SELECT Id, Name, Amount FROM Opportunity — the fields and object.
  3. ORDER BY Amount DESC — sort largest-to-smallest first.
  4. LIMIT 5 — then take only the first 5 — this pattern answers "what are the 5 biggest opportunities?" directly in the query itself, without pulling every record into Apex and sorting/trimming there.
  5. ]; — closes the query.

Exercise

Write a query for the 3 most recently created Accounts (use ORDER BY CreatedDate DESC and LIMIT 3).

Show hint

ORDER BY CreatedDate DESC LIMIT 3

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Sorting and Limiting Results Quiz

1. What does ORDER BY Amount DESC do?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

ORDER BY controls the sequence results come back in; LIMIT caps how many records a query returns — together, the standard way to answer "give me the top N."