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
];
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.
Capping results with LIMIT
List<Opportunity> someOpportunities = [
SELECT Id, Name FROM Opportunity
LIMIT 10
];
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.
Combining both: "top N"
List<Opportunity> topFiveDeals = [
SELECT Id, Name, Amount FROM Opportunity
ORDER BY Amount DESC
LIMIT 5
];
Sort largest-to-smallest, 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.
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
Sorting and Limiting Results Quiz
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."