Salesforce Object Query Language (SOQL)
SOQL stands for Salesforce Object Query Language. SOQL can be used to access information stored in your salesforce database. The syntax of SOQL is similar to that of SQL (Structured Query Language).
SOQL queries can be executed from apex code, Visual studio code or in the Query Editor of the Developer Console.
Note
SOQL queries can only retrieve records from a single sObject if they meet the specified criteria.
Syntax of SOQL
[ SELECT Id, Name FROM Opportunity WHERE StageName = 'Prospecting' ORDER BY Name ASC LIMIT 10 ];
A SOQL query begins with the SELECT statement, followed by the fields you want to retrieve. The FROM keyword specifies the object (or table) where the data is coming from.
You can also use optional keywords like WHERE for filters, ORDER BY for sorting, and LIMIT to restrict the number of results.
Following is an example of a simple SOQL query in apex:
In the above example:
- The SOQL query is enclosed in square brackets, starts with
[
and ends with a];
- The query statement starts with a
SELECT
keyword, followed by a set of comma-separated fields (e.g. id, name) that you want to query from an object. - The
FROM
keyword indicates the object (table) from which data is going to be queried from salesforce.
Note
The SOQL query always returns a list of records unless you use a LIMIT statement to return only one record, or if it’s an aggregate query.