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];

SELECT lists exactly which fields to retrieve; FROM names 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, reinforcing the habit of listing every field you'll actually use.

Assigning a single-record result directly

Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Acme Logistics' LIMIT 1];
System.debug(acc.Name);

When you know a query returns exactly one record (often paired with LIMIT 1, covered soon), you can assign it directly to a single Account variable instead of a List<Account> — but if the query actually returns zero or more than one record, this throws a runtime exception, so it's only safe when you're certain of the count.

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];

Selecting unused fields costs real query performance and makes the intent of the query less clear to a reader — exactly the "read it out loud" clarity habit from Module 14, applied to SOQL: a query's SELECT clause 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];

APEX

Your First SOQL Query Quiz

1. What happens if you try to read a field that wasn't included in a SOQL query's SELECT clause?

Log in to submit the quiz and save your score.

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.