Sub topic 1
SOQL Syntax Basics: SELECT and FROM
SOQL (Salesforce Object Query Language) reads records from Salesforce objects. This chapter covers the two clauses every query needs, SELECT and FROM, and the rules that decide whether a query compiles and returns what you expect.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax: variables, collections, loops, and classes.
- The Salesforce data model: objects, fields, and lookup and master-detail relationships.
- How to run Apex in the Developer Console or an IDE, for example with Anonymous Apex.
Later chapters cover filtering, relationships, and limits. Here you only need to read fields from one object.
What SOQL Is and Is Not
SOQL looks like SQL, but it is narrower. It is built for Salesforce's object model, and several SQL features do not exist in it.
| Feature | SQL | SOQL |
|---|---|---|
| Select all columns with `*` | Supported | Not supported. You name each field. |
| Joins | `JOIN ... ON` | No explicit joins. You follow relationships by name. |
| Write data | `INSERT`, `UPDATE`, `DELETE` | Read-only. You use DML statements in Apex. |
| Table names | Any table | Standard and custom objects, such as `Account` and `Invoice__c` |
SOQL only reads data. To change records, you query them first and then use DML such as insert or update.
The Shape of a Query
The smallest useful query has two parts.
SELECTlists the fields to return.FROMnames the one object to read.
SELECT field1, field2, ... FROM ObjectNameYou use the API names of fields and objects, not their labels. A custom field ends in __c, so Annual Revenue becomes AnnualRevenue and a custom field called "Region" becomes Region__c. SOQL keywords and names are not case-sensitive, so select id from account works. The usual style is uppercase keywords and exact API-name casing.
A query can only read from one object at a time. Data from related objects comes through relationship names, which a later chapter covers.
Running a Query Inline in Apex
In Apex you write SOQL in square brackets. The compiler checks the query when you save the class, so a misspelled field or object is a compile-time error and not a runtime surprise.
List<Account> accts = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 10
];
for (Account a : accts) {
System.debug(a.Name + ' - ' + a.Industry);
}This example uses WHERE, ORDER BY, and LIMIT, which later chapters explain. Focus on the first two lines of the query. SELECT Id, Name, Industry picks three fields, and FROM Account picks the object. The result is a List<Account>, where each element is one Account record holding only the selected fields.
The diagram below shows how the pieces fit together.
Choosing Fields
Only the fields in the SELECT list are populated on the returned records. Reading a field you did not select fails at runtime.
Account a = [SELECT Id, Name FROM Account LIMIT 1];
System.debug(a.Name); // works
System.debug(a.Industry); // throws System.SObjectExceptionThe error is SObjectException: SObject row was retrieved via SOQL without querying the requested field. The fix is to add the field to the SELECT list.
Some points about field lists:
Idis always returned for an object query, even when you leave it out. Include it anyway, because the code is then clear about what it uses.- Select only what you need. Extra fields cost heap memory and transfer time, and wide queries on large objects slow down.
- Fields are separated by commas. A trailing comma before
FROMis a syntax error. - Field order does not matter to the result. You access fields by name.
- You cannot repeat a field in the same list.
SELECT Name, Name FROM Accountis an error.
FIELDS() as a Shortcut
SOQL has no *, but it has a FIELDS() function with three forms: FIELDS(STANDARD), FIELDS(CUSTOM), and FIELDS(ALL). In Apex, FIELDS(STANDARD) works without a limit. FIELDS(ALL) and FIELDS(CUSTOM) need a LIMIT of 200 or less, and Apex restricts them in some contexts. Treat FIELDS() as a tool for exploring data in the Developer Console or Query Editor. In production code, list the fields you use.
Counting Records
SELECT COUNT() returns the number of matching rows as an Integer. It does not return records, so there are no fields to list.
Integer total = [SELECT COUNT() FROM Account];
System.debug('Accounts: ' + total);Use this form when you need only the count. It is cheaper than querying all records into a list and calling size(). Aggregates with GROUP BY are a separate topic.
Single Record or List
The type on the left of the assignment controls what the query returns.
| Assigned to | Returns | If no row matches | If more than one row matches |
|---|---|---|---|
| `List<Account>` | A list | Empty list | List with all rows |
| `Account` | One record | `QueryException` | `QueryException` |
| `Integer` with `COUNT()` | A number | `0` | The count |
Assigning to a single record is a common source of runtime errors. If you are not certain exactly one row will match, query into a list and check it.
List<Account> accts = [
SELECT Id, Name FROM Account WHERE Name = 'No Such Account' LIMIT 1
];
if (!accts.isEmpty()) {
System.debug(accts[0].Id);
}
// Assigning directly to a single record throws a QueryException when no row matches:
// Account a = [SELECT Id FROM Account WHERE Name = 'No Such Account' LIMIT 1];
Integer total = [SELECT COUNT() FROM Account];Chapter on handling results covers this in more depth. For now, default to lists.
Naming the Object in FROM
FROM takes the API name of one object.
- Standard objects use their plain names:
Account,Contact,Opportunity,Case. - Custom objects end in
__c, such asInvoice__c. - Objects from managed packages carry a namespace prefix, such as
acme__Invoice__c.
You can give the object an alias, which becomes useful in relationship queries.
List<Account> accts = [SELECT a.Id, a.Name FROM Account a LIMIT 5];The alias is optional here and has no effect on the results. Do not use SOQL reserved words such as Group or Order as aliases.
Common Errors
| Error message | Likely cause | Fix |
|---|---|---|
| `sObject type 'Acount' is not supported` | Misspelled object name, or the object is not accessible | Check the API name in Object Manager |
| `No such column 'Industy' on entity 'Account'` | Misspelled field name, or the field does not exist on that object | Check the API name and the object |
| `unexpected token: 'FROM'` | A trailing comma, or an empty field list | Remove the comma and list at least one field |
| `SObject row was retrieved via SOQL without querying the requested field` | Reading a field not in `SELECT` | Add the field to the query |
| `List has no rows for assignment to SObject` | A single-record query matched nothing | Query into a list and check `isEmpty()` |
Inline queries in Apex are checked at compile time, so the first three errors show up when you save the class. The last two appear when the code runs.
Exercises
Exercise
This code throws an exception at runtime. What is the cause, and how do you fix it? Contact c = [SELECT Id, LastName FROM Contact LIMIT 1]; System.debug(c.Email);
Show answer
The query did not select Email, so the field is not populated on the record. Reading it throws an SObjectException. Add Email to the SELECT list: SELECT Id, LastName, Email FROM Contact LIMIT 1.
Exercise
You need to know how many Opportunity records exist and nothing else. Write the Apex statement, and say why it is better than querying a list and calling size().
Show answer
Integer total = [SELECT COUNT() FROM Opportunity]; It returns only the number, so the code does not load every record into heap memory.
Exercise
A query is written as Account acct = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];. Name one way it can fail and rewrite it so it cannot.
Show answer
It throws a QueryException when no account is named Acme, and also when two or more are. Query into a list instead: List<Account> accts = [SELECT Id, Name FROM Account WHERE Name = 'Acme']; then check !accts.isEmpty() before reading accts[0].