Intermediate
20 min read
Your First SOQL Query
By the end of this lesson, you'll be able to:
- Write a SOQL query selecting specific fields
- Assign a single-record query result directly to a variable of that type
- Explain why selecting only needed fields matters
Prerequisites: "What Is SOQL?"
The basic shape
List<Contact> contacts = [SELECT Id, FirstName, LastName, Email FROM Contact];
List<Contact> contacts = [SELECT Id, FirstName, LastName, Email FROM Contact];—SELECTlists exactly which fields to retrieve;FROMnames the object. Only the fields listed here are populated on each returned record — trying to read a field you didn't select throws a runtime error.
Assigning a single-record result directly
Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Acme Logistics' LIMIT 1];
System.debug(acc.Name);
Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Acme Logistics' LIMIT 1];— when you know a query returns exactly one record (often paired withLIMIT 1, covered soon), it can be assigned directly to a singleAccountvariable instead of aList<Account>— but if the query actually returns zero or more than one record, this throws a runtime exception.System.debug(acc.Name);— safe here, since exactly one record matched.
Why selecting only needed fields matters
// Wasteful: selects every field on the object
List<Account> accounts = [SELECT FIELDS(ALL) FROM Account LIMIT 10];
// Better: select only what this code actually uses
List<Account> accounts = [SELECT Id, Name, Industry FROM Account LIMIT 10];
// Wasteful: selects every field on the object— the label for the anti-pattern.List<Account> accounts = [SELECT FIELDS(ALL) FROM Account LIMIT 10];— selecting unused fields costs real query performance.- (blank line)
// Better: select only what this code actually uses— the label for the good pattern.List<Account> accounts = [SELECT Id, Name, Industry FROM Account LIMIT 10];— exactly the "read it out loud" clarity habit from Module 14, applied to SOQL: a query'sSELECTclause should read like a list of exactly what the code below actually needs.
Exercise
Write a SOQL query that selects Id, Name, and Industry from Account where the Name is 'Acme Logistics', limited to 1 result, assigned directly to a single Account variable.
Show hint
Account acc = [SELECT ... WHERE Name = 'Acme Logistics' LIMIT 1];
Your First SOQL Query 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
A basic SOQL query names the fields you want and the object to query them from — the SELECT and FROM clauses form the backbone of every query you'll ever write.