Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท SOQL and DML

SOQL Basics

Learn Salesforce Object Query Language: SELECT fields FROM an object, LIMIT, inline queries in Apex, single-record queries and bind variables, with stand-ins.

SOQL (Salesforce Object Query Language) is how you read data. It looks like SQL's SELECT, but it is simpler: you can only read, you always name an object (never join tables by hand) and the language is built into Apex. Every Apex developer writes SOQL daily.

SOQL runs against a Salesforce org's database, which this site cannot provide. Real SOQL is shown read-only. The runnable examples use a small in-memory Java stand-in so you can see what a query does to a list of records.

The shape of a query

SQL
SELECT Id, Name, Industry
FROM Account
LIMIT 10
  • SELECT lists the fields to return. There is no SELECT *; you must name each field (this is deliberate, so queries stay small).
  • FROM names the object.
  • LIMIT caps how many records come back.

Keywords are case-insensitive. Id is always available and is the unique key of the record.

Queries inside Apex

Wrap a query in square brackets and assign it. The result type depends on what you assign it to:

Java
List<Account> accounts = [SELECT Id, Name, Industry FROM Account LIMIT 10];

for (Account a : accounts) {
    System.debug(a.Name + ' - ' + a.Industry);
}

This is called an inline SOQL query. The compiler checks that the object and fields exist, so a typo is a compile-time error, not a runtime surprise.

Assigning to a single record is allowed when you are certain of one row:

Java
Account one = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];

If the query returns zero rows, assignment to a single record throws System.QueryException: List has no rows for assignment to SObject. If it returns more than one, it throws another QueryException. Safer: assign to a list and check isEmpty():

Java
List<Account> found = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];
if (!found.isEmpty()) {
    Account acme = found[0];
}

Choosing fields

Query exactly what you need. Extra fields cost heap, and a field you forget throws an SObjectException when read. Some useful fields: Id, Name, CreatedDate, LastModifiedDate, OwnerId. Formula fields can be queried but not saved.

Bind variables

You can put an Apex variable inside a query with a colon. This is a bind variable, and it is also the safe way to pass user input, because the value is never treated as query text:

Java
String industry = 'Energy';
Set<Id> ids = new Set<Id>{ '001xx000003DGb2AAG' };
List<Account> a = [SELECT Id FROM Account WHERE Industry = :industry];
List<Contact> c = [SELECT Id FROM Contact WHERE AccountId IN :ids];

Bind variables can hold single values, lists or sets (for IN), and even expressions such as :acc.Id.

Counting rows

Java
Integer total = [SELECT COUNT() FROM Account];

COUNT() returns an Integer and counts as one query. More on aggregate queries in Aggregate SOQL.

Limits to remember

  • A transaction may issue 100 queries and retrieve 50,000 records in total.
  • A query without LIMIT on a large object may fail or return too much. Add filters and limits while learning.
  • Queries inside loops are the classic way to hit the 100-query limit.

A stand-in query engine in Java

To get a feel for what SELECT ... FROM ... LIMIT does, here is a tiny stand-in. It selects only the requested fields from a list of records and applies the limit. It is not SOQL and it does not parse text; it just models the result.

Java Stand-in (Java): SELECT fields, LIMIT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same stand-in shows a bind variable idea: the value is passed separately from the query structure.

Java Stand-in (Java): a bind variable keeps data out of the query

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Dynamic SOQL

Sometimes the query text is built at run time. Use Database.query() with a string, and always use bind variables or String.escapeSingleQuotes for anything that came from a user, to prevent SOQL injection:

Java
String field = 'Industry';
String sql = 'SELECT Id FROM Account WHERE ' + field + ' = :value';
List<SObject> rows = Database.query(sql);

Prefer static (inline) SOQL when you can: it is checked at compile time and shows dependencies.

Common mistakes

  • Writing SELECT *.
  • Querying inside a loop.
  • Assigning to a single record without checking for zero results.
  • Forgetting the field in the SELECT list, then reading it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is valid SOQL?

    SOQL has no wildcard. You list each field you want.
  2. 2. What happens if a query assigned to a single Account returns no rows?

    Assigning zero rows to a single SObject throws QueryException; assign to a List to avoid it.
  3. 3. What does :industry mean in a query?

    A colon before a name binds an Apex variable into the query safely.
  4. 4. How many SOQL queries can one synchronous transaction run?

    The limit is 100 queries. 50,000 is the limit on rows retrieved.

Summary

  • SOQL reads data: SELECT fields FROM an object, with an optional LIMIT.
  • There is no SELECT *; query only the fields you need.
  • Inline queries use square brackets; bind variables (:name) pass values safely.
  • Single-record assignment throws if no row or too many rows come back.
  • Respect the 100-query and 50,000-row limits.

Next: Filtering and Sorting with SOQL