Intermediate 15 min read

What Is SOQL?

By the end of this lesson, you'll be able to:

  • Explain what SOQL is and how it differs from a general-purpose query language like SQL
  • Write an inline SOQL query and store its result
  • Recognize that a SOQL query always returns a List of sObjects

Prerequisites: Module 19: "DML: Changing Data Safely"

Reading data, not writing it

Module 19 covered how Apex writes changes to the database — insert, update, delete. SOQL is the other half: how Apex reads data back out. Every [SELECT ... FROM ...] you write anywhere in this course is a SOQL query.

A query always returns a List

List<Account> accounts = [SELECT Id, Name FROM Account];
System.debug(accounts.size());
  1. List<Account> accounts = [SELECT Id, Name FROM Account]; — even a query that matches exactly one record — or zero — still returns a List<Account>, not a single Account directly. This is exactly Module 15's List type.
  2. System.debug(accounts.size()); — logs however many records matched, and it's why looping over a query result with an enhanced for loop (Module 7) is such a natural, constant pattern in Apex.

SOQL vs a general-purpose SQL

SOQL looks a lot like SQL, but it's deliberately more limited: it always queries a single object's relationships in one statement (no arbitrary joins across unrelated tables), and it always respects the running user's actual data access permissions unless explicitly told not to (a later Security module covers this). SOQL is purpose-built for querying Salesforce's specific data model, not a general-purpose database language.

Exercise

Write a SOQL query selecting Id and Name from every Account, and debug how many were returned.

Show hint

[SELECT Id, Name FROM Account]

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

What Is SOQL? Quiz

1. What does a SOQL query always return, even if it matches only one record?

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

SOQL (Salesforce Object Query Language) is how Apex reads data. Inline queries are written directly in square brackets inside your Apex code and return a List of sObjects.