Salesforce SQL: Accessing your Data Made Easy

on Data Integration, Tutorials • December 13th, 2021 • Write for Hevo

Salesforce SQL

Introduction

Customer Resource Management (CRM) is an approach to manage and interact with a company’s existing and potential customers. The goal is to improve business relationships with customers. A CRM solution helps a company to focus on the organization’s relationships with the customers which involve many important steps including finding new customers, maintaining their databases, helping them in growing their business, providing needed support, and other services.

When it comes to customer resource management software, Salesforce is one of the most used solutions by many companies. It is important to be able to access and use this CRM data in an efficient manner. Salesforce SQL lets you do just that.

Table of Contents

Introduction to Salesforce

Salesforce Logo.

According to Salesforce, over 150,000 companies are growing their businesses using this software. Few names include KFC, Godrej, CEAT, Air Asia and many more. This software also improves sales team productivity. Salesforce SQL enables you to query the data easily. There is a mobile app for both Android and iOS devices that features real-time data from dashboards and custom reports including a feed plus feature that shows you any crucial information that you want to know about. It could be anything including sales tracking, custom reports, employee performance reports, etc.

Also, there can be more functions and tools that can be added from a long list of apps in the AppExchange. Moreover, Salesforce Cloud also gives you access to real-time data. There are some AI features implemented as well that help you forecast future sales and employee performance as well.  Moreover, it can be integrated with some external business tools through Salesforce API such as Zendesk, Desk.com, FinancialForce ERP, Team Support, Zuora, and other sales and ERP solutions.  

Here are a few features which make Salesforce one of the most used software:

  • Helps you optimize the conversion rate
  • Productivity enhancement of staff
  • Intelligent and insightful reporting
  • Visual workflows for each level of employees
  • Account Management
  • Lead Management
  • Dashboards for business owners and workers alike

Simplify your data analysis with Hevo’s No-code Data Pipelines

Hevo Data, a No-code Data Pipeline, helps to transfer data from Salesforce and 100+ Sources to your desired data warehouse/ destination and visualize it in a BI Tool for free. Hevo is fully managed and completely automates the process of not only loading data from your desired source but also enriching the data and transforming it into an analysis-ready form without having to write a single line of code. Its fault-tolerant architecture ensures that the data is handled in a secure, consistent manner with zero data loss.

It provides a consistent & reliable solution to manage data in real-time and always have analysis-ready data in your desired destination. It allows you to focus on key business needs and perform insightful analysis using various BI tools such as Power BI, Tableau, etc. 

Get Started with Hevo for Free

Check out what makes Hevo amazing:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
Sign up here for a 14-Day Free Trial!

Understanding Salesforce SQL (SOQL)

Salesforce SQL

Salesforce SQL is also known as the Salesforce Object Query Language (SOQL). We can use SOQL to search for the organization’s Salesforce data for some specific information. Both SQL and SOQL allow you to specify a source object by using the SELECT statement. Additionally, Salesforce SQL uses filters along with the SELECT clause to return an optional set of data. 

The return type of SOQL is always a list of <sObjects>. If we are making a SOQL query on an accounts object, it will return a list of accounts and if we are making a SOQL query on a contacts object, it will return a list of contacts. In short, if we are making a SOQL query on a custom object, it will return a list of custom objects. Moving forward, SOQL does not support advanced features of SQL like * and joins. For example, we cannot do “SELECT * ” to perform a selection of all the values. 

So now the question is when to use SOQL?

  • To retrieve data from a single object or multiple objects that are related to one another. 
  • Count the number of records that meet specified criteria.
  • Sort results as a part of the query e.g. you want the data in ascending or descending order. 
  • Retrieve data from number, date, or checkbox fields. 

Simple/Basic SOQL Structure

SELECT one or more fields, [SubQuery]
FROM an object
WHERE filter statements
GROUP BY
HAVING count(Email) > 2
ORDER BY CreatedDate ASC
LIMIT 10 
OFFSET 5
FOR {VIEW, UPDATE}

Different Types of SOQL Queries

We will look into the following SOQL clauses:

Child to Parent

When you want to fetch a few fields of the parent record while working with the child record then you can go for the child to parent query. For example, if while working with “Contacts” records user needs the “Account Shipping Address” then for this use case, Salesforce SQL will look like this:

SELECT ID, NAME, AccountId, Account.ShippingAddress FROM Contact

In the above SOQL, “Account” is the field name for lookup/master details on the contact (child) object.    

Parent to Child (Inner Query)

Whenever you want to retrieve the related/child record for a particular parent record or a set of parent records then you can use the concept of the inner query.

For example, to retrieve the Contacts related to a particular Account we will be using below SOQL:

SELECT Id, Name, (Select Id, Name From Contacts) FROM Account WHERE ID IN: accList 

In the above query, “Contacts” is the relationship name. For a standard object, it will always be the plural label of the object name. For example, 

Contact => Contacts, Case => Cases, Number => Numbers

For custom objects, we will append “_r” which will represent the relationship. For example, if the custom object name is “Book” and it has a lookup relationship with “Account” then in the inner query, it is represented as Books_r. r represents a relationship.     

Order By in SOQL

We can use ORDER BY in a SELECT statement of a SOQL query to control the order of query results. By default, the order is ascending. There is no guarantee of the order of the result unless we use ORDER By clause in the query.

You can use the Order By clause using the following syntax:

[ORDER BY fieldOrderByList {ASC|DESC} [NULLS {FIRST|LAST}] ]   

For example, if you want to query data from the accounts table and sort it in the descending order for the records having NULL in the last, you can use the following query:

SELECT Name
FROM Account
ORDER BY Name DESC NULLS LAST

Few factors that affect the result obtained through ORDER BY are:- 

  • It is case-sensitive.
  • We can sort multiple columns by listing more than one fieldexpression clause.
  • Sort order is determined by the current user locale. For example, for English locales, it uses sorting mechanisms based on the UTF-8 values of character data, and for Asian locales, it uses a linguistic sorting mechanism based on ISO 14651 & Unicode 3.5 standards.

This is how you can use the Order By clause in Salesforce SQL (SOQL).

Group By in SOQL

Group By as the name suggests is an SQL query to avoid iterating through individual query results. In short, you specify a group of records despite processing multiple records. 

You can use the Group By clause using the following syntax:

[GROUP BY fieldGroupByList]

For example, if you want to count the number of leads related to each type of lead source, you can do this by using the Group By clause while querying data from the lead table as follows:

SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource

This is how you can use the Group By clause in Salesforce SQL (SOQL).

Having in SOQL 

It is used to filter out results/records of an aggregate function based on a particular field. You can use the Having clause using the following syntax:

[HAVING havingConditionExpression]

For example, if you to filter out records having an Id count of more than one or filter out duplicate records from the contact table, you can use the Having clause as follows:

SELECT Name, Count(Id)
FROM Account
GROUP BY Name
HAVING Count(Id) > 1

This is how you can use the Having clause in Salesforce SQL (SOQL).

Aggregate Queries in SOQL

An aggregate query is used to find the aggregate result for a field. Below are a few methods that are supported in an aggregate query:

  • AVG(): The AVG aggregate function returns the average value for a numeric field that belongs to your table.

You can use the AVG() function using the following syntax:

SELECT AVG(NUMERIC_COLUMN) FROM TABLE;

For example, if you want to know the average amount for each campaign, you can use the following query:

SELECT CampaignId, AVG(Amount)
FROM Opportunity
GROUP BY CampaignId
  • COUNT(): The COUNT aggregate function returns the count of records or rows that satisfy your query criteria.

You can use the COUNT() function using the following syntax:

SELECT COUNT(COLUMN) / COUNT() FROM TABLE;

For example, if you want to know the count of names that start with ‘b’, you can use the following query:

SELECT COUNT()
FROM Account
WHERE Name LIKE 'b%'
  • SUM(): The SUM aggregate function returns the sum value for a numeric field that belongs to your table.

You can use the SUM() function using the following syntax:

SELECT SUM(NUMERIC_COLUMN) FROM TABLE

For example, if you want to know the sum of sale amounts for the year 2020, you can use the following query:

SELECT SUM(Amount)
FROM Sales
WHERE Year='2020'
  • MAX() & MIN(): The MAX & MIN aggregate functions return the maximum and minimum values respectively for a numeric field that belongs to your table.

You can use the MAX() & MIN() functions using the following syntax:

SELECT MAX(NUMERIC_COLUMN) FROM TABLE or SELECT MIN (NUMERIC_COLUMN) FROM TABLE

For example, if you want to find the maximum budget value for each campaign, you can do this using the following query:

SELECT Name, MAX(BudgetedCost)
FROM Campaign
GROUP BY Name

This is how you can use the aggregate functions in Salesforce SQL (SOQL).

Polymorphic Query

A Polymorphic query or relationship is the one where the current object can be one of several object types depending on a related event. 

Example Polymorphic Query is as follows:

List<Event> events = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')];

Execution of Salesforce SQL (SOQL) Queries

Salesforce allows you to execute your Salesforce SQL (SOQL) queries either by using the Query Editor or as part of the Apex Code.

Executing SOQL Queries using the Query Editor

To start executing your SOQL queries using the Query Editor, you first need to have some data in your Salesforce database.

For example, if you want to save the information containing the contact details of three control engineers, you can do this by clicking on debug, then the “Open Execute Anonymous Window ” option, and then adding the following lines of code:

Contact contact1 = new Contact(
   Firstname='Quentin',
   Lastname='Foam',
   Phone='(415)555-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Solar Arrays',
   Email='qfoam@trailhead.com');
insert contact1;
// Add second contact and related details
Contact contact2 = new Contact(
   Firstname='Vega',
   Lastname='North',
   Phone='(416)556-1312',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Propulsion',
   Email='vnorth@trailhead.com');
insert contact2;
// Add third contact and related details
Contact contact3 = new Contact(
   Firstname='Palma',
   Lastname='Sunrise',
   Phone='(554)623-1212',
   Department= 'Specialty Crisis Management',
   Title='Control Engineer - Specialty - Radiators',
   Email='psunrise@trailhead.com');
insert contact3;

Once you have the desired information in your Salesforce database, you can now start writing SOQL queries to extract the data. For example, you want to fetch the data related to engineers who work in the Specialty Crisis Management department.

You can do this by clicking on the Query Editor tab and entering the following SOQL query:

SELECT Name, Phone, Email, Title FROM Contact WHERE (Department = 'Specialty Crisis Management')

Once you’ve written the query, click on the execute button. You will now be able to see the results of your SOQL query on your screen. You can click on the Refresh Grid option to re-execute your SOQL query.

Using the Query Editor to execute SOQL Queries.

This is how you can use the Query Editor to execute Salesforce SQL (SOQL) queries.

Executing SOQL Queries using the Apex Code

Another way of executing SOQL queries is by using an Apex code. Such SOQL queries are known as inline SOQL queries, and you can run them with the help of the Developer Console.

For example, if you want to fetch the data related to engineers who work in the Specialty Crisis Management department with the help of an inline SOQL query, you can do as follows:

Click on debug and then select the “Open Execute Anonymous Window” option. Once you’ve clicked on it, enter the following lines of code:

Contact[] theseContacts = [SELECT Name, Phone, Email, Description FROM Contact WHERE (Department='Specialty Crisis Management') ORDER BY Name];
// Log a count of how many contacts were found
System.debug(theseContacts.size() + ' contact(s) returned.');
// Log all values in the array of contacts
System.debug(theseContacts);

Now click on execute. You will now be able to see the results of your query by opening the logs and selecting the “debug only” option. The output of your query execution, that is the contact information will be available in alphabetic order.

This is how you can use the Apex Code to execute Salesforce SQL (SOQL) queries.

Limitations of using Salesforce SQL (SOQL)

There might be some limitations of using SOQL as per its official documentation

  • We can execute 100 SOQL in a single transaction. 
  • Maximum records returned by a single SOQL query are 50k. 
  • Maximum 20 parent-to-child relationships can be specified in a query. 
  • A custom object allows upto 40 relationships. In this way, you can reference all child-to-parent relationships for custom objects in one query. 
  • In each specified relationship, only one level of parent-to-child can be specified in a query. For example, if the FROM clause is specific to Account, the SELECT clause can be specific to only the Contact or other objects that can be present at that level. It will not help in specifying a child object of Contact.
  • The maximum limit of SOQL is 20,000 characters  
  • If characters exceed this number then we will get a QUERY_TO_COMPLICATED error. 
  • Similarly, in Lightning, if a page layout contains more than 250 fields then it will result in QUERY_TO_COMPLICATED error because Lightning uses an auto-generated query to retrieve fields. 

Conclusion

To summarize, SOQL is equivalent to the SELECT SQL statement that searches the record on a given criterion only in a single Object. One difference between SOSL and SOQL is that it cannot search across multiple objects but supports nested queries.

Handling huge amounts of varied data can be a real pain. Ensuring data integrity and simplicity for analytics can be a lot of elaborate work. But it does not have to be a frustrating experience. Hevo Data can make your life a lot easier by transferring your data from free data sources like Salesforce, etc., to any desired destination, without you writing a single line of code.

Visit our Website to Explore Hevo

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand.

Share with us, your experiences working with Salesforce SQL in the comments. We would love to hear from you!

No-Code Data Pipeline for Salesforce