Wednesday 27 September 2023

Salesforce Objects

Salesforce Objects are database tables that allow you to store data specific to an organization.

Salesforce objects are of two types:

  • Standard Objects: Standard objects are the kind of objects that are provided by salesforce.com such as users, contracts, reports, dashboards, etc.
  • Custom Objects: Custom objects are created by users. They collect information that is unique and essential to their organization. They are the heart of any application and provide a structure for sharing data.

Properties of Custom Objects:

  • Custom fields
  • Relationship to another object
  • Page layouts
  • Custom user interface tab

Go through this Salesforce tutorial to learn more about the various components of Salesforce.

Custom Object Behavior

You can extend your organization’s data by defining custom objects using the user interface. Custom objects are nothing but custom database tables that enable you to store unique information or data about your organization. Custom objects behave and relate to objects like standard objects. Custom objects can also have many-to-many relationships with other custom or standard objects. These relationships enable the records to be linked with multiple records between objects and vice versa.

External Objects

External objects are very similar to custom objects. The primary difference is that external objects record data outside of your Salesforce organization. External objects are available using Salesforce Connect and Files Connect.

Relationships Among Objects

Relationships help in associating two objects. These objects can be Standard or Custom objects. You can define different types of relationships by creating custom relationship fields on an object. You can define different types of relationships by creating custom relationship fields in an object. You will understand the differences between relationship types; the differences can be in how relationships handle data deletion, security, record ownership, and required fields in page layouts.

Creating a Salesforce Custom Object

In this section, you will learn how to create a Salesforce Custom Object.

Step 1. First login to your Salesforce account, and in your Salesforce org, click on Setup.

Salesforce account

Step 2. Click on the Object Manager tab. Use the Quick Find box if you are unable to find it.

Object Manager

Step 3. On the Object Manager page, click on the Create drop-down button and then click on Custom Object.

create object manager

Step 4. A New Custom Object page will open, where you must fill in certain details.

new custom object

Step 5. Fill in the details like Label, Object Name information, and other information, if needed.

new custom object manager

  • In order to create a record name, you need to consider two types of data first:
    • Text
    • Auto-number

You also have some optional features while creating objects:

  • Allow Reports: If you tick this checkbox, then only these objects will be available to make Salesforce reports.
  • Allow Activities: If you tick this checkbox, you can make activities on this object.
  • Track Field History: When you tick this checkbox, you will be able to merely track the fields. You will be able to track up to 20 fields for a single object.

Track Field History

Preparing for a Salesforce Interview! Check out our Salesforce Interview Questions and Answers!

Now, you have the following deployment modes:

  • In Development: If you choose this option, then this object will remain in development mode. It will not be present for deployment.
  • Deployed: If you opt for this, then the object will be available for deployment.

deployed

The following options are available only when creating a custom object for the first time:

  • Add notes and attachments related list
  • Launch a new custom tab wizard after saving this custom object

Launch new custom object

After completing all these settings, press the Save button.

If you choose not to select “Launch new custom tab wizard” on the object creation page, the object will be saved without a corresponding tab. In such cases, you will need to manually create a tab for this object. Conversely, if you do select “Launch new custom tab wizard” on the object creation page, the object will be saved, and a tab will be automatically created, making it visible to you.

Sign up for this professional Salesforce Training and enrich your career!

Tabs in Salesforce

Tabs are like a user interface that is used to build records for objects and to view the records in the objects. There are three types of tabs in Salesforce:

How to Create a Custom Tab

  • Go to Setup > Build > Create > Tab. Click on New Tab and enter the details to complete the tab creation process.

Salesforce Standard Objects

Salesforce standard objects are those objects that come with Salesforce. These are different from custom objects because users create them to store unique company information. There are many objects within Salesforce that are standard objects. Some of them are Contact, Account, Lead, Opportunity, etc. Here, we will discuss some of the most common Salesforce standard objects:

Salesforce Standard Objects

Description

AcceptedEventRelation

It helps in representing participants, either invitees or attendees, with the status “Accepted” for an event.

Account

It represents an individual account, which can be an entity, organization, or person who is involved with your business. They can also be a customer, partner, or even a competitor.

ActionCadence

It represents the definition of a sales cadence. This standard object started being available in API version 45.0 and later.

ActionLink

ActionLink is a button on a feed element. If anyone clicks on ActionLink, they will be directed to another web page. On this page, a download will start or an API will be called to an external server or Salesforce.

Workload

Workload started appearing in Salesforce from version 49.0. It represents the time series for work item volume and average handling time from aggregation and forecasting processes.

WorkOrder

WorkOrder represents the field service work that is to be performed for a customer.

WorkGoal

WorkGoal represents the components of a goal, including all metrics and descriptions, but this object has been discontinued in API version 35.0.

WorkStep

Workshop is just a work step in a work plan. This object started appearing in Salesforce API version 52.0.

WorkThanks

WorkThanks represents the source and message of a thanks post.

WorkType

Word type is a template that can be applied to work orders or even work order line items. It represents a work type that is to be performed in Lightning Scheduler and Field Service.

WorkforceCapacity

WorkforceCapacity represents the time series for actual or forecasted workforce allocation. This object started being available in API version 51.0.

SOQL (Salesforce Object Query Language)

 

What is SOQL?

SOQL stands for Salesforce Object Query Language. It is a SQL-like language that queries records from Salesforce objects like Accounts, Contacts, Opportunities, etc. SOQL allows us to retrieve data that matches specific criteria. 

Some of the key benefits of SOQL are:

  • It provides an easy mechanism to extract relevant data from Salesforce objects. 
  • SOQL queries can be embedded in Apex classes and Visualforce pages to display data on the front end.
  • Aggregate functions can be used to summarize data. 
  • Query results can be limited, sorted, and filtered as per requirements.
  • SOQL is optimized for the Salesforce multi-tenant architecture. Queries are fast and efficient.

SOQL Query Structure and Syntax 

The basic structure of a SOQL query is

SELECT <field list>
FROM <object name>
WHERE <condition(s)>
LIMIT <number of rows>

For example, to query Account records where the Account Name starts with ‘Acme’, the SOQL query would be:

SELECT Name, BillingCountry 
FROM Account
WHERE Name LIKE 'Acme%'
LIMIT 10

This will return the Name and BillingCountry of 10 Accounts where the Name starts with ‘Acme’.

Different Parts of a SOQL Query 

Different parts of a SOQL query

SOQL has several parts, some of them are:

  • SELECT
    Specifies the list of fields to retrieve from the object. We can select standard fields, custom fields, and aggregate functions.
  • FROM
    Specifies the object to query. We can query standard objects like Account, Contact, Opportunity, or custom objects. 
  • WHERE
    Filters the records to retrieve only those that match the specified conditions. Conditions can include parameters like =, <>, >, <, >=, <=, LIKE, IN, etc.
  • LIMIT
    Restricts the number of records retrieved to the specified limit. This helps improve query performance. 
  • ORDER BY
    Sorts the retrieved records in ascending or descending order based on the specified fields. The default sort order is ascending.
  • GROUP BY
    Groups query results based on the specified field. Usually used in conjunction with aggregate functions.
  • HAVING
    Filters records after grouping and aggregation. Similar to WHERE but operates on grouped records.

Using SOQL to Query Salesforce Standard and Custom Objects

We can use SOQL to query both standard Salesforce objects as well as custom objects. The syntax is the same, we just need to specify the correct object name.

For example, to query Accounts, the object name is simply ‘Account’:

SELECT Name, BillingCountry
FROM Account
WHERE Name LIKE 'Acme%' 

To query the Opportunity object, use:

SELECT Id, Name, StageName, Amount
FROM Opportunity
WHERE CloseDate = THIS_MONTH  

For custom objects, refer to them by their API name. For a custom object with the API name ‘Product__c’, the SOQL would be: 

SELECT Name, Description__c, Price__c
FROM Product__c
WHERE Name = 'Widget'

We can query fields of all data types including text, number, date, lookup relationship, etc. SOQL also allows querying across relationships using dot notation. For example, to retrieve the Account Name for Opportunity records, we can use:

SELECT Opportunity.Name, Account.Name
FROM Opportunity

This works for both standard object relationships as well as custom object relationships.

Want to make a career in the Salesforce industry? Make sure to enroll in a Salesforce Training Course right now!

Limiting Results and Sorting with SOQL  

To optimize performance, limiting the number of records retrieved by a SOQL query using the LIMIT clause is a good practice. For example, to retrieve only the first 50 Account records, we can use:

SELECT Id, Name
FROM Account
LIMIT 50

To sort the retrieved records in ascending or descending order, use the ORDER BY clause. For example, to sort Accounts by Name in descending order:

SELECT Id, Name
FROM Account
ORDER BY Name DESC

We can sort based on both standard and custom fields. To sort on multiple fields, specify them in the desired sort order:

SELECT Id, Name, BillingCountry
FROM Account
ORDER BY Name DESC, BillingCountry ASC

This will first sort records by Name in descending order. For records with the same Name, they will be sorted by BillingCountry in ascending order.


Using SOQL Aggregates to Summarize Data  

Aggregate functions allow us to summarize data and calculate metrics like count, sum, average, etc. Some commonly used aggregate functions in SOQL are:

  • COUNT(): Returns the total number of records. 
  • SUM(): Calculates the sum of values for a numeric field. 
  • AVG(): Returns the average value of a numeric field. 
  • MIN(): Returns the minimum value for a field. 
  • MAX(): Returns the maximum value for a field. 

For example, to get the count of Accounts:

SELECT COUNT()
FROM Account

To get the sum of Amount for all Opportunities:

SELECT SUM(Amount)
FROM Opportunity  

We can also use GROUP BY to summarize data by a particular field. For example, to get the count of Accounts by BillingCountry:

SELECT BillingCountry, COUNT()
FROM Account
GROUP BY BillingCountry

The HAVING clause is used to filter summarized records. For example, to get the sum of Amount for Opportunities where the sum is greater than $200,000: 

SELECT SUM(Amount)
FROM Opportunity
GROUP BY CloseDate
HAVING SUM(Amount) > 200000

SOQL queries with aggregates can also contain standard fields, custom fields and be limited and sorted. They provide a powerful way to analyze and summarize your Salesforce data.

Check out Salesforce Tutorial to learn Salesforce!

Embedding SOQL Queries in Apex and Visualforce pages

SOQL queries are typically executed in:

  • Developer Console: To test and debug SOQL queries during development. 
  • Apex classes: SOQL queries can be embedded in Apex to retrieve data and use it for processing. The results are stored in Apex variables, which can be manipulated afterwards.
  • Visualforce pages: SOQL queries embedded in Visualforce pages can be used to display data and create interactive reports and dashboards. 

For example, here is an Apex class that executes a SOQL query and iterates over the results:

public class AccountQuery {
  public List<Account> queryAccounts(){
    List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 10];
    for(Account a : accounts){
      System.debug(a.Name);
    }
    return accounts;
  }
}

In Visualforce, a SOQL query can be used to populate a table as follows:

<apex:page>
<apex:form>
  <apex:pageBlock>
    <apex:pageBlockTable value="{!accounts}" var="a">
      <apex:column value="{!a.Name}"/>
      <apex:column value="{!a.BillingCountry}"/> 
    </apex:pageBlockTable>
  </apex:pageBlock>
</apex:form>
<apex:includeScript value="{!$Resource.AccountsQuery}"/> 
</apex:page>

<apex:includeScript> is used to execute the Apex class that returns the Query results. These results are then displayed in the Visualforce page using <apex:pageBlockTable>.



SOQL and SOSL have several differences between them. Some of them are:

DifferentiationSOQLSOSL
SyntaxSOQL uses a SQL-like syntax for querying data from a single object or related objects.SOSL uses a text-based syntax for searching across multiple objects and fields.
FunctionalitySOQL is best suited for retrieving specific records and related data from a single object or a set of related objects.SOSL is designed for searching across multiple objects and fields, making it ideal for complex search queries.
Query performanceSOQL is optimized for retrieving a small number of records and has better performance for retrieving data from a single object.SOSL is optimized for searching across multiple objects and fields and can retrieve a large number of records more efficiently.
Sorting and filteringSOQL supports the sorting and filtering of records based on specific fields.SOSL supports the sorting and filtering of records based on relevance.

Conclusion

Salesforce SOQL is an incredibly powerful tool that allows you to extract and manipulate data from your Salesforce database. With its intuitive syntax and documentation, learning SOQL is easier than you might think. It is a must-know tool for anyone working with Salesforce data.