Sub topic 1
SOQL Syntax Basics: SELECT and FROM
Prerequisites
Assume you know basic Apex variables, lists, loops, and classes. You should also know that a Salesforce object is a type of record, such as Account, and a field stores one value on that record.
SELECT and FROM
SOQL, or Salesforce Object Query Language, reads records from Salesforce. A query names the fields to return with SELECT and the object to search with FROM.
List<Account> accounts = [
SELECT Id, Name, Industry
FROM Account
];This query returns a List<Account>. Id, Name, and Industry are the only fields loaded into each returned record. Requesting only the fields you need makes the query easier to understand and reduces work.
Running SOQL Inline in Apex
The square brackets make this an inline SOQL query. Apex runs the query and assigns its result to accounts.
for (Account account : accounts) {
System.debug(account.Name);
}A query assigned to a single sObject expects exactly one row. If no row or more than one row matches, Apex throws a QueryException. Use a list when the number of matches is uncertain.
flowchart TD
A["Apex code"] --> B["SOQL query"]
B --> C["Salesforce records"]
C --> D["List<Account>"]Filtering Records with WHERE
WHERE limits the rows returned. Text values use single quotes. Operators include =, !=, >, <, >=, and <=.
List<Account> technologyAccounts = [
SELECT Id, Name
FROM Account
WHERE Industry = 'Technology'
];Using Bind Variables
A bind variable inserts an Apex variable's value into a static query. Put a colon before the variable name.
String industry = 'Energy';
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Industry = :industry
];Binding avoids building query text by string concatenation and is safer when values come from users or other external input.
Sorting and Limiting Results
ORDER BY sorts rows. Add ASC for ascending order or DESC for descending order. LIMIT restricts the number of rows.
List<Account> firstTen = [
SELECT Id, Name
FROM Account
WHERE Industry = :industry
ORDER BY Name ASC
LIMIT 10
];Exercise
Which clause filters records, and which clause limits the number of returned rows?
Show answer
WHERE filters records. LIMIT restricts the number of returned rows.