SOQL Naming Conventions

SELECT statements are used to fetch data from Salesforce by specifying which fields we want to retrieve. In addition to the fields we want to bring, we also have to tell Salesforce which Object to get. To do this we use the keyword FROM followed by the name of the Object.

Important
SOQL queries uses API names when it refers to field names and object names. </br> In case of custom fields and custom objects, the API names end with "__c"

For example, if we want to see some records in the Contact Object, we could use the following query:

SELECT Id, FirstName, LastName, MRN__c
FROM Contact

Note that only MRN (medical representative number) is written as MRN__c, meaning it is a custom field on a standard object. Id, FirstName, Lastname are standard fields and can not be appended with __c.

Now let’s take a look at SOQL on a custom object

SELECT Id, Name, Street__c, City__c , State__c
FROM Clinic__c

Note that Id, Name is a standard field created automatically for all custom objects and cannot be appended by __c. Custom fields and Custom objects are appended with __c.

Important
In SOQL, you cannot use the asterisk (*) to retrieve all object fields. You have to explicitly select the desired fields.

Combining the AND and OR Conditions

The logical_expressions which combine multiple logical operators must use parentheses to declare priority of one operator over the other. Otherwise, a syntax error is shown.

Example: Find the clinics which are either in zip code 32003 or 32004, and open on holidays.

Incorrect Query:

SELECT Id, Name
FROM clinic__c
WHERE mailingpostalcode = '32003'
OR mailingPostalCode = '32004'
AND is_open_on_holidays__c = True

Correct Query:

SELECT Id, Name
FROM clinic__c
WHERE (mailingpostalcode = '32003'
OR mailingPostalCode = '32004')
AND is_open_on_holidays__c = True

SOQL Order of execution

The SOQL order of execution defines the order in which the clauses of a query are evaluated. Some of the most common query challenges I run into could be easily avoided with a clearer understanding of the SOQL order of execution.

  1. SELECT
  2. FROM
  3. WHERE
  4. GROUP BY
  5. HAVING
  6. ORDER BY
  7. LIMIT