Apex Interview Questions
Apex Interview Questions
Ans: A sharing rule is a setting that allows you to give access to specific records to a group of
users or roles. Sharing rules can be used to extend access to records beyond the
organization-wide default settings, which control the visibility of records to all users in an
organization.
Sharing rules can be based on various criteria, such as record owner, record type, or criteria-
based rules that use filters to identify specific records. You can also set up sharing rules to
grant access either read-only or read/write access to users or roles.
Sharing rules can be particularly useful when you need to provide access to specific records
to users who don't have access by default, without having to grant them access to all records
of a certain object. Sharing rules can be used in conjunction with other sharing settings, such
as role hierarchies and sharing groups, to fine-tune access to records in Salesforce
Ans: In Salesforce, there are several types of sharing that can be used to control access to
records:
• Organization-wide sharing settings: This is the baseline level of access that applies to
all records of an object in the organization. There are three settings for organization-
wide sharing: Public, Private, and Public Read Only.
• Role hierarchies: Role hierarchies are a way to grant access to records based on a
user's role and position in the hierarchy. Users in higher roles can access records
owned by users in lower roles. This is useful when you want to grant access to a
subset of records to users who are not record owners.
• Sharing rules: Sharing rules allow you to extend access to specific records to users or
roles who don't have access by default. Sharing rules can be based on criteria such as
record owner, record type, or criteria-based rules that use filters to identify specific
records.
• Manual sharing: Manual sharing allows record owners to manually grant access to
specific records to individual users or roles. This can be useful when you need to
provide access to a specific record to a user who wouldn't have access otherwise.
• Apex managed sharing: Apex managed sharing is a programmatic way to share
records using custom logic implemented in Apex code. This allows for more granular
control over record sharing and can be used for complex sharing scenarios.
Profile?
Profiles and Permission Sets are both used to control access to various Salesforce objects,
fields, and features, but they have some key differences:
• Scope: Profiles are used to control access at the user level, while permission sets are
used to grant additional permissions to users who already have a profile. A profile is
assigned to a user when they are created, while permission sets can be assigned to
users at any time.
• Inheritance: Profiles are inherited by all the users who are assigned to them, while
permission sets are not inherited. Each permission set must be assigned to individual
users.
• Granularity: Profiles control a wide range of permissions and settings, including
object and field permissions, user interface settings, and data access settings.
Permission sets are more granular and can be used to grant additional permissions
for specific objects, fields, or features.
• Limitations: Profiles can have certain limitations, such as a maximum of two profiles
per user, and they cannot be combined. Permission sets have no limitations and can
be combined with other permission sets to grant additional permissions.
• User Interface: Profiles have a user interface where administrators can manage a
range of settings such as page layouts, record types, and tabs. Permission sets do not
have a user interface to manage settings
5.
6.
7. Can I make a asynchronous call from a trigger?
No, it's not recommended to make an asynchronous call from a trigger in Salesforce. Trigger
execution is synchronous and adding an asynchronous call could lead to unpredictable
behavior and potential issues.
Instead, you should consider using a future method or a Queueable Apex class to perform
asynchronous processing from your trigger. These methods will allow your trigger to
continue executing synchronously while the asynchronous processing is done separately in
the background.
In general, it's a best practice to keep triggers as lean as possible and move any complex or
time- consuming processing to separate classes or services. This will help keep your code
more modular and easier to maintain over time.
Order of Execution:
Load the original record from the database and load the record for the upsert statement.
• Load the new record field values from the request and overwrite the old values.
• If the request comes from a standard UI edit page, Salesforce runs system validation
to check the record for:
1. Compliance with layout-specific rules
2. Required values at the layout level and field-definition level
3. Valid field formats
4. Maximum field length.
• Whenever a request comes from other sources, e.g., Apex application or a SOAP API
call, Salesforce validates only the foreign keys.
• Executes record-triggered flows that are configured to run before the record is saved.
• Executes all before triggers.
• Run most system validation steps. Verify that all required fields have a non-null value
and run user-defined validation rules.
• Executes duplicate rules.
• Saves the record to the database, but doesn't commit yet.
• Executes all after triggers.
• Executes assignment rules.
• Executes auto-response rules.
• Executes workflow rules.
• Executes escalation rules.
• If there are workflow field updates, update the record again.
• If the record was updated with workflow field updates, fires before update triggers
and after update trigger onemore time (and only one more time), in addition to
standard validations.
• Executes processes and flows launched using flow trigger workflow actions.
• Executes entitlement rules.
• Executes record-triggered flows that are configured to run after the record is saved.
• If the record contains a roll-up summary field or is part of a cross-object workflow,
perform calculations and update the roll-up summary field in the parent record.
Parent record goes through the save procedure.
• If the parent record is updated, and a grandparent record contains a roll-up summary
field or is part of a cross-object workflow, performs calculations and updates the roll-
up summary field in the grandparent record.
• Executes Criteria Based Sharing evaluation.
• Commits all DML operations to the database.
• Executes post-commit logic, such as sending an email.
Governor limits in Salesforce are the limits enforced by the platform on the amount of
resources a single transaction can consume. These limits are in place to ensure the efficient
and fair use of shared resources on the platform, and to prevent any one transaction from
monopolizing too many resources, which could impact other transactions on the platform.
• CPU Time Limit: This is the amount of time that a single transaction can use to
execute Apex code on the Salesforce platform. The default limit is 10,000
milliseconds (10 seconds), and exceeding this limit will result in a CPU time limit
exceeded error.
• Heap Size Limit: This is the amount of memory that can be used by a single
transaction to store data and execute code. The default limit is 6 MB for synchronous
transactions and 12 MB for asynchronous transactions.
• SOQL Query Limit: This is the number of records that can be retrieved in a single
SOQL query. The default limit is 50,000 records, but this can be increased to 1 million
records using the SOQL query optimizer.
• DML Statement Limit: This is the number of records that can be modified in a single
DML statement. The default limit is 10,000 records.
• Email Limit: This is the number of emails that can be sent in a single transaction. The
default limit is 5,000 emails per day per org, but this can be increased by contacting
Salesforce support.
• Callout Limit: This is the number of external HTTP requests that can be made in a
single transaction. The default limit is 100 callouts per transaction, but this can be
increased by using a callout to an Apex REST endpoint.
• Yes, you can add additional methods to a batch class, as long as you follow the basic
structure and syntax requirements of a batch class.
• However, keep in mind that any additional methods you add to a batch class should
not interfere with the standard functionality of the batch class. The main entry point
of a batch class is the execute() method, which is called when the batch job is
started, so any additional methods should not interfere with this method.
• Additionally, if you plan to use any additional methods in your batch class from
outside the class (for example, in a test class), make sure to mark them as public so
they can be accessed from other classes.
What is the difference between schedulable and batchable?
• Required Field Property: In the field properties of a custom or standard field, you can
mark the "Required" checkbox. This will make the field mandatory on all page layouts
and prevent users from saving a record without entering a value in the field.
• Validation Rule: You can create a validation rule on a record that checks whether a
field has a value. If the field is empty, the rule will display an error message and
prevent the record from being saved until the field has a value.
• Page Layout: You can make a field mandatory on a specific page layout by using the
page layout editor. In the "Field Properties" section, select the "Required" checkbox
for the field to make it mandatory on that page layout.
• Apex Trigger: You can create an Apex trigger on a custom or standard object that
checks whether a field has a value. If the field is empty, the trigger can display an
error message and prevent the record from being saved until the field has a value.
• Roll-up summary fields in Salesforce are fields that summarize data from child
records and display that data on the parent record. They allow you to perform
calculations on related records and show the results on a single record.
• Roll-up summary fields are only available on master-detail relationships where the
detail object is the child and the master object is the parent. For example, if you have
a custom object called "Order" and a related object called "Order Line Item," you can
create a roll-up summary field on the Order object that summarizes data from the
Order Line Item object.
• You can use roll-up summary fields to perform various calculations, such as
calculating the sum, average, maximum, or minimum value of a particular field on
the child records. Roll-up summary fields are calculated in real-time and update
automatically when changes are made to the child records.
• Create a Record: This quick action allows users to create a new record of a specified
object. For example, you could create a "New Account" quick action to allow users to
quickly create a new account record from any page in Salesforce.
• Update a Record: This quick action allows users to update one or more fields on a
record without leaving the page they are on. For example, you could create an
"Update Status" quick action to allow users to quickly update the status of an
opportunity from any page in Salesforce.
• Log a Call: This quick action allows users to log a call related to a specific record. For
example, you could create a "Log Call" quick action to allow users to quickly log a call
related to a lead or contact record.
• Send Email: This quick action allows users to send an email related to a specific
record. For example, you could create a "Send Email" quick action to allow users to
quickly send an email to a lead or contact record.
• Each quick action can be customized to include specific fields, pre-populated values,
and other options based on your business needs. Quick actions can be accessed from
the Salesforce mobile app, the Salesforce Lightning Experience, and the Salesforce
Classic interface.
• Tabular Reports: Tabular reports are the simplest type of report, which display data
in a table format. They allow users to group data by a single field and filter the data
based on specific criteria.
• Summary Reports: Summary reports display data in a compact, summarized format.
They allow users to group data by multiple fields and display subtotals and grand
totals for each group. Users can also filter the data based on specific criteria.
• Matrix Reports: Matrix reports allow users to display data in a grid format, similar to
a pivot table in Excel. They allow users to group data by both rows and columns and
display subtotals and grand totals for each group. Users can also filter the data based
on specific criteria.
• Joined Reports: Joined reports allow users to display data from multiple objects in a
single report. They allow users to create blocks of related data, each with its own set
of fields, filters, and sorting options.
• Custom Settings and Custom Metadata are two types of custom data that can be
created in Salesforce. They are similar in some ways but have some key differences.
• Custom Settings are custom objects that allow you to store custom data that is
specific to your organization. They can be used to store data that is frequently
accessed and shared across your organization, such as application settings or
configuration data. Custom Settings can be created and maintained by administrators
and are customizable, meaning you can define your own fields and relationships.
They can also be accessed in Apex code or formulas.
• Custom Metadata, on the other hand, is a type of metadata that allows you to store
data in a way that can be easily deployed across different Salesforce environments,
such as from sandbox to production. Custom Metadata can be used to store data
that is frequently accessed and shared across different components in Salesforce,
such as record types, picklist values, or configuration data. Custom Metadata is
created and maintained by developers and is customizable, meaning you can define
your own fields and relationships. They can be accessed in Apex code or formulas,
and are also accessible through the Metadata API.
• The main difference between Custom Settings and Custom Metadata is that Custom
Settings are organization- specific and can only be accessed within the same
organization, whereas Custom Metadata can be deployed across different Salesforce
environments. This makes Custom Metadata particularly useful for managing data
that is shared across multiple organizations or for managing configuration data in
managed packages.
In Custom setting can I use the lookup relationship and master detail relationship ?
No
• When writing test classes in Salesforce, there are several best practices to follow to
ensure that your code is effective and efficient:
• Test every scenario: Your test class should cover all possible scenarios for your code,
including positive and negative tests. This ensures that your code works as expected
and is robust enough to handle edge cases.
• Use meaningful names: Use meaningful names for your test methods and variables
to make it easier to understand the purpose of each test.
• Avoid hardcoding values: Avoid hardcoding values in your test class whenever
possible, and use variables or constants instead. This makes it easier to maintain your
code and update values as needed.
• Test data setup: Use test data setup methods to create and populate test data in your
test class. This ensures that your tests run consistently and that your test data is
always available.
• Use System.assert() statements: Use System.assert() statements to verify the
expected results of your tests. This ensures that your tests are actually testing what
they're intended to test.
• Test governor limits: Test governor limits in your test class to ensure that your code
stays within the limits set by Salesforce.
• Test asynchronous code: Test asynchronous code by using Test.startTest() and
Test.stopTest() to ensure that asynchronous code completes before the test method
completes.
• Test code coverage: Ensure that your test class covers at least 75% of your Apex code.
This ensures that your code can be deployed to production.
• Keep test classes separate from other classes: Keep your test classes separate from
your other classes to ensure that they are not deployed to production accidentally.
Whenever you are writing any test classes what all are the debug, error like exception you
faced while running my code.
• Future Methods: Future methods are used to run long-running operations in the
background, asynchronously, and are typically used when you need to perform some
operation that takes a lot of time to complete, such as a callout to an external API or
a batch process.
• Queueable Apex: Queueable Apex is used to chain multiple jobs together in a
specific order or to run jobs in parallel, and is useful for running jobs that may take a
long time to complete or that need to be run in a specific order.
• Batch Apex: Batch Apex is used to process a large number of records asynchronously
and is useful for situations where you need to perform some operation on a large
number of records, such as updating all accounts with a specific value.
These asynchronous methods are designed to help developers avoid hitting governor
limits, such as CPU time and heap size limits, and to improve the performance of the
Salesforce org by running long-running operations in the background,
asynchronously.
We are having 2000 records and those records like I am trying to insert in the batch size is
200.On 298th record some error occur. What will happen? What will happen after 298th
record?
• When inserting 2000 records in Salesforce with a batch size of 200, the system will
process the records in batches of 200 until all the records have been processed.
• If an error occurs on the 298th record, the system will roll back the entire batch of
200 records that were being processed at that time, including the 298th record. This
means that none of the 200 records in that batch will be inserted into the database.
• After the error has occurred, the system will attempt to insert the remaining 1702
records in batches of 200, until all the records have been processed. However, it's
important to note that if there are any more errors that occur during the insertion
process, the system will continue to roll back the entire batch of 200 records that
were being processed at that time, and will not insert any of the records in that
batch.
• Once all the records have been processed, you will receive a report that details any
errors that occurred during the insertion process, including the error that occurred
on the 298th record.
Ans: In Salesforce, the terms "Export" and "Export All" refer to two different data export
options available for exporting records from Salesforce objects. Here's an explanation of
each option and an example to illustrate their use:
• Export: The "Export" option allows you to export a subset of records from a
Salesforce object based on specified criteria. When using the Export option, you can
define filters or conditions to export only a specific set of records that meet the
criteria you specify. This option is useful when you want to export a targeted subset
of records from an object.
Example: Let's say you have a custom object called "Opportunity___c" in Salesforce, and you
want to export all closed opportunities from the last quarter. You can use the Export option
and apply filters to export only the closed opportunities with a close date in the desired date
range. This export will generate a file containing only the closed opportunities meeting your
criteria.
• Export All: The "Export All" option allows you to export all records from a Salesforce
object, including those that may be archived or placed in the Salesforce recycle bin.
When using the Export All option, you retrieve all records from the object, regardless
of any filters or conditions. This option is useful when you want to export a complete
dataset, including archived or deleted records.
Example: Let's consider the same custom object "Opportunity__c" in Salesforce. In this case,
you want to export all opportunities, including the ones that have been archived or deleted.
You can use the Export All option to retrieve all records from the Opportunity___c object,
providing you with a comprehensive export file that includes all opportunities, whether
active, archived, or deleted.
What is the use of hard delete? What is the use of delete? What is the differende between
Delete and Hard delete?
Ans:
In Salesforce, "hard delete" and "delete" are terms used to describe different ways of
removing records from the system. Here's an explanation of each term and the difference
between them:
• Use of Delete: In Salesforce, the "delete" operation is used to remove records from
the database. When you delete a record, it is moved to the Salesforce recycle bin,
where it can be restored if needed. The deleted record remains in the recycle bin for
a certain retention period, typically 15 days by default (can be modified). During this
period, the record can be undeleted by the user or system administrator. The
"delete" operation provides a level of safety and allows for recovery of accidentally
deleted records.
• The primary use of the delete operation is to remove records from the active dataset
while still providing the option to restore them within the retention period.
Use of Hard Delete: "Hard delete" is an option available in Salesforce that allows for
the permanent and immediate removal of records from the system without moving
them to the recycle bin. When you perform a hard delete, the record is immediately
and permanently deleted, and it cannot be restored. Hard deleted records are not
recoverable.
The use of hard delete is typically limited to specific scenarios where there is a requirement
to completely and permanently eliminate records without any possibility of recovery. It
should be used with caution, as the deleted records cannot be retrieved.
What is the use/ significance of external ids in terms of doing Upsert operation using data
loader?
Ans: In the context of performing upsert operations using Data Loader in Salesforce, the use
of external IDs is significant and serves several purposes. Here's the significance and use of
external IDs in relation to upsert operations:
• Unique Identifier: External IDs act as unique identifiers for records in Salesforce. An
external ID is a custom or standard field that contains a unique value for each record,
which can be used to identify and match records during the upsert operation.
• Upsert Operation: The upsert operation in Data Loader allows you to update existing
records or insert new records based on matching values in the external ID field. By
specifying the external ID field, Data Loader determines whether a record already
exists based on that field's value. If a match is found, the record is updated; if no
match is found, a new record is inserted.
• Integration and Data Synchronization: External IDs are commonly used in integration
scenarios where data needs to be synchronized between Salesforce and external
systems. By using the same external ID field across systems, you can uniquely identify
and match records, enabling efficient data updates or inserts during the upsert
operation.
What Upsert do? How will data loader salesforces know if data in present or not?
Ans: The upsert operation in Salesforce combines the functionality of inserting new records
and updating existing records in a single operation. It allows you to upsert (i.e., update or
insert) records based on a specified matching field, typically an external ID. Here's how Data
Loader in Salesforce determines if data is present or not during an upsert operation:
• Matching Field: When configuring the Data Loader operation, you need to specify a
matching field that will be used to identify and match records. This field should
contain a unique value for each record that you want to load or update. It can be an
external ID field or any other custom or standard field that serves as a unique
identifier.
• Record Comparison: As Data Loader processes the data during the load or update
operation, it compares the values in the matching field of each record being loaded
with the existing records in Salesforce.
• Existing Record Match: If Data Loader finds a match between the value in the
matching field of the data being loaded and an existing record's matching field value
in Salesforce, it identifies it as an existing record that needs to be updated.
• Update or Insert: Once a match is found, Data Loader performs an update operation
on the existing record. It updates the record with the new data provided in the Data
Loader operation, modifying specific fields or updating the entire record as required.
• No Match Found: If Data Loader does not find a match for the value in the matching
field of the data being loaded, it considers it a new record that needs to be inserted.
In this case, Data Loader creates a new record in Salesforce with the provided data.
• By utilizing the specified matching field and comparing it with existing records, Data
Loader can determine if the data is present or not in Salesforce. If a match is found, it
performs an update operation on the existing record. If no match is found, it
proceeds with inserting a new record.
• It's crucial to ensure the uniqueness and consistency of the matching field values to
avoid unexpected results during the Data Loader operation.
If you delete certain record from the org mistakenly and you have to restore it so what will
be the steps to stored it. Suppose you have delete 1 lakh of record from the production
system and need to restore in the org without knowing your manager. How will you do it?
How we can identify the record is being deleted? How to query the data from recycle bin.
Ans: If you have mistakenly deleted a large number of records from your production system
in Salesforce and need to restore them from the recycle bin without informing your
manager, here are the steps you can take:
• To identify the deleted records, you can use the "Deleted Objects" feature in
Salesforce. This feature provides a list of recently deleted records in your org.
• From the Salesforce setup menu, search for "Deleted Objects" and select it.
• Look for the object related to the deleted records and click on it to view the deleted
records.
• Select and Restore Records:
• In the "Deleted Objects" view, select the records you want to restore. You can filter
or search for specific records if needed.
• Once you have selected the records, click on the "Undelete" button to restore them.
• Note that you can only restore records that are still within the retention period
(typically 15 days) since their deletion.
• If you need to query the data from the recycle bin programmatically, you can use the
"ALL ROWS" clause in Salesforce SOQL queries. This clause allows you to retrieve
both active records and records in the recycle bin.
• Construct a SOQL query using the object and fields relevant to the deleted records
you want to retrieve. Include the "ALL ROWS" clause in the query.
• Execute the query through the Salesforce API, Apex code, or tools like Salesforce
Workbench or Developer Console.
• The query results will include both active records and records from the recycle bin.
You can identify the deleted records based on their IsDeleted field, which will be set
to "true" for deleted records.
• Additionally, always ensure that you have the necessary permissions and access
privileges to perform these actions in your Salesforce org.
What is OWD? What are the difference types of access we have in OWD?
Ans: In Salesforce, OWD stands for "Organization-Wide Default." It refers to the default level
of access granted to records in an organization. OWD settings determine the baseline level
of access that all users have to records within the organization.
OWD settings control the visibility and sharing of records among users. There are three
different types of OWD settings:
• Private:
With the "Private" OWD setting, the most restrictive level, each record is only visible to its
owner. Only the owner and users with higher-level access (such as administrators or users
higher in the role hierarchy) can access the record.
Other users, even within the same organization, cannot access or view the record unless
explicitly granted access through sharing rules, manual sharing, or other mechanisms.
• With the "Public Read Only" OWD setting, records are accessible to all users within the
organization, but they can only be viewed.
• Users can see the records, but they cannot make any modifications or changes to them
unless they are the owner or have been granted additional access through other
mechanisms (e.g., sharing rules, manual sharing, or permission sets).
• Public Read/Write:
• The "Public Read/Write" OWD setting provides the most open level of access. All users
within the organization can view and modify (read/write) the records by default.
• With this setting, users can access and edit records they don't own. However, more
granular sharing settings, like sharing rules and manual sharing, can still be used to further
control access
OWD settings define the baseline access level for records, and additional sharing
mechanisms can be used to grant more specific and controlled access to records based on
business requirements and security considerations. It's important to carefully evaluate and
set OWD settings to align with the organization's data access and privacy needs.
You have custom object and its private. So what it means in salesforce in terms of record
level access?
Ans: In Salesforce, if a custom object has its Organization-Wide Default (OWD) setting set to
"Private," it means that the record-level access for that custom object is restricted to the
owner of the record. Let's explore what this means in terms of record-level access:
• Only the Owner Can Access: With the "Private" OWD setting, records of the custom
object can only be accessed by the user who owns the record. Other users within the
organization, even if they have access to the custom object's tab or related lists,
cannot view or modify these records by default.
• Higher-Level Access Overrides: Users with higher-level access, such as administrators
or users higher in the role hierarchy, can access and modify the records owned by
other users. These users can see all records of the custom object, regardless of
ownership.
• Sharing Rules and Manual Sharing: To grant access to specific records owned by
others, additional sharing mechanisms like sharing rules or manual sharing can be
utilized. Sharing rules can be set up to automatically share records with certain
criteria to specified groups or roles. Manual sharing allows the owner or
administrators to manually share specific records with other users or groups.
• Implicit Sharing via Parent Objects: If the custom object has a parent-child
relationship with another object, such as a master-detail or lookup relationship, the
record-level access to the custom object's records can be affected by the parent's
OWD setting. For example, if the parent object has a "Public Read/Write" OWD
setting, the child records will inherit the same access level.
• By setting the OWD for a custom object to "Private," organizations can enforce strict
access control, ensuring that only the record owners can view and modify their
respective records. This setting is often used to maintain data privacy and
confidentiality, particularly for sensitive or confidential information.
• It's important to carefully consider the business requirements, data sensitivity, and
security needs when determining the OWD settings for custom objects in Salesforce.
Additional sharing mechanisms can be utilized to grant access to specific records as
needed.
What is the difference between With sharing and without sharing in salesforce?
Ans: In Salesforce, "with sharing" and "without sharing" are keywords used in Apex classes
to define the sharing rules that determine how records are accessed and shared among
users. Here's the difference between "with sharing" and "without sharing":
With sharing:
• When a class is declared with the "with sharing" keyword, it enforces the
organization's sharing rules and record-level access permissions.
• Apex code within the class respects the sharing settings and ensures that users only
have access to records they are authorized to see based on their profile, role, sharing
rules, and other factors.
• This keyword enforces record-level security and applies the organization's sharing
settings even if the code is executed by a user with higher privileges, such as an
administrator.
Without sharing:
• When a class is declared with the "without sharing" keyword, it bypasses the
organization's sharing rules and grants unrestricted access to records.
• Apex code within the class operates in system mode, disregarding the user's
permissions and sharing settings.
• This keyword allows developers to perform operations and access records that might
not be accessible under normal sharing rules. It is typically used in specific scenarios
where the business requirements necessitate bypassing the default sharing rules.
• In summary, the main difference between "with sharing" and "without sharing" is
how they handle record-level access and sharing rules:
• "with sharing" respects the organization's sharing rules and enforces record-level
security.
• "without sharing" bypasses the sharing rules, providing unrestricted access to
records and operating in system mode.
It's important to use these keywords appropriately based on the specific requirements of the
Apex class to ensure proper data security and adherence to the organization's sharing
policies.
Yes, Apex classes are by default executed in system mode, which means they operate
without sharing. This is true unless specified otherwise by using the "with sharing" keyword
in the class declaration.
If an Apex class does not have either "with sharing" or "without sharing" specified, it will
default to "without sharing." In this mode, Apex code bypasses the organization's sharing
rules and accesses records with unrestricted privileges. The code operates in system mode,
ignoring the user's profile, sharing settings, and record-level access permissions.
It's important to be cautious when using the "without sharing" mode, as it can potentially
bypass important security measures and expose sensitive data. It is recommended to
carefully consider the sharing requirements and apply the appropriate sharing mode ("with
sharing" or "without sharing") based on the specific needs and security considerations of
your application.
Class B is inside class A. Class A is withsharing and Class B is there. So what class B runs in?
Ans: In Salesforce, when Class B is defined inside Class A and Class A is declared with the
"with sharing" keyword, Class B will inherit the sharing settings of Class A. This means that
Class B will also run with sharing, and the record-level access will be enforced based on the
sharing rules and organization-wide default (OWD) settings defined for Class A.
What is Named credential?
Ans: A named credential is a Salesforce object that stores the authentication information for
a specific external service. This information can include the service's URL, username,
password, and any other required credentials. Named credentials can be used to make
authenticated callouts to external services from Apex code.
Ans: The "SOQL Too Many" error, commonly known as "SOQL 101 Error" or "Query Limit
Exception," occurs when you exceed the maximum number of SOQL queries allowed within
a single transaction.
Salesforce imposes governor limits to ensure efficient resource utilization and to prevent
overloading the system. The specific limit for SOQL queries in a single transaction depends
on the context in which the code is executed:
To avoid this error and optimize your code, consider the following best practices:
• Bulkify Your Code: Ensure that your code is designed to handle multiple records
efficiently. Avoid performing queries or DML operations within loops, as this can
quickly consume SOQL queries and other governor limits. Instead use collections
such as lists or sets, to process records in bulk.
• Reduce the Number of Queries: Analyze your code and see if you can optimize the
logic to reduce the number of queries required. For example, instead of querying
related records for each parent record in a loop, consider using relationship queries
or aggregate queries to retrieve the necessary data in a single query.
• Consider Using Collections and Maps: Use collections (e.g., lists, sets, maps) to store
queried records and reuse the data as needed, instead of querying the same
information multiple times.
• Utilize Selective SOQL Queries: Optimize your queries by making them selective and
filtering based on indexed fields. Selective queries have a lower impact on governor
limits and perform more efficiently.
• Evaluate Trigger Execution: When working with triggers, ensure they are properly
designed to handle bulk data and avoid recursive triggers.
These best practices and optimizing your code, you can reduce the number of SOQL queries
and minimize the chances of encountering the "SOQL Too Many" error.
Suppose you are getting too many SOQL 101 error while updating the record in the trigger.
How will you identify the error?
Ans: When encountering the "SOQL Too Many" error (SOQL 101 Error) in a trigger, you can
identify the cause and location of the error by following these steps:
• Review the Error Message: When the error occurs, Salesforce will provide an
exception message indicating the cause of the error. The error message will typically
state "System.LimitException: Too many SOQL queries: XX". Take note of the number
mentioned in the error message, as it indicates how many SOQL queries were
executed.
• Analyze the Trigger Code: Examine the trigger code to identify any potential areas
where multiple SOQL queries might be executed. Look for queries inside loops,
queries within recursive methods, or any other scenarios where queries are called
repeatedly for each record.
• Check for Nested Queries: Verify if there are any nested queries within the trigger
code. Nested queries occur when one query is executed inside a loop that iterates
over records from another query. This can quickly lead to exceeding the SOQL query
limit.
Ans: There are many use cases when we can use the future methods in Salesforce.
• Avoid the CPU time limit Error: To avoid the log running talk and avoid the CPU time
limit we can use the @Future method in Salesforce. Learn more about Apex CPU
Time Limit Exceeded.
• Callout from Trigger: As we know we cannot do the callout from the trigger but we
can invoke callouts from triggers by encapsulating the callouts in @future methods.
• Avoid Mixed DML operation: A Mixed DML operation error occurs when you try to
persist in the same transaction, change to a Setup Object, and a non-Setup Object.
• You can also make use of future methods to isolate DML operations on different
sObject types to prevent the mixed DML error.
• Higher governor limit: A benefit of using future methods is that some governor limits
are higher, such as SOQL query limits and heap size limits.
• From another Apex class: This is the most common way to call an Apex class. You can
use the static keyword to call a static method in another class, or you can use the
new keyword to create a new instance of the class and then call a method on that
instance.
• From a Visualforce page: You can use the apex:action Function tag to call an Apex
class from a Visualforce page. This tag takes two attributes: the name of the Apex
class and the name of the method to call.
• From a web service: You can expose an Apex class as a web service. This allows you
to call the class from external applications.
• From the Developer Console: You can use the Developer Console to call an Apex
class. This is a good way to test your code before you deploy it to production.
• From a JavaScript button: You can use a JavaScript button to call an Apex class. This
is a good way to call an Apex class from a web page that is not a Visualforce page.
What is the Application event and component event in LWC. Can you explain the bundle
In Lightning Web Components (LWC), both application events and component events are
mechanisms for communication between different components within a Salesforce Lightning
application. They allow you to pass data and trigger actions across component boundaries.
Application Event:
An application event is an event that can be fired from one component and listened to by
any component within the same Lightning App. It enables communication between
components that are not directly related in the component hierarchy. Application events are
useful when you want to communicate between components that might be distant from
each other in the component tree.
• Listen for and handle the application event in other components using the
lightning:addEventListener method.
Component Event:
A component event is an event that is fired from a parent component and can be listened to
only by its child components. It allows communication between a parent component and its
direct child components.
Bulkifying" a trigger in Salesforce means optimizing the trigger code to handle multiple
records at once, known as bulk operations. This ensures that the trigger performs efficiently
and doesn't hit governor limits when processing a large number of records.
When users or processes perform actions that involve multiple records, such as inserting,
updating, or deleting records in bulk, triggers are invoked for each record. If the trigger code
is not optimized for bulk operations, it can lead to performance issues, increased processing
time, and even hitting Salesforce's governor limits, which could cause the trigger to fail.
• Loops: Avoid using unnecessary loops inside triggers. Instead, try to process records
using set-based operations whenever possible. Collections: Use collections like sets
and maps to hold records and data. These collections allow for more efficient
processing of multiple records.
• Querying Outside Loops: Avoid querying the database within a loop. If you need
related data, query it outside the loop and store it in a map or list for reference.
• Governor Limits: Be mindful of Salesforce's governor limits, such as the limit on the
number of SOQL queries or DML operations in a single transaction. Bulkifying helps
you stay within these limits.
A Flexipage is a type of Lightning page that is used to create custom pages in Salesforce.
Flexipages are made up of regions, which are containers for components. Components are
the building blocks of Flexipages, and they can be used to display data, interact with users,
and perform actions.
Flexipages are a powerful way to create custom pages in Salesforce. They allow you to use a
variety of components to create a rich and interactive user experience. Flexipages are also
easy to develop and maintain, and they can be reused across different Salesforce
applications.
• Flexibility: Flexipages are highly flexible and can be used to create a variety of
different page layouts.
• Reusability: Flexipages can be reused across different Salesforce applications, which
saves time and effort.
• Ease of development: Flexipages are easy to develop and maintain, even for
developers with limited experience.
• Performance: Flexipages are efficient and do not impact the performance of your
Salesforse application.
Lookup Relationship:
Master-Detail Relationship:
In Salesforce, Batch Apex, Queueable Apex, and Future methods are mechanisms for
handling asynchronous processing, but they have some key differences:
Batch Apex:
• Purpose: Used for processing large sets of data in smaller, manageable chunks.
• Governor Limits: Can process up to 50 million records with a maximum of 200
records per batch.
• Usage: Ideal for scenarios where you need to process large volumes of records and
avoid hitting governor limits.
• Example: Mass updating or deleting records, complex calculations, data cleansing.
Queueable Apex:
• Purpose: Used for executing a single job in the background, which can be enqueued
after the current transaction is complete. Governor Limits: Can process up to 50 jobs
in a single transaction.
• Usage: Ideal for scenarios where you need to perform one-off, non-batchable
operations asynchronously.
• Example: Sending emails, making callouts, performing long-running operations.
@future Methods:
• Purpose: Used for making asynchronous callouts from Salesforce to external systems.
• Governor Limits: Can make up to 50 future calls in a single transaction.
• Usage: Ideal for scenarios where you need to make HTTP requests to external
services asynchronously. Example: Integrating with external APIs, web services.
@future
MyFutureClass.myFutureMethod(param);
Key Points:
• Batch Apex is best suited for processing large data sets in smaller chunks.
• Queueable Apex is used for executing single jobs in the background, and it's more
flexible than Batch Apex.
• Future methods are primarily used for making asynchronous callouts to external
services.
• Decision elements: Decision elements allow you to make decisions based on the
values of variables or the results of other flow elements.
• Assignment elements: Assignment elements allow you to assign values to variables
or update Salesforce records. • Wait elements: Wait elements allow you to pause the
flow for a specified amount of time.
• Screen elements: Screen elements allow you to display information to the user or
collect input from the user.
• Action elements: Action elements allow you to perform actions, such as sending
emails or updating Salesforce records.
• Flow control elements: Flow control elements allow you to control the flow of the
flow, such as looping through a set of records or branching to a different section of
the flow.
Can we call another batch class from start and execute method as well?
What will happen if error occurs in 2nd batch transaction then, further batch transactions
will execute or not?
• Yes, rest all batches will be executed because each batch is considered as a discrete
transaction.
What kind of relationship is there between Account and Opportunity/Contact?
• A special kind of lookup relationship or Hybrid relationship that has features of both
lookup and MDR.
What are the advantages of using Named credentials over remote site settings
• •Can specifies the API endpoint and its required authentication parameters in one
definition.
• ·Remote site settings not required if we are using Named credentials
• Don't need to provide Username and password everywhere in code.
• Easier to maintain because if something will get changed in future than only need to
make changes in Named credentials.
Assume we have 10 managed package installed in our org and all they have triggers on
account object and each trigger has 10 SQOL queries and I am also creating 1 custom
trigger with 5 SOQL, so will it work or throw Too many SQOL queries:101 error?
Assume we have two triggers on same object, one is created in managed package and
another is custom trigger and I want to call custom trigger prior to managed package
trigger, so how can I achieve this?
No
Can we call future method anyhow in batch class?
• No
• If really required then we can call it via webservices
Suppose we have a validation rule on Account object, to make website field required and
on same Account object, we have a validation rule to make website field blank.
Assume we have a lead and owner of lead is Queue than after conversion who will be
owner of the Opportunity/Account/Contact?
• User Mode
• Yes we can
PermissionsetAssigment psa=new
PermissionsetAssigment(PermissionsetId=mypersmissionSetId,AssignedId=myAssignedId); ,
insert psa
Difference between Abstract class and Interface?
• Abstract class will have an abstract method as a must but also have methods with
Body in that class.
• In Interface class method without Body.It will have only signature of the method.
• Strongly typed language means we must tell the compiler the data type before we
ask for a variable to be defined.
What is the Max Characters that can be used in URL mapping?
• 255
@Restresource(urlMapping=’test’ ) -→ 25