Intermediate
30 min read
Query the Catalog
By the end of this lesson, you'll be able to:
- Write SOQL queries inside LibraryService to answer real catalog questions
- Query only available (not checked out) books
- Return query results in a form useful to a caller
Prerequisites: "Build the Core Classes"
Listing every book
public List<Book__c> getAllBooks() {
return [SELECT Id, Title__c, Author__c, Is_Checked_Out__c FROM Book__c ORDER BY Title__c];
}
public List<Book__c> getAllBooks() {— the simplest catalog-browsing method, and the foundation the next two build on.return [SELECT Id, Title__c, Author__c, Is_Checked_Out__c FROM Book__c ORDER BY Title__c];— sorted alphabetically by title (Module 20'sORDER BY).}— closes the method.
Filtering to available books only
public List<Book__c> getAvailableBooks() {
return [
SELECT Id, Title__c, Author__c
FROM Book__c
WHERE Is_Checked_Out__c = false
ORDER BY Title__c
];
}
public List<Book__c> getAvailableBooks() {— answers "what can a member actually borrow right now?" directly.return [— opens the query.SELECT Id, Title__c, Author__c— the fields needed.FROM Book__c— the object.WHERE Is_Checked_Out__c = false— this is Module 20'sWHEREclause, without pulling every book and filtering in Apex afterward.ORDER BY Title__c— sorted alphabetically.];— closes the query.}— closes the method.
Finding books by a specific author
public List<Book__c> getBooksByAuthor(String authorName) {
return [
SELECT Id, Title__c, Author__c
FROM Book__c
WHERE Author__c = :authorName
ORDER BY Title__c
];
}
public List<Book__c> getBooksByAuthor(String authorName) {— takes the author name as a parameter.return [— opens the query.SELECT Id, Title__c, Author__c— the fields needed.FROM Book__c— the object.WHERE Author__c = :authorName—:authorNameis Module 20's bind variable pattern — the value flows straight into the query safely, without any raw string concatenation.ORDER BY Title__c— sorted alphabetically.];— closes the query.}— closes the method.
Exercise
Add a getCheckedOutBooks() method to LibraryService querying Book__c where Is_Checked_Out__c is true.
Show hint
WHERE Is_Checked_Out__c = true
Query the Catalog 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
This lesson adds catalog-browsing methods to LibraryService, using the SOQL patterns from Module 20 to answer real questions like "which books are available right now?"