<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Divyansh Kotnala on Medium]]></title>
        <description><![CDATA[Stories by Divyansh Kotnala on Medium]]></description>
        <link>https://medium.com/@kotnalacooldivyansh?source=rss-7f8e18d2273a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*58G_GJbtFoVlHjWnIqBTYw.jpeg</url>
            <title>Stories by Divyansh Kotnala on Medium</title>
            <link>https://medium.com/@kotnalacooldivyansh?source=rss-7f8e18d2273a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:06:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kotnalacooldivyansh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 SOQL Query Challenges (With Solutions)]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/10-soql-query-challenges-with-solutions-e4b2493312b1?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b2493312b1</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-soql]]></category>
            <category><![CDATA[soql-question]]></category>
            <category><![CDATA[soql]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-11-30T14:31:01.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*77DN6WN9PAYbwzzkWUBhKw.jpeg" /></figure><p><em>Ten practice problems where you write the query. Try each one yourself first, then check the answer.</em></p><p>The best way to learn SOQL is to write it. Each challenge below gives you a task, a solution you can paste into the Developer Console Query Editor, and a short explanation of why it works. The challenges move from simple filtering to relationships and finally to aggregate queries.</p><p>They use standard objects (Account, Contact, Opportunity, Lead) so they run in any Developer Edition org or sandbox.</p><h3>Challenge 1: Filter with LIKE and IN</h3><p><strong>Task:</strong> Get the name and industry of every account whose name starts with “Acme” and whose industry is either Technology or Finance.</p><p><strong>Answer:</strong></p><pre>SELECT Name, Industry<br>FROM Account<br>WHERE Name LIKE &#39;Acme%&#39;<br>AND Industry IN (&#39;Technology&#39;, &#39;Finance&#39;)</pre><p><strong>Why it works:</strong> LIKE with the % wildcard matches names that begin with the text. IN checks a field against a list of values, which is cleaner than chaining OR conditions.</p><h3>Challenge 2: Sort and limit</h3><p><strong>Task:</strong> Show the 5 most recently created contacts.</p><p><strong>Answer:</strong></p><pre>SELECT Id, FirstName, LastName, CreatedDate<br>FROM Contact<br>ORDER BY CreatedDate DESC<br>LIMIT 5</pre><p><strong>Why it works:</strong> ORDER BY ... DESC puts the newest records first, and LIMIT 5 keeps only the first five rows.</p><h3>Challenge 3: Date literals</h3><p><strong>Task:</strong> Find all opportunities that close this month and have an amount greater than 10,000.</p><p><strong>Answer:</strong></p><pre>SELECT Name, Amount, CloseDate, StageName<br>FROM Opportunity<br>WHERE CloseDate = THIS_MONTH<br>AND Amount &gt; 10000</pre><p><strong>Why it works:</strong> SOQL has built-in date literals such as TODAY, THIS_MONTH, LAST_N_DAYS:30 and NEXT_QUARTER. They save you from hard-coding dates and keep the query correct as time passes.</p><h3>Challenge 4: Child to parent (dot notation)</h3><p><strong>Task:</strong> List contacts together with the name and industry of their parent account.</p><p><strong>Answer:</strong></p><pre>SELECT FirstName, LastName, Account.Name, Account.Industry<br>FROM Contact<br>WHERE AccountId != null</pre><p><strong>Why it works:</strong> From the child object (Contact) you reach the parent (Account) with dot notation. The WHERE AccountId != null filter removes contacts that have no account, which would otherwise show empty parent values.</p><h3>Challenge 5: Parent to child (subquery)</h3><p><strong>Task:</strong> List each account with its contacts’ last names and emails.</p><p><strong>Answer:</strong></p><pre>SELECT Name, (SELECT LastName, Email FROM Contacts)<br>FROM Account</pre><p><strong>Why it works:</strong> The inner query uses the child relationship name, which is usually the plural of the object name (Contacts). Each account row comes back with a nested list of its contacts.</p><h3>Challenge 6: Semi-join (records that have related records)</h3><p><strong>Task:</strong> Find only the accounts that have at least one contact.</p><p><strong>Answer:</strong></p><pre>SELECT Id, Name<br>FROM Account<br>WHERE Id IN (SELECT AccountId FROM Contact)</pre><p><strong>Why it works:</strong> The subquery returns the IDs of accounts that appear on contacts, and the outer query keeps only those accounts. This pattern is called a semi-join.</p><h3>Challenge 7: Anti-join (records that have no related records)</h3><p><strong>Task:</strong> Find accounts that have no opportunities at all.</p><p><strong>Answer:</strong></p><pre>SELECT Id, Name<br>FROM Account<br>WHERE Id NOT IN (SELECT AccountId FROM Opportunity)</pre><p><strong>Why it works:</strong> It is the opposite of Challenge 6. NOT IN removes any account whose ID appears in the opportunity subquery. This is useful for finding accounts that need sales attention.</p><h3>Challenge 8: Aggregate with SUM</h3><p><strong>Task:</strong> Calculate the total value of all closed-won opportunities.</p><p><strong>Answer:</strong></p><pre>SELECT SUM(Amount) total<br>FROM Opportunity<br>WHERE IsWon = true</pre><p><strong>Why it works:</strong> SUM() adds up the Amount field in the database and returns one row. The alias total is how you would read the value in Apex (ar.get(&#39;total&#39;)). Note that aggregate functions ignore null amounts.</p><h3>Challenge 9: GROUP BY with COUNT</h3><p><strong>Task:</strong> Count how many opportunities exist in each stage, along with the total amount per stage.</p><p><strong>Answer:</strong></p><pre>SELECT StageName, COUNT(Id) deals, SUM(Amount) total<br>FROM Opportunity<br>GROUP BY StageName</pre><p><strong>Why it works:</strong> GROUP BY StageName creates one result row per stage. Every non-aggregated field in the SELECT list (here, StageName) must appear in GROUP BY. Aliases give each aggregate a stable name.</p><h3>Challenge 10: HAVING to find duplicates</h3><p><strong>Task:</strong> Find lead email addresses that appear more than once.</p><p><strong>Answer:</strong></p><pre>SELECT Email, COUNT(Id) duplicates<br>FROM Lead<br>WHERE Email != null<br>GROUP BY Email<br>HAVING COUNT(Id) &gt; 1</pre><p><strong>Why it works:</strong> WHERE filters records before grouping (here, it removes leads without an email). HAVING filters groups after aggregation, so it keeps only emails that occur more than once. A variation is to group accounts and keep those with more than five contacts: SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) &gt; 5.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b2493312b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Salesforce LWC Interview Questions & Answers]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/top-10-salesforce-lwc-interview-questions-answers-f44f5f8657e8?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f44f5f8657e8</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-lwc]]></category>
            <category><![CDATA[salesforce-interview]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[lwc-interview-question]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-11-30T14:31:01.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Lightning Web Component (LWC)?</h3><p><strong>Answer:</strong></p><p>Lightning Web Components (LWC) is a Salesforce UI framework used to build reusable and efficient user interface components.</p><p>It is based on modern web standards such as JavaScript, HTML, and CSS, and uses Web Components standards.</p><p><strong>Key features:</strong></p><ul><li>Reusable components.</li><li>Modern JavaScript.</li><li>Component-based architecture.</li><li>Communication between components.</li><li>Integration with Apex and Salesforce data.</li></ul><h3>2. What are decorators in LWC?</h3><p><strong>Answer:</strong></p><p>Decorators add special functionality to JavaScript properties and methods.</p><p>There are three commonly used decorators:</p><p>DecoratorPurpose@apiMakes a property or method public and accessible to the parent component.@trackTracks changes inside plain objects and arrays, including nested properties.@wireConnects a component to a Salesforce data source or Apex method reactively.</p><p>Example:</p><pre>import { LightningElement, api, track, wire } from &#39;lwc&#39;;</pre><pre>export default class MyComponent extends LightningElement {<br>    @api recordId;</pre><pre>    @track user = {<br>        name: &#39;John&#39;<br>    };<br>}</pre><p><strong>Important:</strong> Primitive fields are reactive by default. For objects and arrays, assigning a new value is generally sufficient; @track is useful when you need to observe nested mutations.</p><h3>3. What is the difference between @wire and imperative Apex?</h3><p><strong>Answer:</strong></p><p>Both are used to call Apex methods from LWC, but their execution approaches are different.</p><p>@wireImperative ApexReactive approachManual invocationAutomatically provisions dataCalled when requiredReturns a property or callback resultReturns a PromiseSuitable for read operationsSuitable for controlled executionRequires cacheable=true for Apex methodsCan call cacheable or non-cacheable Apex methods</p><p><strong>Wire Example:</strong></p><pre>import { LightningElement, wire } from &#39;lwc&#39;;<br>import getAccounts from &#39;@salesforce/apex/AccountController.getAccounts&#39;;</pre><pre>export default class AccountList extends LightningElement {<br>    @wire(getAccounts)<br>    accounts;<br>}</pre><p><strong>Imperative Example:</strong></p><pre>import { LightningElement } from &#39;lwc&#39;;<br>import getAccounts from &#39;@salesforce/apex/AccountController.getAccounts&#39;;</pre><pre>export default class AccountList extends LightningElement {</pre><pre>    accounts;</pre><pre>    handleClick() {<br>        getAccounts()<br>            .then(result =&gt; {<br>                this.accounts = result;<br>            })<br>            .catch(error =&gt; {<br>                console.error(error);<br>            });<br>    }<br>}</pre><h3>4. What are lifecycle hooks in LWC?</h3><p><strong>Answer:</strong></p><p>Lifecycle hooks are special methods that execute at different stages of a component’s lifecycle.</p><p>Important lifecycle hooks:</p><p>HookPurpose</p><p>constructor() — Initializes the component.</p><p>connectedCallback() — Executes when the component is inserted into the DOM.</p><p>renderedCallback()- Executes after the component renders.</p><p>disconnectedCallback()- Executes when the component is removed from the DOM.</p><p>errorCallback()- Handles errors from descendant components.</p><p><strong>Example:</strong></p><pre>connectedCallback() {<br>    console.log(&#39;Component connected&#39;);<br>}</pre><pre>renderedCallback() {<br>    console.log(&#39;Component rendered&#39;);<br>}</pre><p><strong>Interview tip:</strong> Avoid updating reactive state repeatedly inside renderedCallback() because it can cause unnecessary re-rendering or an infinite rendering loop.</p><h3>5. How do you communicate between components in LWC?</h3><p><strong>Answer:</strong></p><p>Communication depends on the relationship between components.</p><p><strong>Parent to Child:</strong><br>Use @api properties or public methods.</p><p>Child component:</p><pre>import { LightningElement, api } from &#39;lwc&#39;;</pre><pre>export default class ChildComponent extends LightningElement {<br>    @api message;<br>}</pre><p><strong>Child to Parent:</strong><br>Use Custom Events.</p><p>Child component:</p><pre>this.dispatchEvent(<br>    new CustomEvent(&#39;sendmessage&#39;, {<br>        detail: &#39;Hello Parent&#39;<br>    })<br>);</pre><p>Parent HTML:</p><pre>&lt;c-child-component<br>    onsendmessage={handleMessage}&gt;<br>&lt;/c-child-component&gt;</pre><p><strong>Sibling Components:</strong><br>Communicate through a common parent.</p><p><strong>Unrelated Components:</strong><br>Use Lightning Message Service (LMS).</p><h3>6. What is the difference between connectedCallback() and renderedCallback()?</h3><p><strong>Answer:</strong></p><ul><li>connectedCallback() executes when the component is inserted into the DOM. It is generally used for initialization and setting up subscriptions.</li><li>renderedCallback() executes after the component has rendered. It is useful for DOM-related operations and third-party library initialization.</li></ul><p><strong>Key difference:</strong> connectedCallback() runs before rendering, whereas renderedCallback() runs after rendering.</p><h3>7. What is the use of key in LWC for iteration?</h3><p><strong>Answer:</strong></p><p>The key attribute uniquely identifies each item in an iterated list.</p><p>It helps the LWC rendering engine identify which items have changed, been added, or removed.</p><p>Example:</p><pre>&lt;template for:each={accounts} for:item=&quot;acc&quot;&gt;<br>    &lt;p key={acc.Id}&gt;<br>        {acc.Name}<br>    &lt;/p&gt;<br>&lt;/template&gt;</pre><p><strong>Important:</strong> Always provide a unique and stable key. Do not use the array index as the key.</p><h3>8. What is Lightning Data Service (LDS)?</h3><p><strong>Answer:</strong></p><p>Lightning Data Service is used to create, read, update, and delete Salesforce records without writing Apex.</p><p>It handles record data access and helps manage caching and sharing/security enforcement.</p><p>Common LDS functions:</p><ul><li>getRecord</li><li>getFieldValue</li><li>createRecord</li><li>updateRecord</li><li>deleteRecord</li></ul><p>Example:</p><pre>import { getRecord } from &#39;lightning/uiRecordApi&#39;;<br>import NAME_FIELD from &#39;@salesforce/schema/Account.Name&#39;;<br>import { wire } from &#39;lwc&#39;;<br>import { LightningElement, api } from &#39;lwc&#39;;</pre><pre>export default class AccountDetails extends LightningElement {<br>    @api recordId;</pre><pre>    @wire(getRecord, {<br>        recordId: &#39;$recordId&#39;,<br>        fields: [NAME_FIELD]<br>    })<br>    account;<br>}</pre><h3>9. What is the difference between conditional rendering and iteration in LWC?</h3><p><strong>Answer:</strong></p><p>Conditional rendering displays elements based on a Boolean condition, whereas iteration displays multiple elements using an array.</p><p><strong>Conditional Rendering:</strong></p><pre>&lt;template lwc:if={showMessage}&gt;<br>    &lt;p&gt;Hello Salesforce&lt;/p&gt;<br>&lt;/template&gt;</pre><p><strong>Iteration:</strong></p><pre>&lt;template for:each={accounts} for:item=&quot;acc&quot;&gt;<br>    &lt;p key={acc.Id}&gt;{acc.Name}&lt;/p&gt;<br>&lt;/template&gt;</pre><h3>10. How do you handle errors in LWC when calling Apex?</h3><p><strong>Answer:</strong></p><p>Errors can be handled using JavaScript’s try-catch with async/await or .catch() with Prom</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f44f5f8657e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 SOQL Questions and Answers]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/top-10-soql-questions-and-answers-15b006657fe4?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/15b006657fe4</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-interview]]></category>
            <category><![CDATA[salesforce-soql]]></category>
            <category><![CDATA[soql]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 05:47:14 GMT</pubDate>
            <atom:updated>2026-11-29T05:47:14.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is SOQL, and how is it different from SQL?</h3><p>SOQL (Salesforce Object Query Language) is the query language for reading data from Salesforce objects. It looks like SQL but has important differences:</p><ul><li>You query <strong>objects and fields</strong>, not tables and columns.</li><li>There is no SELECT *. You must list the fields you want.</li><li>It is <strong>read-only</strong>. Changes to data use DML (insert, update, delete) or the API.</li><li>There are no free-form joins. You traverse <strong>relationships</strong> instead (see question 8).</li><li>It runs under platform limits, so queries must be written with volume in mind.</li></ul><pre>SELECT Id, Name, Industry FROM Account WHERE Industry = &#39;Technology&#39;</pre><h3>2. What is the difference between SOQL and SOSL?</h3><p>SOQL queries one object (plus its related objects) and filters by field values. SOSL (Salesforce Object Search Language) searches for text across <strong>multiple objects and fields at once</strong>, like a search box.</p><ul><li>Use <strong>SOQL</strong> when you know which object holds the data and want precise filtering, sorting or summarizing.</li><li>Use <strong>SOSL</strong> when you need to find a keyword across many objects.</li></ul><pre>FIND &#39;Acme*&#39; IN ALL FIELDS RETURNING Account(Name), Contact(Name, Email)</pre><h3>3. What are the aggregate functions in SOQL?</h3><p>Six are supported:</p><p>Function</p><p>Returns</p><p>AVG()</p><p>Average of a numeric field</p><p>COUNT() / COUNT(field)</p><p>Number of matching rows</p><p>COUNT_DISTINCT()</p><p>Number of distinct non-null values</p><p>MIN()</p><p>Smallest value</p><p>MAX()</p><p>Largest value</p><p>SUM()</p><p>Total of a numeric field</p><p>They work with or without GROUP BY, but they are most useful with it:</p><pre>SELECT StageName, SUM(Amount) FROM Opportunity GROUP BY StageName</pre><p>By the official reference, all aggregate functions ignore nulls except COUNT() and COUNT(Id). MIN() and MAX() on a picklist use the picklist&#39;s sort order, not alphabetical order. Not all field types are supported: numeric fields support everything, while strings, dates and picklists support COUNT, COUNT_DISTINCT, MIN and MAX only.</p><h3>4. What is the difference between COUNT(), COUNT(Id) and COUNT(fieldName)?</h3><p>COUNT() and COUNT(Id) count rows, similar to COUNT(*) in SQL. COUNT(fieldName) counts only rows where that field is <strong>not null</strong>.</p><pre>SELECT COUNT() FROM Contact            -- all contacts<br>SELECT COUNT(Phone) FROM Contact       -- contacts that have a phone</pre><p>There is also a limits benefit: an ungrouped COUNT() query is counted as one query row regardless of how many records it counted.</p><h3>5. How do you read aggregate results in Apex, and why use an alias?</h3><p>An aggregate query returns AggregateResult objects (read-only sObjects). You read values with get(), which returns Object, so you cast it.</p><pre>AggregateResult[] rows = [<br>    SELECT StageName stage, SUM(Amount) total<br>    FROM Opportunity<br>    GROUP BY StageName<br>];<br>for (AggregateResult r : rows) {<br>    String stage = (String) r.get(&#39;stage&#39;);<br>    Decimal total = (Decimal) r.get(&#39;total&#39;);<br>}</pre><p>Without an alias, Salesforce assigns an implied name in the form expr0, expr1, and so on, numbered by position among the unaliased aggregates. If someone reorders the query, get(&#39;expr0&#39;) quietly points at a different value. Aliases make the code readable and safe.</p><h3>6. Can you use LIMIT with an aggregate query?</h3><p>Not when the query uses an aggregate function <strong>without</strong> GROUP BY. This is invalid:</p><pre>SELECT MAX(CreatedDate) FROM Account LIMIT 1</pre><p>It is also pointless, since an ungrouped aggregate already returns a single row. With GROUP BY, LIMIT is allowed and limits the number of groups returned.</p><h3>7. What is the difference between WHERE and HAVING?</h3><p>WHERE filters <strong>records before</strong> they are grouped. HAVING filters <strong>groups after</strong> aggregation, so it is the only way to filter on an aggregate result.</p><pre>-- accounts that have more than 5 contacts<br>SELECT AccountId, COUNT(Id) total<br>FROM Contact<br>WHERE AccountId != null<br>GROUP BY AccountId<br>HAVING COUNT(Id) &gt; 5</pre><p>A typical use is finding duplicates: group by the field, then keep groups with HAVING COUNT(Id) &gt; 1.</p><h3>8. How do relationship queries work?</h3><p>Two directions:</p><p><strong>Child to parent</strong> uses dot notation:</p><pre>SELECT Name, Account.Name, Account.Industry FROM Contact</pre><p><strong>Parent to child</strong> uses a subquery on the child relationship name (usually the plural):</p><pre>SELECT Name, (SELECT LastName, Email FROM Contacts) FROM Account</pre><p>This replaces the join you would write in SQL. Custom relationships use the __r suffix on the relationship name.</p><h3>9. How do governor limits affect SOQL, and what is the bulkification rule?</h3><p>Apex runs in a shared multi-tenant environment, so each transaction has limits. Commonly cited synchronous limits include 100 SOQL queries per transaction and 50,000 records retrieved (confirm current values in the Apex governor limits documentation for your release).</p><p>The rule: <strong>never put a SOQL query inside a loop.</strong> Query once for the whole set, then use a Map or Set in memory.</p><pre>// Bad: one query per record<br>for (Contact c : contacts) {<br>    Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];<br>}</pre><pre>// Good: one query for all<br>Set&lt;Id&gt; ids = new Set&lt;Id&gt;();<br>for (Contact c : contacts) ids.add(c.AccountId);<br>Map&lt;Id, Account&gt; accounts =<br>    new Map&lt;Id, Account&gt;([SELECT Name FROM Account WHERE Id IN :ids]);</pre><p>For aggregates, remember the accounting: ungrouped COUNT() counts as one row, grouped COUNT counts one row per group, and the other aggregate functions count each row they use. So SUM() over a huge table can still consume your row budget even though it returns one result.</p><h3>10. How do you keep SOQL secure?</h3><p>There are two concerns: <strong>injection</strong> and <strong>data access</strong>.</p><p><strong>Injection.</strong> Prefer static SOQL with <strong>bind variables</strong>, which treat the value as data and not as query text:</p><pre>String name = userInput;<br>List&lt;Account&gt; result = [SELECT Id FROM Account WHERE Name = :name];</pre><p>If you must build a dynamic query string, bind variables still work with Database.queryWithBinds, and otherwise you must escape input, for example with String.escapeSingleQuotes().</p><p><strong>Data access.</strong> Apex runs in system mode by default, which can ignore the user’s field and object permissions. Adding WITH USER_MODE makes the query respect the running user&#39;s permissions (the Apex Developer Guide&#39;s aggregate examples use it):</p><pre>SELECT AVG(Amount) avgAmt FROM Opportunity WITH USER_MODE</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15b006657fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Looping, Start Aggregating: A Practical Guide to Salesforce SOQL Aggregate Queries]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/stop-looping-start-aggregating-a-practical-guide-to-salesforce-soql-aggregate-queries-82dd650f8099?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82dd650f8099</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[soql]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <category><![CDATA[salesforce-soql]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 05:22:15 GMT</pubDate>
            <atom:updated>2026-11-29T05:22:15.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*FeHfxMzg21DetSBn0nG42g.png" /></figure><p><em>How to summarize millions of records in one query, the traps that catch most developers, and why this one feature changes how you build on Salesforce.</em></p><h3>The 40,000-row mistake</h3><p>Picture a familiar scene (this is an illustrative scenario, not a real incident). A sales manager asks for the total value of all open opportunities over 60% probability. A developer writes an Apex loop: query every matching opportunity, add up the A<em>How to summarize millions of records in one query, the traps that catch most developers, and why this one feature changes how you build on Salesforce.</em></p><p>mount field one record at a time, return the number. It works in the sandbox with 200 records. In production, with tens of thousands of records, it gets slow, burns through memory, and eventually hits a platform limit.</p><p>The fix is a single line of SOQL. The database does the arithmetic and sends back one number. That is what aggregate queries are for, and the Apex Developer Guide describes them simply: aggregate functions such as SUM() and MAX() let you roll up and summarize data inside a query.</p><p>This article teaches you how they work, step by step, and then looks at their real impact on performance, reporting, data quality and even AI.</p><h3>1. What an aggregate query is</h3><p>An ordinary SOQL query returns records. An aggregate query returns <em>summaries</em> of records. You can use an aggregate function with no GROUP BY at all, for example the average Amount across every opportunity:</p><pre>SELECT AVG(Amount) FROM Opportunity</pre><p>But the real power appears when you combine aggregate functions with GROUP BY, which summarizes per category:</p><pre>SELECT CampaignId, AVG(Amount)<br>FROM Opportunity<br>GROUP BY CampaignId</pre><p>This returns one row per campaign, each with its average amount. Think of it as a report built directly in code.</p><h3>2. The six aggregate functions</h3><p>Function</p><p>What it returns</p><p>AVG()</p><p>Average of a numeric field</p><p>COUNT() / COUNT(fieldName)</p><p>Number of rows matching the query</p><p>COUNT_DISTINCT()</p><p>Number of distinct non-null values</p><p>MIN()</p><p>Smallest value of a field</p><p>MAX()</p><p>Largest value of a field</p><p>SUM()</p><p>Total of a numeric field</p><p>Two details from the official reference are worth memorizing:</p><ul><li><strong>Nulls:</strong> all aggregate functions ignore null values, except COUNT() and COUNT(Id). COUNT(fieldName) for other fields does ignore nulls.</li><li><strong>Picklists:</strong> MIN() and MAX() on a picklist field use the picklist&#39;s defined sort order, not alphabetical order.</li></ul><p>COUNT() and COUNT(Id) behave like COUNT(*) in SQL, and COUNT_DISTINCT(field) is the equivalent of COUNT(DISTINCT field).</p><h3>Examples to try</h3><pre>-- how many accounts start with &#39;a&#39;?<br>SELECT COUNT() FROM Account WHERE Name LIKE &#39;a%&#39;</pre><pre>-- how many different companies do my leads come from?<br>SELECT COUNT_DISTINCT(Company) FROM Lead</pre><pre>-- total value of open, likely deals<br>SELECT SUM(Amount) FROM Opportunity<br>WHERE IsClosed = false AND Probability &gt; 60</pre><pre>-- earliest created contact per name<br>SELECT MIN(CreatedDate), FirstName, LastName<br>FROM Contact<br>GROUP BY FirstName, LastName</pre><h3>3. Using aggregates in Apex</h3><p>In Apex, any query containing an aggregate function returns an array of AggregateResult objects. AggregateResult is a read-only sObject used only for query results. You read values with get(), which returns a generic Object, so you cast it:</p><pre>AggregateResult[] results = [<br>    SELECT AVG(Amount) aver<br>    FROM Opportunity<br>    WITH USER_MODE<br>];<br>Decimal avgAmount = (Decimal) results[0].get(&#39;aver&#39;);</pre><p>Notice three things:</p><ol><li><strong>Alias.</strong> The word aver after the function names the result column so you can fetch it by name.</li><li><strong>No alias means </strong><strong>exprN.</strong> If you leave the alias off, Salesforce gives it an implied name in the form expr0, expr1, and so on, counting up in order for each unaliased aggregated field. That works but is fragile. If you reorder the query, your get(&#39;expr0&#39;) silently points to a different value. Always use aliases.</li><li><strong>WITH USER_MODE.</strong> The official Apex examples include it. It runs the query with the current user&#39;s permissions, which matters when your summary could expose data the user should not see.</li></ol><p>A grouped query with a loop looks like this:</p><pre>AggregateResult[] results = [<br>    SELECT StageName stage, COUNT(Id) deals, SUM(Amount) total<br>    FROM Opportunity<br>    WHERE IsClosed = false<br>    WITH USER_MODE<br>    GROUP BY StageName<br>];<br>for (AggregateResult ar : results) {<br>    String stage = (String) ar.get(&#39;stage&#39;);<br>    Integer deals = (Integer) ar.get(&#39;deals&#39;);<br>    Decimal total = (Decimal) ar.get(&#39;total&#39;);<br>    System.debug(stage + &#39;: &#39; + deals + &#39; deals, &#39; + total);<br>}</pre><p>This single query produces a pipeline summary by stage, which you would otherwise assemble with a loop and a map.</p><h3>4. COUNT(), COUNT(Id) and COUNT(field): not the same</h3><p>This trips up many beginners. COUNT() and COUNT(Id) count rows. COUNT(Phone) counts only rows where Phone is not null. If 1,000 contacts exist and 700 have a phone number, the two give different answers, and each is correct for its own question.</p><h3>5. Which field types work</h3><p>Not every field can be aggregated. Salesforce documents a support matrix. The practical summary:</p><ul><li><strong>Numeric types</strong> (int, double, currency, percent) support all six functions, including SUM() and AVG().</li><li><strong>Date, dateTime and string-like types</strong> (picklist, email, phone, URL, reference/lookup, ID, text area) support COUNT(), COUNT_DISTINCT(), MIN() and MAX(), but not SUM() or AVG().</li><li><strong>Unsupported entirely:</strong> base64, boolean, byte, time, address, anyType, encrypted string, location, multipicklist, and array types.</li><li><strong>Long text:</strong> Text Area (Long) and Text Area (Rich) do not support aggregates.</li><li><strong>Calculated (formula) fields:</strong> support depends on the formula’s return type.</li><li><strong>Currency:</strong> aggregate results on currency fields default to the system currency, which matters in multi-currency orgs.</li></ul><p>Some field types also cannot appear in a GROUP BY clause, so if grouping fails on a field, check its type first.</p><h3>6. Rules and limits you must know</h3><p><strong>No </strong><strong>LIMIT without </strong><strong>GROUP BY.</strong> A query like SELECT MAX(CreatedDate) FROM Account LIMIT 1 is invalid when it uses an aggregate function without GROUP BY. It is also unnecessary, since it returns one row anyway.</p><p><strong>Query-row limits still apply, and this is the subtle part.</strong> Aggregate queries count toward the total query-row limit, but the accounting differs by function:</p><ul><li>For COUNT() or COUNT(fieldname) without grouping, the whole query counts as <strong>one</strong> row, no matter how many records were counted.</li><li>With GROUP BY, COUNT consumes <strong>one row per group</strong>.</li><li>Every <em>other</em> aggregate function (SUM, AVG, MIN, MAX, COUNT_DISTINCT) counts each row used in the aggregation as a query row.</li></ul><p>So COUNT() is dramatically cheap against governor limits, while SUM() over a huge table can still consume a lot of your row budget even though only one result row comes back. For very large data volumes, check the current governor-limit numbers in the Apex documentation and consider the guidance on very large queries and SOQL for loops.</p><p><strong>Mixing columns.</strong> In grouped queries, every non-aggregated field in SELECT must appear in GROUP BY, as in the MIN(CreatedDate), FirstName, LastName example above.</p><p>The SOQL reference also covers GROUP BY ROLLUP, GROUP BY CUBE, the GROUPING() function (for telling subtotal rows from detail rows) and HAVING (for filtering groups after aggregation). Those extend the same idea and are worth learning once the basics feel natural. This article does not go into them in detail.</p><h3>7. A learning path: five exercises</h3><p>Run these in the Developer Console Query Editor or Workbench on a sandbox or developer org.</p><ol><li><strong>Total.</strong> SELECT SUM(Amount) FROM Opportunity WHERE IsWon = true</li><li><strong>Count by status.</strong> SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName</li><li><strong>Average by owner.</strong> SELECT OwnerId, AVG(Amount) FROM Opportunity GROUP BY OwnerId</li><li><strong>Distinct values.</strong> SELECT COUNT_DISTINCT(Industry) FROM Account</li><li><strong>Apex version.</strong> Re-do exercise 2 in Apex, with aliases, casting and a debug loop.</li></ol><p>For each, ask yourself: what would the loop-based version cost me?</p><h3>8. The impact</h3><h3>Performance and platform limits</h3><p>Aggregation happens inside the database, so you avoid pulling thousands of records into Apex memory just to add them up. You write less code, use less heap and CPU, and return fewer bytes. The nuance above applies: non-COUNT aggregates still consume query rows, so aggregates reduce heap and code complexity more than they reduce row-limit usage, while COUNT() reduces both.</p><h3>Reporting without a report</h3><p>Aggregate queries power custom dashboards, Lightning components, scheduled summaries, API integrations and validation logic. They fill the gap when standard reports are not flexible enough or when the numbers must feed another process, such as roll-ups across lookup relationships.</p><h3>Data quality</h3><p>A grouped count is the quickest way to spot problems: records grouped by a field where the count is greater than one often reveal duplicates, and counting nulls versus non-nulls shows how complete a field really is.</p><h3>Correctness and trust in the AI era</h3><p>This connects to the theme of earlier articles about trusting AI. A language model asked to add up a long list of numbers is guessing token by token and can be wrong while sounding confident. A SOQL aggregate returns the exact answer, computed deterministically by the database, under the user’s permissions. That is why agent platforms are built so that models <em>call tools and queries</em> to get figures rather than invent them. If you build Agentforce actions or any AI feature on Salesforce data, an aggregate query is often the correct tool for the numbers, and the model’s job is to explain them, not to calculate them. (This is my analysis of good design practice, not a claim from the Salesforce documentation.)</p><h3>9. Quick checklist</h3><ul><li>Use an aggregate function instead of a loop whenever you only need a summary.</li><li>Always alias aggregate results; do not rely on expr0.</li><li>Cast AggregateResult.get() values to the right type.</li><li>Use COUNT() when you want rows, COUNT(field) when you want non-null values.</li><li>Check field-type support before aggregating or grouping.</li><li>Remember: no LIMIT on ungrouped aggregates, and non-COUNT aggregates consume query rows.</li><li>Use WITH USER_MODE in Apex so users only see what they are allowed to see.</li><li>Test with realistic data volumes, not 200 sandbox records.</li></ul><h3>Bottom line</h3><p>SOQL aggregate queries are a small feature with a large effect. They move summarizing work to where the data lives, make your code shorter and safer, and give you exact numbers you can trust. Learn the six functions, always use GROUP BY and aliases deliberately, and respect the limit rules, and you will write faster, cleaner Salesforce code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82dd650f8099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Company That Sold the AI Revolution Became Its First Test Subject]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/the-company-that-sold-the-ai-revolution-became-its-first-test-subject-a842f2db2198?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a842f2db2198</guid>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 05:16:21 GMT</pubDate>
            <atom:updated>2026-11-29T05:16:21.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Gf_nQ6d1JL5dUw0LX9Bi9g.jpeg" /></figure><p><em>Inside Salesforce’s Agentforce bet: what changed, what the numbers really say, and where the technology still needs a human.</em></p><h3>The podcast moment</h3><p>In the summer of 2025, Marc Benioff kept telling the public the same comforting thing: AI would augment workers, not replace them. As late as the day before a certain podcast went live, he reinforced that message on X.</p><p>Then, in an interview on The Logan Bartlett Show, he dropped a different fact. Salesforce’s customer support organization had gone from about 9,000 people to about 5,000. His explanation was short and blunt: he needed fewer heads.</p><p>That sentence turned Salesforce from a company that <em>sells</em> AI agents into the most-watched case study of what happens when a large enterprise actually <em>uses</em> them. A year later, we have enough data to look past the headline. This article walks through what Salesforce did, how the technology works, what the numbers do and do not prove, and what the case teaches about the limits of trusting AI.</p><p>One caution before we start: almost all performance figures below come from Salesforce itself, in earnings releases, its own research reports and executive commentary. That is not a reason to dismiss them, but it is a reason to read them like a careful engineer, asking how each metric is defined.</p><h3>Part 1: What actually happened inside Salesforce</h3><p>The facts reported at the time:</p><ul><li>Support headcount fell from roughly 9,000 to roughly 5,000, a cut of about 4,000 roles.</li><li>Benioff said support costs dropped about 17% since the start of 2025.</li><li>He described AI agents as having handled over a million customer conversations, with customer satisfaction scores roughly unchanged. This is his claim, not an independent audit.</li><li>Earlier in 2025 he had said AI was doing 30% to 50% of the work at Salesforce. The company employed around 76,000 people at the time.</li><li>Salesforce said that fewer support cases were arriving and that it was no longer actively backfilling support engineer roles.</li><li>Benioff said half of support conversations were now with agents and half with humans, and he expected that split to spread into sales and marketing.</li></ul><p>The reaction split into two camps. Supporters saw proof that agentic AI delivers real labor savings. Critics, including the analyst Ed Zitron, argued that AI was partly a convenient explanation for cuts driven by pandemic-era overhiring. An Oxford researcher raised a longer-term concern: cutting junior roles too deeply can damage the talent pipeline that produces your future senior people.</p><p>Both readings can be partly true. What matters for our purposes is that Salesforce’s support organization became a live production test of AI agents handling customer-facing work at scale.</p><h3>Part 2: How Agentforce works, technically</h3><p>Agentforce is Salesforce’s platform for building and running AI agents inside its CRM ecosystem. From the public material, a few architectural pieces stand out.</p><p><strong>1. An LLM gateway.</strong> Salesforce reported that Agentforce had processed more than 3.2 trillion tokens through its LLM gateway by late 2025. A gateway is a control layer between applications and the underlying language models. It is where routing, logging, access control and safety filtering can live. Putting this layer in the middle is how an enterprise avoids wiring raw model calls straight into business processes.</p><p><strong>2. Grounding in company data.</strong> A language model on its own only knows its training data. To answer questions about a specific customer’s order, the agent needs that customer’s records. Salesforce’s answer is Data 360 plus the Informatica acquisition, which gives it a way to unify and govern enterprise data. In Q2 of fiscal 2027, Salesforce said Data 360 ingested 104 trillion records, 82 trillion of them via Zero Copy, meaning access to data where it already lives instead of duplicating it. In engineering terms this is retrieval-grounded generation at enterprise scale: the model is not trusted to remember facts, it is handed them at query time.</p><p><strong>3. Skills and actions.</strong> Salesforce’s own index report says the average agent could act on six distinct skills by the end of 2025, up from two at the start of the year, and that retail agents reached nine skills during peak holiday demand. A skill here is a bounded action: look up a record, answer a question, update a field, route a lead.</p><p><strong>4. A headless architecture.</strong> The same report describes decoupling the agent’s logic from traditional user interfaces, so agents can run tasks and trigger workflows from anywhere. This is why Salesforce talks about opening its platform to any model, agent or interface, including a partnership with Anthropic called Claudeforce, launched with a plugin of 37 pre-built sales skills.</p><p><strong>5. Multi-agent orchestration.</strong> Siemens, per Salesforce, used a coordinated workflow in which one agent engages and nurtures an inbound lead, and a second gathers missing data, applies qualification rules and routes the lead with context. This pattern, splitting a job into specialist agents with a rules layer, is common because a single general prompt is harder to test and constrain.</p><h3>Part 3: The numbers, and what each one really measures</h3><p><strong>Agentforce ARR.</strong> Annual recurring revenue for Agentforce rose from about $800 million (quarter ending January 2026, up 169% year over year) to $1.2 billion in the next quarter (up 205%), then above $1.5 billion in the quarter ended July 2026 (up over 240%). Growth is fast. Two cautions apply:</p><ul><li>Scale: at the $1.2 billion mark, Agentforce was under 3% of Salesforce’s roughly $46 billion revenue guidance.</li><li>Definition: Salesforce stated that, starting in Q2 FY27, Agentforce ARR includes its AI offerings, Slackbot and Headless 360. A broader definition makes the latest quarter-over-quarter comparison less clean.</li></ul><p><strong>Agentic Work Units (AWUs).</strong> Salesforce defines an AWU as one discrete task completed by an AI agent. It reported 7.0 billion delivered to date, with 3.2 billion in Q2 alone, up 97% from the prior quarter. This is an <em>activity</em> metric. It counts tasks done, not whether each task was done correctly or whether it created business value. A looked-up record and a corrected billing dispute both count as work, but they are not equal in risk or value.</p><p><strong>Overall growth.</strong> Total revenue in Q2 FY27 was $11.3 billion, up 11% year over year. That figure includes about $456 million from the Informatica acquisition. Salesforce’s own full-year guidance says growth of 11% to 12% includes slightly above 3 points from Informatica, which by simple arithmetic puts organic growth somewhere around 8% to 9%. (That arithmetic is mine, not Salesforce’s.) So AI is growing fast inside a business that is growing modestly overall.</p><h3>Part 4: Where autonomy works and where it stops</h3><p>The most revealing data point for anyone thinking about AI reliability is Salesforce’s own help agent. The company reported more than 5 million customer conversations with 64% resolved autonomously. That is a strong result for a language-model system. It also means roughly 36% still went to a human, or at least were not resolved by the agent alone.</p><p>Salesforce’s Sophistication Index points to the same boundary. It sorts agent actions into five tiers: basic read and retrieval, standard messaging and coordination, text synthesis, transactional database modifications (writes), and advanced analytics and parsing. The first three are described as lower-risk capabilities, such as looking up records, drafting emails and summarizing documents. The top two are higher-complexity actions like updating database fields.</p><p>This maps neatly onto how language models fail:</p><ul><li><strong>Reading and summarizing</strong> errors are usually visible and recoverable. A human can check a draft before it goes out.</li><li><strong>Writing to systems of record</strong> is different. A wrong value in a financial or patient record is quietly propagated, can trigger downstream actions, and may be discovered late.</li></ul><p>The regulated-industry examples reflect this. Salesforce’s report notes that PenFed, a federally chartered credit union, needed robust risk controls and cross-functional legal and compliance oversight to move beyond traditional rule-based chatbots. That is the pattern: the more regulated the setting, the more the agent is wrapped in governance.</p><p>Even Benioff has voiced the underlying limit. In the same period he said AI augments people but may not necessarily replace them, because current systems are still built on language models, and a future, more accurate model may change that. Notice what he is describing: the probabilistic nature of next-token prediction, which no amount of product packaging fully removes.</p><h3>Part 5: The business-model shock</h3><p>Here the AI story turns on Salesforce itself.</p><p>Traditional SaaS, Salesforce’s classic model, sells per-seat licenses. If AI lets a customer do the same work with fewer humans, fewer seats are needed. Salesforce experienced this from both sides: it cut support staff internally, and it asked investors to believe that customers adopting agents would spend more on the platform rather than less.</p><p>Investors were not convinced at first. In early 2026, a broad software sell-off, nicknamed the SaaSpocalypse, hit the sector on fears that AI agents and AI coding tools would let enterprises replace or bypass packaged software. By late February the stock was down about 27.6% year to date even after an earnings beat, and by June it was down about 37% for the year, near a 52-week low, trading around 19 times earnings. After the Q1 report, a Barclays analyst wrote that the results might not be enough to drive a meaningful reaction.</p><p>Salesforce’s response has been to shift how it charges. Metrics like AWUs, usage credits and premium bundles show a move toward consumption and outcome-linked pricing. In Q2, the company said about half of Agentforce bookings came from customers replenishing usage credits, and that bookings of its premium Agentforce One Edition and Agentforce for Apps more than doubled quarter over quarter. This is a structural bet: charge for work done by agents, not for human seats.</p><h3>Part 6: What the case teaches</h3><ol><li><strong>AI can deliver real labor savings in narrow, high-volume workflows.</strong> Support is the textbook example: repetitive, text-based, with abundant historical data and clear resolution definitions.</li><li><strong>Vendor metrics measure activity more than correctness.</strong> Ask how AWUs, ARR and resolution rates are defined before drawing conclusions, and look for independent measurement of error rates, escalations and customer harm.</li><li><strong>Autonomy is a dial, not a switch.</strong> A 64% autonomous resolution rate is impressive and still leaves a large human-handled remainder. The risk rises where agents write to records or make decisions with legal and financial consequences.</li><li><strong>Grounding and governance are what make agents usable.</strong> Gateways, data layers, skill boundaries and compliance review exist because the base model is probabilistic and can be confidently wrong.</li><li><strong>Second-order effects matter.</strong> Cutting junior support roles may save money now and weaken talent development later. Replacing seats with agents changes a software company’s own revenue model.</li></ol><h3>Bottom line</h3><p>Salesforce shows both sides of the AI story at once. It is evidence that agentic systems can take over a meaningful share of routine work at scale, and it is evidence that even the vendor with every incentive to push automation still keeps humans in the loop, wraps agents in governance, and measures progress with carefully defined metrics.</p><p>The lesson for anyone deploying AI is not to copy the headline of 4,000 fewer heads. It is to copy the architecture: ground the model in real data, limit what it can write, measure what it actually gets right, and keep an accountable human where the cost of a wrong answer is high.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a842f2db2198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Cannot Blindly Trust AI]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/why-you-cannot-blindly-trust-ai-a15bca2b4b92?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15bca2b4b92</guid>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artifical-intellegence]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 05:02:43 GMT</pubDate>
            <atom:updated>2026-11-29T05:02:43.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*cz_N2A264cC7PNvS_WGj6g.jpeg" /></figure><p><em>A technical look at how modern AI works, where it breaks, and why it should not make high-impact decisions alone.</em></p><h3>1. What an AI language model actually is</h3><p>Most AI assistants today are large language models (LLMs) built on the transformer architecture. Strip away the marketing and the core is simple:</p><ol><li>Text is split into <strong>tokens</strong> (word pieces).</li><li>Each token becomes a vector of numbers (an embedding).</li><li>Stacked layers of <strong>self-attention</strong> and feed-forward networks mix information between tokens.</li><li>The final layer outputs a <strong>probability distribution over the next token</strong>.</li><li>One token is sampled, appended to the input, and the loop repeats.</li></ol><p>That is the whole generation process. The model is trained to answer one question: <em>given this text so far, what token is most likely to come next?</em></p><p>Training happens in stages:</p><ul><li><strong>Pretraining:</strong> the model learns next-token prediction over a massive text corpus. This is where it picks up grammar, facts, code patterns and reasoning-like behavior.</li><li><strong>Fine-tuning and RLHF-style tuning:</strong> the model is further trained on curated examples and on human (or AI) preference ratings so its answers become helpful, polite and safe-looking.</li></ul><p>The key point: the training objective is <strong>plausibility, not truth</strong>. The model is optimized to produce text that looks like a good answer. Truth correlates with plausibility often, but not always, and the model has no internal mechanism that separates the two.</p><h3>2. Why that design leads to failure</h3><h3>Hallucination is a built-in behavior, not a rare bug</h3><p>When the model lacks knowledge, it does not return an error. It still has to output a next token, and the most plausible-looking continuation is often a confident, fluent, wrong answer. This is how models invent citations, API functions that do not exist, legal cases, statistics and quotes. The fabricated output is statistically shaped like real output, which makes it hard to spot.</p><p>Hallucination rates have dropped with better training, retrieval and tool use, but they have not reached zero, and no current architecture guarantees they will.</p><h3>Confidence is not calibrated</h3><p>The fluency of an answer says almost nothing about its correctness. A wrong answer and a right answer are often written in the same confident tone. Token probabilities exist internally, but they do not map cleanly to “how likely is this claim to be true,” and models are often poor at reporting their own uncertainty.</p><h3>The knowledge is frozen and incomplete</h3><p>The model’s knowledge comes from training data with a cutoff date. Anything after that is unknown unless the system adds search or retrieval. Even before the cutoff, coverage is uneven: popular topics are well represented, niche, local or recent topics are thin, and thin coverage is where errors cluster.</p><h3>Training data carries bias and errors</h3><p>The model learns from human-written text, including mistakes, outdated claims, stereotypes and propaganda. Averaging over a huge corpus does not remove these. It can bake them in as “the likely answer.”</p><h3>Preference tuning introduces sycophancy</h3><p>If human raters prefer answers that agree with them or sound helpful, the tuned model learns to do that. The result: models can echo the user’s wrong assumption, soften correct criticism, or change a right answer after pushback. A system that tends to agree with you is a bad judge of your decision.</p><h3>Reasoning is brittle</h3><p>Models can solve hard problems and then fail an easy variation. Performance can shift with rewording, ordering of options, irrelevant details or small changes in numbers. Long multi-step reasoning accumulates error: if each step is 95% reliable, a 20-step chain is correct only about 36% of the time. “Chain-of-thought” text also does not always reflect the actual computation that produced the answer, so a neat explanation is not proof the explanation is real.</p><h3>Output is probabilistic</h3><p>Because tokens are sampled, the same prompt can produce different answers on different runs. Even at low temperature, small changes in wording, context or model version can change outputs. A decision process that cannot be reproduced is hard to audit.</p><h3>Limited and lossy context</h3><p>The model only sees what is in its context window. It can miss or misweigh details in long documents, especially in the middle. It does not know facts about your situation that you did not tell it, and it will usually not tell you what it is missing.</p><h3>Security: prompt injection</h3><p>When an AI reads emails, web pages or documents, text inside them can contain instructions that the model may follow. LLMs do not have a strict separation between “instructions” and “data.” For AI agents with access to tools, money, files or accounts, this is a real attack surface.</p><h3>Opacity</h3><p>Billions of parameters means no one can point to a specific line and say why the model gave an answer. Interpretability research is progressing, but you cannot currently inspect a model and certify it is correct for your case.</p><h3>3. The human factor: automation bias</h3><p>The technical limits are made worse by how people behave. When a system is fluent, fast and usually right, people stop checking it. This is automation bias, and it is well documented in aviation, medicine and other fields. An AI that is right 95% of the time can be more dangerous than one right 60% of the time, because the 95% one trains you to stop verifying.</p><h3>4. Why high-impact decisions are different</h3><p>A wrong movie recommendation costs nothing. These do not:</p><ul><li><strong>Medical:</strong> diagnosis, drug dosage, treatment choice.</li><li><strong>Legal:</strong> contracts, filings, compliance. There are real court cases where lawyers were sanctioned for submitting AI-invented citations.</li><li><strong>Financial:</strong> investments, loans, tax positions, trades.</li><li><strong>Safety-critical engineering:</strong> structural, electrical, aviation, industrial control.</li><li><strong>Hiring, credit, policing, benefits:</strong> decisions about people, where hidden bias causes real harm and discrimination.</li><li><strong>Security and infrastructure:</strong> access control, production deployments, deleting data.</li></ul><p>Three properties make these cases unsuitable for blind AI trust:</p><ol><li><strong>The cost of errors is asymmetric.</strong> One rare bad answer can outweigh thousands of good ones.</li><li><strong>Errors are hard to detect.</strong> Hallucinations look like correct answers, and you often cannot tell without already knowing the answer.</li><li><strong>There is no accountability.</strong> A model cannot be held responsible, lose a license or testify. A human or organization stays accountable, so a human must stay in control.</li></ol><h3>5. How to use AI responsibly</h3><p>This is not an argument to avoid AI. It is an argument to treat it as a powerful but unreliable component.</p><ul><li><strong>Keep a qualified human in the loop.</strong> The AI drafts, summarizes, suggests and explores. A person with expertise decides.</li><li><strong>Verify against primary sources.</strong> Check citations, numbers, code and legal or medical claims independently. If the AI cites something, open it.</li><li><strong>Ground the model.</strong> Retrieval from trusted documents and tool use (calculators, databases, code execution) reduce errors, though they do not eliminate them.</li><li><strong>Test it on your own task.</strong> Build an evaluation set from real cases with known answers and measure error rates before deploying. Re-test when the model changes.</li><li><strong>Prefer reversible decisions.</strong> Let AI act freely where mistakes are cheap to undo, and add approval gates where they are not.</li><li><strong>Limit permissions.</strong> Give AI agents least-privilege access, and never let them take irreversible actions (payments, deletions, production changes) without confirmation.</li><li><strong>Ask for uncertainty and counterarguments.</strong> Ask what could be wrong, what it does not know, and to argue the opposite. Do not lead with your preferred answer.</li><li><strong>Log and audit.</strong> For serious uses, keep records of inputs, outputs, model version and who approved the result.</li><li><strong>Get a real professional.</strong> For health, law, finances and safety, use AI to prepare better questions, not to replace the expert.</li></ul><h3>6. Bottom line</h3><p>An LLM is a statistical text generator trained to produce plausible continuations, then tuned to be helpful and pleasant. That makes it remarkably useful and unavoidably fallible. It can be wrong while sounding certain, it cannot reliably tell you when, and it carries no responsibility for the consequences.</p><p>Use AI to think faster. Do not use it to stop thinking. For decisions that can seriously affect health, money, freedom, safety or other people’s lives, the final judgment, and the verification behind it, must belong to an accountable human.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15bca2b4b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentforce & Agentic Workflows: The Next Evolution of Salesforce Automation]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/agentforce-agentic-workflows-the-next-evolution-of-salesforce-automation-01e7d5fd6baa?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/01e7d5fd6baa</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[salesforce-automation]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 04:46:25 GMT</pubDate>
            <atom:updated>2026-11-29T04:46:25.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*-kv8FNxj__G1HzpbjgV_WA.jpeg" /></figure><p>Salesforce automation is evolving beyond traditional rule-based processes. For years, organizations have relied on Workflow Rules, Process Builder, Salesforce Flow, Apex Triggers, and integrations to automate business operations.</p><p>These technologies remain important, but they generally depend on predefined conditions and execution paths. They work exceptionally well when the business process is predictable. However, real-world business scenarios are not always predictable.</p><p>Consider a customer contacting a company with a complicated issue. The system might need to understand the customer’s intent, retrieve information from multiple records, identify the correct solution, execute several actions, and escalate the issue when necessary.</p><p>This is where <strong>Agentforce and Agentic Workflows</strong> become important.</p><p>Agentforce brings AI-powered agents into the Salesforce ecosystem, allowing businesses to move from simply automating predefined tasks to building intelligent systems that can understand context, reason about possible actions, and execute business processes within defined boundaries.</p><h3>1. What Is Agentforce?</h3><p>Agentforce is Salesforce’s platform for building and deploying AI agents that can interact with users, access business data, and perform tasks using configured actions.</p><p>Unlike a traditional chatbot that primarily answers questions, an Agentforce agent can take action.</p><p>For example, a customer might ask:</p><p>“I haven’t received my order. Can you check its status and help me resolve the issue?”</p><p>An Agentforce agent can:</p><ol><li>Understand the customer’s request.</li><li>Identify the relevant customer and order information.</li><li>Retrieve the latest order details.</li><li>Determine the appropriate next step.</li><li>Execute an available action, such as creating a case.</li><li>Provide the customer with an appropriate response.</li><li>Escalate the issue to a human representative when necessary.</li></ol><p>The key difference is that the agent is not limited to generating text. It can interact with Salesforce functionality through actions and integrations.</p><h3>2. Core Components of Agentforce</h3><p>To understand how Agentforce works, developers should understand its major building blocks.</p><p><strong>Agent</strong></p><p>An agent is an AI-powered system designed to achieve a specific business objective. It receives requests or triggers, understands the context, and determines which available capabilities can help complete the task.</p><p><strong>Subagents</strong></p><p>Subagents are specialized areas of responsibility within an agent. Each subagent handles a particular category of work and has its own instructions, available actions, and purpose.</p><p>For example, a customer service agent could have specialized subagents for order management, billing inquiries, and technical support.</p><p><strong>Actions</strong></p><p>Actions allow an agent to interact with Salesforce and external systems.</p><p>An action can invoke:</p><ul><li>Salesforce Flow</li><li>Apex methods</li><li>Prompt Templates</li><li>APIs and integrations</li><li>Other supported Salesforce capabilities</li></ul><p>For developers, custom Apex actions are particularly useful when a requirement involves complex business logic that cannot be handled efficiently through standard configuration.</p><p><strong>Atlas Reasoning Engine</strong></p><p>The Atlas Reasoning Engine is responsible for processing requests and coordinating agent behavior. It helps determine the relevant subagent, apply instructions and rules, select actions, and produce grounded responses.</p><p><strong>Agentforce Script</strong></p><p>Agentforce Script provides structured control over agent behavior. It combines natural-language instructions with deterministic logic, helping developers define predictable execution paths rather than relying entirely on free-form AI responses.</p><p><strong>Data and Grounding</strong></p><p>An agent needs accurate business information to make useful decisions. Salesforce CRM records, knowledge articles, and connected enterprise data can provide this context.</p><p>Data 360 can support data unification, retrieval, and grounding, including retrieval-augmented generation (RAG).</p><h3>3. What Are Agentic Workflows?</h3><p>An agentic workflow is a business process in which an AI agent can understand a goal, evaluate the available context, choose suitable actions, and coordinate multiple steps to achieve an outcome.</p><p>Traditional automation follows a predefined path.</p><p>An agentic workflow introduces a decision-making layer that can adapt its choice of actions according to the situation.</p><p>Consider a traditional lead management process:</p><ul><li>A lead is created.</li><li>A Flow checks mandatory fields.</li><li>A scoring rule assigns a lead score.</li><li>A task is created for a sales representative.</li></ul><p>This is effective when the rules are known in advance.</p><p>Now consider an agentic lead management workflow.</p><p>A new lead is received, and the agent is asked to qualify it. The agent can retrieve relevant CRM information, assess the available lead details, identify missing information, invoke duplicate-checking logic, and recommend the next action.</p><p>It can then use Salesforce Flow or Apex to execute the approved business operations.</p><p>The important point is that AI handles flexible interpretation and decision support, while deterministic automation handles critical business rules and transactions.</p><h3>4. Agentforce vs Traditional Salesforce Automation</h3><p>CapabilityTraditional automationAgentforceExecutionPredefined rulesContext-based reasoning and configured logicInputStructured events and conditionsNatural language, events, and other supported triggersDecision-makingExplicitly configured conditionsAI reasoning combined with business rulesActionsFlow, Apex, integrationsFlow, Apex, integrations, and other agent actionsAdaptabilityLimited to defined pathsCan handle variations within configured boundariesHuman involvementApprovals and manual tasksCan collaborate with humans and escalate decisions</p><p>Neither approach makes the other obsolete.</p><p>The strongest Salesforce architecture combines traditional automation with agentic capabilities.</p><h3>5. How Agentforce and Agentic Workflows Work Together</h3><p>A typical architecture can look like this:</p><p><strong>Step 1: Trigger</strong></p><p>An agent receives a customer message, an employee request, or a supported event-based trigger.</p><p><strong>Step 2: Understand the Context</strong></p><p>The agent interprets the request and retrieves the relevant Salesforce records or connected data.</p><p><strong>Step 3: Select the Appropriate Subagent</strong></p><p>The reasoning engine identifies the relevant area of responsibility based on the request and the agent’s configuration.</p><p><strong>Step 4: Determine the Required Actions</strong></p><p>The agent identifies which actions are necessary to achieve the requested outcome.</p><p><strong>Step 5: Execute Business Logic</strong></p><p>The agent invokes Salesforce Flow, Apex, or an external API through configured actions.</p><p><strong>Step 6: Validate the Result</strong></p><p>The system checks the action result and applies the relevant business rules and controls.</p><p><strong>Step 7: Respond or Escalate</strong></p><p>The agent communicates the outcome or transfers the process to a human when the situation requires human judgment.</p><p>This architecture makes it possible to combine AI-driven decisions with predictable execution.</p><h3>6. Real-World Salesforce Use Cases</h3><h3>A. Intelligent Lead Qualification</h3><p>Sales teams receive leads from websites, campaigns, referrals, and other sources.</p><p>An Agentforce agent could:</p><ul><li>Review lead information.</li><li>Retrieve relevant Account and Contact records.</li><li>Identify incomplete or inconsistent information.</li><li>Invoke Apex-based duplicate checking.</li><li>Recommend qualification or further investigation.</li><li>Create follow-up tasks through Flow.</li><li>Route the lead to the appropriate sales representative.</li></ul><p>The advantage is that sales representatives spend less time collecting and organizing information.</p><h3>B. Customer Service Automation</h3><p>A customer contacts the company about a failed product or service.</p><p>An Agentforce agent could retrieve the customer’s Case history, identify relevant Knowledge articles, check the associated Account information, and invoke actions to create or update a Case.</p><p>When the issue requires an exception or specialist intervention, it can escalate the request to a human service representative.</p><h3>C. Opportunity Management</h3><p>An agent can assist sales representatives by reviewing Opportunity information, identifying missing fields, summarizing recent customer interactions, and recommending next steps.</p><p>For example, before an Opportunity moves to the Negotiation stage, the agent could check whether the required information is present.</p><p>A Flow or Apex action can enforce mandatory conditions, while the agent helps the sales representative understand what needs attention.</p><h3>D. Intelligent Case Resolution</h3><p>An agent can analyze a customer’s description, retrieve previous cases, search relevant Knowledge articles, and recommend a resolution.</p><p>For straightforward cases, it may execute configured actions. More complicated cases can be routed to a human representative with a summary of the investigation already completed.</p><h3>7. Role of Salesforce Developers: Flow, Apex, and LWC</h3><p>Agentforce does not eliminate the need for Salesforce developers. Instead, it creates new opportunities to use existing Salesforce development skills.</p><p><strong>Salesforce Flow</strong></p><p>Flow is useful for implementing declarative business operations, record updates, validations, task creation, and approval-related processes.</p><p>For example, an agent can invoke a Flow to create a follow-up task after qualifying a lead.</p><p><strong>Apex</strong></p><p>Apex is useful when a process requires complex logic, advanced validations, custom integrations, or operations that are difficult to implement using Flow alone.</p><p>Developers can expose supported Apex methods as Agentforce actions using @InvocableMethod.</p><p>For example, an Apex class could perform duplicate detection, validate GST information, or integrate with an external verification service.</p><p><strong>Lightning Web Components</strong></p><p>LWC can provide custom interfaces for Salesforce users who need to review agent-generated information, inspect recommendations, or interact with structured action results.</p><p>Custom Lightning Types can also improve the presentation of complex action inputs and outputs where supported.</p><p><strong>SOQL</strong></p><p>SOQL remains essential for retrieving CRM information. Developers can implement the required data retrieval logic in Apex or use supported Named Query actions.</p><p>The objective is not to move every business operation into AI. It is to give the agent access to reliable Salesforce capabilities.</p><h3>8. Security and Governance</h3><p>Security is one of the most important considerations when implementing autonomous agents.</p><p>An agent should never receive unrestricted access simply because it is designed to automate work.</p><p>A production-ready implementation should consider:</p><ol><li><strong>Data Access:</strong> Configure appropriate object permissions, field-level security, record access, and execution context.</li><li><strong>Least Privilege:</strong> Give the agent only the access required for its specific responsibilities.</li><li><strong>Guardrails:</strong> Define what the agent can and cannot do, including restrictions on sensitive operations.</li><li><strong>Human Approval:</strong> Require human review for high-impact or sensitive business decisions.</li><li><strong>Data Grounding:</strong> Use trusted and relevant information rather than allowing unsupported responses.</li><li><strong>Testing and Monitoring:</strong> Test different scenarios, monitor action outcomes, and continuously improve the agent.</li></ol><p>Salesforce’s Einstein Trust Layer provides security and privacy controls for generative AI interactions. However, it does not remove the need for sound Salesforce permission design and application-level controls.</p><h3>9. Best Practices for Implementing Agentic Workflows</h3><p>A successful implementation starts with the business problem, not the AI technology.</p><p><strong>Start with a clearly defined use case.</strong> Identify a repetitive or time-consuming process where an intelligent agent can deliver measurable value.</p><p><strong>Keep deterministic logic outside free-form AI reasoning.</strong> Mandatory validations, financial calculations, permissions, and transaction rules should be enforced using Flow, Apex, or other appropriate controls.</p><p><strong>Design focused subagents and actions.</strong> Give each component a clear responsibility. Avoid creating one oversized agent that handles unrelated business processes.</p><p><strong>Provide relevant context.</strong> An agent is only as useful as the information available to it. Ensure CRM data, Knowledge content, and connected information are accurate and relevant.</p><p><strong>Test before deployment.</strong> Test successful scenarios, missing data, duplicate records, unexpected user requests, authorization failures, and escalation conditions.</p><p><strong>Measure actual business outcomes.</strong> Evaluate task completion rates, action failures, response quality, escalation rates, processing time, and customer satisfaction.</p><h3>10. The Future of Salesforce Development</h3><p>The introduction of Agentforce represents an important evolution in how Salesforce applications can be designed.</p><p>Earlier, developers primarily focused on building applications that followed predefined business rules. With agentic capabilities, developers can also build systems that interpret goals, work with business context, and coordinate multiple operations.</p><p>This does not mean traditional Salesforce development skills are becoming irrelevant.</p><p>In fact, a strong understanding of Apex, LWC, SOQL, Flow, security, integrations, and Salesforce architecture becomes even more valuable because these technologies provide the reliable foundation on which intelligent agents operate.</p><p>The future Salesforce developer will need to understand both traditional application development and AI-driven orchestration.</p><h3>Conclusion</h3><p>Agentforce and Agentic Workflows represent a move from task-based automation toward goal-oriented business execution.</p><p>Agentforce provides the platform for creating intelligent agents, while agentic workflows describe how those agents can coordinate data retrieval, business logic, integrations, and human collaboration to complete larger business processes.</p><p>The most effective approach is not to replace Flow or Apex with AI. It is to combine the flexibility of AI with the reliability of Salesforce’s existing automation and development capabilities.</p><p>For Salesforce developers and architects, understanding this combination will be an important skill in building the next generation of intelligent CRM applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01e7d5fd6baa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Required Fields in Salesforce Objects: A Guide for Developers]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/finding-required-fields-in-salesforce-objects-a-guide-for-developers-ef4cda731f9f?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef4cda731f9f</guid>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 13:46:53 GMT</pubDate>
            <atom:updated>2025-02-02T13:46:53.960Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Finding Required Fields in Salesforce Objects: A Guide for Developers</strong></p><p>As Salesforce developers, one of the most common challenges we face is understanding the structure of an object, especially when we need to identify the required fields for data insertion. Salesforce objects come with a mix of required and optional fields, and knowing which fields are truly necessary can significantly impact the way we interact with these objects programmatically.</p><p>To make this task easier, we can leverage Salesforce’s Schema API to dynamically determine the required fields for any custom or standard object. In this article, we’ll walk through a simple method that can help you identify all the necessary fields for a specific Salesforce object.</p><h3>The Code: How to Find Required Fields for a Salesforce Object</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apkgKMxzOdlgMmONWFHHVg.png" /></figure><h3>Explanation of the Code:</h3><ol><li><strong>sObjectName</strong>: This variable holds the name of the Salesforce object you’re interested in, such as Appointment__c. Replace it with any custom or standard object name.</li><li><strong>Global Describe</strong>: The Schema.getGlobalDescribe() method provides a map of all objects available in the Salesforce schema. We retrieve the specific object type using get(sObjectName).</li><li><strong>DescribeSObjectResult</strong>: This describes the metadata of the object, including its fields.</li><li><strong>Field Description</strong>: We iterate over all fields of the object and use getDescribe() on each field to retrieve detailed information.</li><li><strong>Identify Required Fields</strong>: A field is considered required if:</li></ol><ul><li>It is not <em>nillable</em> (meaning it cannot be left blank).</li><li>It is not <em>defaulted on create</em> (meaning it doesn’t automatically get a value during record creation).</li><li>If both conditions are met, the field is added to the requiredFields list.</li></ul><p><strong>6. Output</strong>: Finally, the list of required fields is printed out using System.debug().</p><h3>Why Is This Useful?</h3><p>When developing in Salesforce, understanding which fields are required helps in several key areas:</p><ol><li><strong>Data Validation</strong>: Ensuring that all required fields are populated when creating or updating records is crucial to avoid errors during DML operations (like insert or update). This method helps you identify all mandatory fields for your object, reducing the risk of running into errors when submitting data.</li><li><strong>Testing and Debugging</strong>: During unit testing or debugging, knowing which fields are required can help you write tests that simulate real-world scenarios more accurately. It’s especially useful for ensuring that test data creation includes all necessary fields to avoid test failures.</li><li><strong>Efficiency in Development</strong>: When working with complex Salesforce data models, manually checking each field for its required status can be tedious and error-prone. Automating this process with the Schema API simplifies development and increases productivity.</li></ol><h3>Limitations of the Approach</h3><p>While this method is effective in most cases, it’s important to note that it may not be 100% fault-proof. Some edge cases where this method might fall short include:</p><ol><li><strong>Formula Fields</strong>: Formula fields are often marked as required in the UI, but they may not be identified by this code because they are computed fields and may not be explicitly set as required in the object metadata.</li><li><strong>Validation Rules</strong>: Fields that are marked as required through validation rules or business logic are not always detected by this method. This is because validation rules might enforce required fields based on specific conditions that aren’t captured in the field’s metadata.</li><li><strong>Dependent Fields</strong>: Some fields’ requirements might be conditional, based on the value of another field. For example, certain fields may become required only if another field has a particular value. This approach does not account for such dependencies.</li><li><strong>Custom Metadata</strong>: If your object has custom metadata or dynamic field requirements based on a configuration or external logic, the method won’t capture these nuances.</li></ol><h3>Method 2: Using Schema Builder to Visualize Required Fields</h3><p>Another method for finding required fields is to use Salesforce’s <strong>Schema Builder</strong>. This tool offers a visual interface that can help you quickly identify the required fields within an object. Here’s how you can use it:</p><ol><li><strong>Navigate to Schema Builder</strong>:</li></ol><ul><li>Go to <strong>Setup</strong> in Salesforce.</li><li>From the <strong>Build</strong> section, select <strong>Schema Builder</strong>.</li></ul><p><strong>2. Select Your Object</strong>:</p><ul><li>Once the Schema Builder is open, you’ll see a list of available objects on the left-hand panel.</li><li>Click or select the object you want to inspect (e.g., Appointment__c).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*1OdlLymwZ0r8CL45YDCH9g.png" /></figure><p><strong>3. View Required Fields</strong>:</p><ul><li>After selecting your object, you will see a list of fields within that object.</li><li><strong>Required fields</strong> are marked with a red asterisk next to their name.</li></ul><p><strong>4. Scroll for More Fields</strong>:</p><ul><li>The Schema Builder shows up to 20 fields at a time. To see more fields, click <strong>Show More Fields</strong> and a scrollbar will appear, allowing you to scroll through the additional fields.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*L5hvo-UZEn8huGjeVwKAMA.png" /></figure><p><strong>5. Take Notes and Compare</strong>:</p><ul><li>You can note down the required fields and compare them with the data you are trying to feed in through the API. This method is especially helpful to ensure you don’t miss any required fields during your update operations.</li></ul><h3>Why Use Schema Builder?</h3><ul><li><strong>Visual Representation</strong>: Unlike the Apex code method, which requires coding and debugging, Schema Builder offers a <strong>graphical user interface</strong> that visually marks required fields, making it easy to understand which fields are essential.</li><li><strong>Quick Inspection</strong>: This method is faster for developers who prefer a visual representation of the fields and don’t want to dive into the code.</li><li><strong>Useful for Non-developers</strong>: For those who may not be as familiar with coding, Schema Builder provides a user-friendly way to inspect required fields without needing to write Apex code.</li></ul><h3>Conclusion</h3><p>In Salesforce development, identifying required fields programmatically can save you a lot of time and ensure your data operations are efficient and error-free. You can use the <strong>Apex Code method</strong> for automated field identification, or the <strong>Schema Builder method</strong> for a quick and visual representation of required fields.</p><p>While these methods are not perfect and may miss certain edge cases, they are highly effective for most use cases and can be a big help during development, testing, and debugging.</p><p>By using these methods, you can ensure that all the required fields are accounted for, leading to smoother data operations and better code quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef4cda731f9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging the Pub-Sub Model: API Calling with Platform Events in LWC]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/leveraging-the-pub-sub-model-api-calling-with-platform-events-in-lwc-c065844a364e?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c065844a364e</guid>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 07:32:11 GMT</pubDate>
            <atom:updated>2024-09-19T07:32:11.355Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Platform Events</strong> are a powerful feature in Salesforce that enable the exchange of real-time data between applications and components. They facilitate an event-driven architecture, allowing different Salesforce functionalities and external systems to communicate seamlessly. By defining custom event structures, developers can send and receive messages that trigger specific actions, ensuring instant updates and synchronization across various systems.</p><h3><strong>Pub-Sub Model</strong></h3><p>(Publisher-Subscriber) complements Platform Events by providing a standardized way to handle these asynchronous communications. In this model, a “publisher” emits events while “subscribers” listen for those events. When an event occurs, subscribers receive notifications, enabling them to react without direct coupling to the publisher. This decoupling enhances scalability and maintainability, allowing different parts of an application to evolve independently</p><h3>Steps to Create a Platform Event in Salesforce</h3><p><strong>1. Navigate to Setup</strong>:</p><ul><li>Log in to your Salesforce org.</li><li>Click on the gear icon (⚙️) in the top right corner and select <strong>Setup</strong>.</li></ul><p><strong>2. Find Platform Events</strong>:</p><ul><li>In the Quick Find box, type <strong>Platform Events</strong>.</li><li>Click on <strong>Platform Events</strong> under the <strong>Integrations</strong> section.</li></ul><p><strong>3. Create a New Platform Event</strong>:</p><ul><li>Click the <strong>New Platform Event</strong> button.</li><li>Enter a <strong>Label</strong> for your event (e.g., “Techdicer Event”).</li><li>The <strong>API Name</strong> will auto-populate based on the label. You can customize it if needed.</li></ul><p><strong>4. Define Event Fields</strong>:</p><ul><li>Scroll down to the <strong>Custom Fields</strong> section and click on <strong>New</strong>.</li><li>Choose the appropriate field type (e.g., Text, Number, Date/Time) for the data you want to send.</li><li>Fill in the field details (e.g., Field Label, Field Name, Length, etc.) and click <strong>Next</strong>.</li><li>Set the field-level security and visibility as needed, then click <strong>Next</strong>.</li><li>Review your settings and click <strong>Save</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHADVXPbFEdi5SOEhlYiAQ.png" /><figcaption>Creating Platform Event</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_BdyqJD1eAYorsAWBh43Q.png" /><figcaption>Custom Feilds</figcaption></figure><h4>Emit events when specific conditions are met, using Apex or Process Builder. I will create an Apex class to publish the platform event.</h4><blockquote>public class PlatformEventCtrl {<br> public static void publishEvent() {<br> Event__e event = new Event__e();<br> event.message__c = ‘test’;<br> event.recordId__c = ‘0016F000041zsTDQAY’;<br> event.status__c = ‘Success’;<br> EventBus.publish(event);<br> }<br>}</blockquote><h4>Leverage Lightning Web Components to subscribe to these events and take immediate action. Here we will create an LWC component for Subscribe to the event and show data sent by the platform event.</h4><h4>Html file</h4><blockquote>&lt;template&gt;<br> &lt;lightning-card title=”Platform Event In LWC Techdicer” icon-name=”standard:contact”&gt;<br> &lt;div class=”slds-m-around_medium”&gt;<br> &lt;p&gt;Status: {status}&lt;/p&gt;<br> &lt;p&gt;Message: {message}&lt;/p&gt;<br> &lt;p&gt;Record Id: {recordId}&lt;/p&gt;<br> &lt;/div&gt;<br> &lt;/lightning-card&gt;<br>&lt;/template&gt;</blockquote><h4>LWCPlatformEvent.js file</h4><blockquote>import { LightningElement, api, track } from ‘lwc’;<br>import { subscribe, unsubscribe, onError } from ‘lightning/empApi’;<br>import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;</blockquote><blockquote>export default class LWCPlatformEvent extends LightningElement {<br> <a href="http://twitter.com/track">@track</a> status;<br> <a href="http://twitter.com/track">@track</a> message;<br> <a href="http://twitter.com/track">@track</a> recordId;</blockquote><blockquote>subscription = {};<br> <a href="http://twitter.com/api">@api</a> channelName = ‘/event/event__e’; // Updated to match the event name</blockquote><blockquote>connectedCallback() {<br> // Register error listener <br> this.registerErrorListener();<br> this.handleSubscribe();<br> }</blockquote><blockquote>// Handles subscription<br> handleSubscribe() {<br> const self = this;<br> const messageCallback = function (response) {<br> console.log(‘New message received: ‘, JSON.stringify(response));<br> const objData = response.data.payload; // No need for JSON parse<br> self.message = objData.message__c;<br> self.status = objData.status__c; // Ensure this matches the field name<br> self.recordId = objData.recordId__c;<br> self.showToast(‘Event Received’, self.message, ‘success’, ‘dismissable’);<br> };</blockquote><blockquote>// Invoke subscribe method of empApi<br> subscribe(this.channelName, -1, messageCallback).then(response =&gt; {<br> console.log(‘Subscription request sent to: ‘, JSON.stringify(response.channel));<br> this.subscription = response;<br> });<br> }</blockquote><blockquote>// Handle error<br> registerErrorListener() {<br> onError(error =&gt; {<br> console.log(‘Received error from server: ‘, JSON.stringify(error));<br> });<br> }</blockquote><blockquote>showToast(title, message, variant, mode) {<br> const evt = new ShowToastEvent({<br> title: title,<br> message: message,<br> variant: variant,<br> mode: mode<br> });<br> this.dispatchEvent(evt);<br> }<br>}</blockquote><p>Call the class</p><blockquote>PlatformEventCtrl.publishEvent();</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_3moOY8Rde45k-8hwzd8A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c065844a364e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Event Monitoring in Salesforce]]></title>
            <link>https://medium.com/@kotnalacooldivyansh/real-time-event-monitoring-in-salesforce-fe1bdd731e41?source=rss-7f8e18d2273a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe1bdd731e41</guid>
            <dc:creator><![CDATA[Divyansh Kotnala]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 12:58:01 GMT</pubDate>
            <atom:updated>2024-09-15T12:58:01.216Z</atom:updated>
            <content:encoded><![CDATA[<p>Salesforce provides a powerful feature known as <strong>Real-Time Event Monitoring</strong>, which allows organizations to monitor and track important user actions and system behavior. This feature is critical for ensuring the security, performance, and health of your Salesforce environment. Real-Time Event Monitoring gives administrators and developers detailed insight into what’s happening within their Salesforce instance, helping them to detect anomalies, troubleshoot issues, and meet compliance requirements.</p><p>At the heart of Salesforce Event Monitoring are <strong>Event Log Files</strong> and various <strong>Event Monitoring objects</strong> that capture specific types of events in real-time. These events include user logins, page views, data exports, and more, providing actionable data for improving system performance, user behavior analysis, and security auditing.</p><p>In this article, we’ll explore the key concepts of <strong>Real-Time Event Monitoring</strong> in Salesforce and discuss the core <strong>Event Monitoring objects</strong> that help organizations track events effectively.</p><h3>What is Real-Time Event Monitoring?</h3><p><strong>Real-Time Event Monitoring</strong> provides visibility into Salesforce usage and system activity in real-time. This includes tracking user actions like logins, report executions, or record access. The data is collected in the form of <strong>event logs</strong>, which can be queried using <strong>Event Log File</strong> (ELF) objects and accessed through the <strong>Event Monitoring API</strong>.</p><p>With this data, administrators can identify and mitigate performance issues, monitor security risks, and create custom alerts or automation to respond to certain events.</p><h4>Key Use Cases:</h4><ul><li><strong>Security Auditing</strong>: Detect suspicious activities such as data exports or unauthorized logins.</li><li><strong>Performance Monitoring</strong>: Track events to analyze performance bottlenecks and page load times.</li><li><strong>Compliance and Governance</strong>: Ensure regulatory compliance by monitoring how data is accessed and shared.</li><li><strong>Troubleshooting and Debugging</strong>: Pinpoint issues by tracking system or user actions in real time.</li></ul><h3>Core Event Monitoring Objects</h3><p>Event Monitoring objects are specialized Salesforce objects that store event data for various types of activities occurring within your Salesforce organization. Some of the most commonly monitored events include login attempts, API usage, page views, and record modifications.</p><p>Here’s a breakdown of some of the key <strong>Event Monitoring objects</strong>:</p><h4>1. LoginEvent:</h4><p>The LoginEvent object stores information about user login attempts. It records details like the login time, login status (success or failure), user ID, and the origin of the login attempt. This object is crucial for monitoring access patterns and identifying unauthorized login attempts.</p><ul><li><strong>Key Fields</strong>:</li><li>LoginTime</li><li>UserId</li><li>LoginType</li><li>LoginStatus</li></ul><h4>2. LogoutEvent:</h4><p>The LogoutEvent object tracks user logout activities. It logs when a user has successfully logged out of Salesforce, providing a clear audit trail of user sessions.</p><ul><li><strong>Key Fields</strong>:</li><li>LogoutTime</li><li>UserId</li></ul><h4>3. ApiEvent:</h4><p>The ApiEvent object tracks all API calls made to the Salesforce platform. This is particularly useful for monitoring integrations and understanding how external systems interact with Salesforce.</p><ul><li><strong>Key Fields</strong>:</li><li>ApiVersion</li><li>Uri</li><li>RequestSize</li><li>ResponseTime</li></ul><h4>4. ReportEvent:</h4><p>The ReportEvent object logs events related to report generation. This includes when reports are run and how long it takes to generate them, helping administrators monitor report usage and performance.</p><ul><li><strong>Key Fields</strong>:</li><li>ReportId</li><li>ExecutionTime</li><li>RowCount</li></ul><h4>5. ListViewEvent:</h4><p>The ListViewEvent object tracks usage of Salesforce list views, which are used to display lists of records in a tabular format. This object provides data on which list views are accessed and how they are used.</p><ul><li><strong>Key Fields</strong>:</li><li>ListViewId</li><li>UserId</li><li>ExecutionTime</li></ul><h4>6. ChangeEventHeader:</h4><p>The ChangeEventHeader object is part of <strong>Change Data Capture (CDC)</strong>, which tracks changes to Salesforce records in real-time. The events captured by this object include record creation, updates, and deletion events.</p><ul><li><strong>Key Fields</strong>:</li><li>ChangeType (Create, Update, Delete)</li><li>EntityName</li><li>RecordIds</li></ul><h3>How to Access Event Monitoring Data</h3><p>Event Monitoring data can be accessed in several ways:</p><h4>1. Event Monitoring API:</h4><p>You can use the <strong>Event Monitoring REST API</strong> to retrieve event log data. This API allows developers to query and download large volumes of event logs for further analysis. The logs are available in <strong>JSON</strong>, <strong>CSV</strong>, or <strong>XML</strong> formats.</p><h4>2. SOQL Queries:</h4><p>Many of the Event Monitoring objects, such as LoginEvent and ApiEvent, can be queried directly using SOQL (Salesforce Object Query Language). This provides a simple and efficient way to extract event data for custom reports or dashboards.</p><h4>3. Event Log File (ELF) Browser:</h4><p>Salesforce provides an <strong>Event Log File Browser</strong> app, available on the AppExchange, that lets you view and download event log files from the past 30 days without the need for API calls.</p><h4>4. Real-Time Event Monitoring Dashboard:</h4><p>Salesforce also offers pre-built <strong>Real-Time Event Monitoring dashboards</strong>, which are available as part of the <strong>Salesforce Shield</strong> suite. These dashboards provide visual insights into key security and performance metrics.</p><h3>Real-Time Event Monitoring vs. Transaction Security</h3><p>Salesforce Shield also provides <strong>Transaction Security Policies</strong>, which work closely with Real-Time Event Monitoring. While Real-Time Event Monitoring logs and tracks events, <strong>Transaction Security</strong> allows you to define custom policies that trigger actions in response to specific events. For example, if an unusual number of API calls are detected, you can define a policy to block the user or notify an administrator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe1bdd731e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>