Search Functionality using SOSL and SOQL

Last updated on Nov 24 2021
Abha Kulkarni

Table of Contents

Search Functionality using SOSL and SOQL

Every business or application has search functionality together of the essential requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL. allow us to discuss the SOSL approach intimately during this blog.

SOSL

Searching the text string across the thing and across the sector are going to be done by using SOSL. this is often Salesforce Object command language . it’s the potential of searching a specific string across multiple objects.
SOSL statements evaluate to an inventory of sObjects, wherein, each list contains the search results for a specific sObject type. The result lists are always returned within the same order as they were laid out in the SOSL query.
SOSL Query Example
Consider a business case wherein, we’d like to develop a program which may search a specified string. Suppose, we’d like to look for string ‘ABC’ within the Customer Name field of Invoice object. The code goes as follows −
First, you’ve got to make one record in Invoice object with Customer name as ‘ABC’ in order that we will get valid result when searched.

// Program to look the given string altogether Object
// List to carry the returned results of sObject generic type
List invoiceSearchList = new List();

// SOSL query which can look for 'ABC' string in Customer Name field of Invoice Object
invoiceSearchList = [FIND 'ABC*' altogether FIELDS RETURNING APEX_Invoice_c
(Id,APEX_Customer_r.Name)];

// Returned result are going to be printed
System.debug('Search Result '+invoiceSearchList);

// Now suppose, you'd wish to search string 'ABC' in two objects,
// that's Invoice and Account. Then for this question goes like this:

// Program to look the given string in Invoice and Account object,
// you'll specify more objects if you would like , create an Account with Name as ABC.

// List to carry the returned results of sObject generic type
List invoiceAndSearchList = new List();

// SOSL query which can look for 'ABC' string in Invoice and in Account object's fields
invoiceAndSearchList = [FIND 'ABC*' altogether FIELDS RETURNING APEX_Invoice__c
(Id,APEX_Customer__r.Name), Account];

// Returned result are going to be printed
System.debug('Search Result '+invoiceAndSearchList);

// This list will hold the returned results for Invoice Object
APEX_Invoice__c [] searchedInvoice = ((List)invoiceAndSearchList[0]);

// This list will hold the returned results for Account Object
Account [] searchedAccount = ((List)invoiceAndSearchList[1]);
System.debug('Value of searchedInvoice'+searchedInvoice+'Value of searchedAccount'
+ searchedAccount);

SOQL

This is almost an equivalent as SOQL. you’ll use this to fetch the thing records from one object only at a time. you’ll write nested queries and also fetch the records from parent or child object on which you’re querying now.
Apex – SOQL
This is Salesforce Object command language designed to figure with SFDC Database. It can search a record on a given criterion only in single sObject.
Like SOSL, it cannot search across multiple objects but it does support nested queries.
SOQL Example
Consider our ongoing example of Chemical Company. Suppose, we’d like an inventory of records which are created today and whose customer name isn’t ‘test’. during this case, we’ll need to use the SOQL query as given below −

// fetching the Records via SOQL
List InvoiceList = new List();
InvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM
APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != 'Test'];
// SOQL query for given criteria

// Printing the fetched records
System.debug('We have total '+InvoiceList.size()+' Records in List');

for (APEX_Invoice__c objInvoice: InvoiceList) {
System.debug('Record Value is '+objInvoice); 
// Printing the Record fetched
}

You can run the SOQL query via the Query Editor within the Developer console as shown below.
Run the query given below within the Developer Console. look for the Invoice records created today.
SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c
WHERE createdDate = today
You must select the fields that you would like the values, otherwise, it can throw run time errors.
Traversing Relationship Fields
This is one among the foremost important parts in SFDC as repeatedly we’d like to traverse through the parent child object relationship
Also, there could also be cases once you got to insert two associated objects records in Database. for instance, Invoice object has relationship with the Customer object and hence one Customer can have many invoices.
Suppose, you’re creating the invoice then you would like to relate this invoice to Customer. you’ll use the subsequent code for this functionality −

// Now create the invoice record and relate it with the Customer object
// Before executing this, please create a Customer Records with Name 'Customer
// Creation Test'
APEX_Invoice__c objInvoice = new APEX_Invoice__c();

// Relating Invoice to customer via id field of Customer object
objInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name =
'Customer Creation Test' LIMIT 1].id;
objInvoice.APEX_Status__c = 'Pending';
insert objInvoice; //Creating Invoice
System.debug('Newly Created Invoice'+objInvoice); //Newly created invoice

Execute this code snippet within the Developer Console. Once executed, copy the Id of invoice from the Developer console then open an equivalent in SFDC as shown below. you’ll see that the Parent record has already been assigned to Invoice record as shown below.

salesforce 66
salesforce

Fetching Child Records

Let us now consider an example wherein, all the invoices associated with particular customer record got to be in one place. For this, you want to know the kid relationship name. to ascertain the kid relationship name, attend the sector detail page on the kid object and check the “Child Relationship” value. In our example, it’s invoices appended far and away at the top .
Example
In this example, we’ll got to found out data, create a customer with name as ‘ABC Customer’ record then add 3 invoices thereto customer.
Now, we’ll fetch the invoices the Customer ‘ABC Customer’ has. Following is that the query for an equivalent −

// Fetching Child Records using SOQL
List ListCustomers = [SELECT Name, Id, 
(SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = 'ABC Customer'];

// Query for fetching the kid records along side Parent
System.debug('ListCustomers '+ListCustomers); // Parent Record

List ListOfInvoices = ListCustomers[0].Invoices__r;
// By this notation, you'll fetch the kid records and reserve it in List
System.debug('ListOfInvoices values of kid '+ListOfInvoices);
// Child records

You can see the Record values within the Debug logs.

Fetching Parent Record

Suppose, you would like to fetch the Customer Name of Invoice the creation date of which is today, then you’ll use the query given below for an equivalent −
Example
Fetch the Parent record’s value along side the kid object.

// Fetching Parent Record Field value using SOQL
List ListOfInvoicesWithCustomerName = new List();
ListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name 
FROM APEX_Invoice__c LIMIT 10];

// Fetching the Parent record's values
for (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) {
System.debug('Invoice Customer Name is '+objInv.APEX_Customer__r.Name);
// Will print the values, all the Customer Records are going to be printed
}

Here we’ve used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you’ve got to append the __r at the top of the Parent field then you’ll fetch the parent field value.

Aggregate Functions

SOQL does have aggregate function as we’ve in SQL. Aggregate functions allow us to roll up and summarize the info . allow us to now understand the function intimately .
Suppose, you wanted to understand that what’s the typical revenue we are becoming from Customer ‘ABC Customer’, then you’ll use this function to require up the typical .
Example

// Getting Average of all the invoices for a Perticular Customer
AggregateResult[] groupedResults = [SELECT
AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE
APEX_Customer__r.Name = 'ABC Customer'];
Object avgPaidAmount = groupedResults[0].get('averageAmount');
System.debug('Total Average Amount Received From Customer ABC is '+avgPaidAmount);

Check the output in Debug logs. Note that any query that has an aggregate function returns its leads to an array of AggregateResult objects. AggregateResult may be a readonly sObject and is merely used for query results. it’s useful once we got to generate the Report on Large data.
There are other aggregate functions also which you’ll be wont to perform data summary.
MIN() − this will be wont to find the minimum value
MAX() − this will be wont to find the utmost value.
Binding Apex Variables
You can use the Apex variable in SOQL query to fetch the specified results. Apex variables are often referenced by the Colon (:) notation.
Example

// Apex Variable Reference
String CustomerName = 'ABC Customer';
List ListCustomer = [SELECT Id, Name FROM APEX_Customer__c
WHERE Name = :CustomerName];
// Query Using Apex variable
System.debug('ListCustomer Name'+ListCustomer); // Customer Name

So, this brings us to the end of blog. This Tecklearn ‘Search Functionality using SOSL and SOQL’ blog helps you with commonly asked questions if you are looking out for a job in Salesforce. If you wish to learn Salesforce and build a career in Salesforce domain, then check out our interactive, Salesforce Certification Training: Admin 201 and App Builder, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Salesforce Certification Training: Admin 201 and App Builder

Salesforce Certification Training: Admin 201 and App Builder

About the Course

Salesforce Certification Training course will help you pass the Salesforce Administrator Exam (Admin 201) and the Salesforce App Builder (Dev 401) Exam. Concepts on Force.com Platform, AppExchange, SFDC Security Model, Service Cloud, Sales Cloud, Lightning App Builder, Salesforce Reports & Dashboard can be mastered in this Salesforce Training course. You can also configure the platform, manage users, find better ways to use the platform’s features, build applications with Salesforce Lightning, and more. Further, in this Salesforce certification training course, you will master App builder, Apex, Visualforce, etc.

Why Should you take Salesforce Admin 201 and App Builder Training?

• As per Indeed.com data, 200% global jump in Salesforce jobs since Jan 2016. Salesforce Certified Administrators earn an annual average salary of $87,000 but can go as high as $160,000 depending on their knowledge, skills, and experience.
• More than 200,000 companies worldwide use Salesforce platform. Salesforce leads the CRM market with 19.5 percent of market share – Forbes.
• The global CRM software market will reach US$40.26 billion in 2023, up from US$36.9 billion (2020) – Statista.

What you will Learn in this Course?

Salesforce Fundamentals
• Introduction to CRM concepts and Cloud computing
• Salesforce.com Overview and Fundamentals
• Understanding Salesforce Platform
Understanding Salesforce Platform
• Understanding Salesforce Terminologies and Introducing the force.com platform
• Understanding Salesforce Metadata and API
• Describe the capabilities of the core CRM objects in the Salesforce schema
• Identify common scenarios for extending an org using the AppExchange
• About Salesforce Certification
Introduction to Sales Cloud
• Sales Cloud
• Sales Process
• Sales Productivity Features
• Lead Management
• Lead auto response
• Lead assignment
• Web to lead
• Accounts and Contacts Management
• Opportunities
• Campaign Management
Security Model, User Management and Its Features
• Security Model Mind Map
• System Level or Org Level Security
• User Administration and Troubleshooting
• Permission Sets
• Profile Management
• User Actions
• Assigning Permission
• Session settings
• Activations
• Page layout assignment
• Tab setting
• Field level security
Object, Record and Field Level Features
• Custom Object
• Custom Field
• Data Types
• Relationship among Objects
• Working with App and Tabs
Data Handling and Processing
• Data Import and Export with Salesforce
• Insert, Update and Delete Data with Salesforce
• Export Data with UI
• Export Data using Data Loader Tool
Deployment
• SandBox
• Moving Data from SB to Production – Deployment
• Types of SandBox
• Change Sets
• Types of Change Sets
Application Cycle
• Milestones
• Sandboxes
• Change Sets
• Packages
Reports and Dashboards
Declarative Implementation in Salesforce
Salesforce Development and Apex Programming
• Apex Programming
• Apex Classes
• Apex Settings
• SOQL – Salesforce Object Query Language
• DML Commands
• Apex Class in Detail
• Apex Triggers
• Apex Testing
• Access Specifier in Salesforce
• Testing
Lightning in Salesforce
• Lightning Components
• Lightning Component Capabilities
• Lightning Components vs. Visualforce
Visual Force in Salesforce
• Standard Visualforce controller and controller extensions,
• Visualforce Page
• Understanding the MVC Pattern
• Tools for Visualforce Development
• Visual Force Components
WorkFlows in Salesforce
• Work Flows in Salesforce
• Types of Work Flows
• Work Flows Rules
About Preparation of Salesforce 201 and App Builder Certification exams

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Search Functionality using SOSL and SOQL"

Leave a Message

Your email address will not be published. Required fields are marked *