RP.
Database Portals / SOQL Details

Purpose & Utility

Why do we need SOQL?

SOQL is the bridge between your logic and the physical data. It allows you to talk to the database and retrieve exactly what you need with surgical precision.

Relational Retrieval

Retrieve data from a single object or cross-reference multiple objects that are related through parent-child lookups.

Cross-Object Access

Calculated Logic

Power your logic by using SOQL to Count, Sort, and Group records based on complex business criteria.

Aggregate Functions

Universal Support

Seamlessly retrieve data from all platform datatypes including Date, Checkbox, and Number.

Full Schema Coverage

Architecture

Query Structure

SELECT
<fields>
List of fields
FROM
<objectname>
Object API Name
WHERE
<Filter Condition>
Filter Condition

Calculated Insights

Aggregate Functions

Aggregate functions allow you to perform calculations on a set of records. Instead of returning individual rows, the database returns summarized data like totals, averages, or counts.

Quantity

COUNT()

Returns the number of rows matching your criteria.

SELECT COUNT(Id) FROM Account
Total Value

SUM()

Calculates the total sum of a numeric field.

SELECT SUM(Amount) FROM Opportunity
Mean

AVG()

Finds the average value of a numeric field.

SELECT AVG(ExpectedRevenue) FROM Opportunity
Extremes

MIN() & MAX()

Retrieves the lowest or highest value in a set.

SELECT MAX(Amount), MIN(Amount) FROM Opportunity

The GROUP BY Clause

To summarize data by a specific field (like Stage or Industry), you must use GROUP BY. This is the foundation of Salesforce reporting.

SELECT LeadSource, COUNT(Name)

FROM Lead

GROUP BY LeadSource

Advanced Retrieval

Relationship Queries

Salesforce is a relational database. Use these patterns to traverse between objects without writing multiple queries, saving you from hitting governor limits.

Child to Parent

When querying a child object (like Contact), use **Dot Notation** to reach up and grab data from the parent (like Account).

// Retrieve Contact with Parent Account Name

SELECT Name, Account.Name

FROM Contact

Rule: Use the Relationship Name + "." + Field Name

Parent to Child

When querying a parent, use a **Subquery** inside parentheses to retrieve all related children in one go.

// Retrieve Account with all its related Contacts

SELECT Name, (SELECT LastName FROM Contacts)

FROM Account

Rule: Use the Child Relationship Name (usually plural)

Constraints

Governor Limits

In the Salesforce multi-tenant environment, limits are not suggestions—they are hard rules that ensure platform stability for everyone.

Query Frequency

Per Transaction

100

Sync Queries (Limit)

Number of SOQL queries per transaction: 100 (sync). This means you cannot execute more than 100 SELECT statements in a single code execution path.

Retrieval Volume

Total Records

50,000

Max Records (Limit)

Number of SOQL records returned per query: 50,000. Regardless of how many queries you run, the total records fetched cannot exceed this threshold.

Developer Best Practice: Never place a SOQL query inside a FOR loop. This is the fastest way to hit the 100-query limit. Always "bulkify" your code by querying once and storing results in a Map or List.

Practical Application

Use Cases

Test your knowledge with these common development scenarios. Mastering these patterns is essential for building efficient Salesforce applications.

Scenario 01

Targeted Data Retrieval

Question: How do you retrieve the Name and Phone of all Accounts where the Industry is 'Technology' and the Account is active?

// The Solution

SELECT Name, Phone

FROM Account

WHERE Industry = 'Technology'

AND IsActive__c = true

Scenario 02

Chronological Sorting

Question: You need to get the 10 most recently created Contacts. How do you structure the query?

// The Solution

SELECT FirstName, LastName, CreatedDate

FROM Contact

ORDER BY CreatedDate DESC

LIMIT 10

Scenario 03

Relational Logic

Question: How can you retrieve an Account's name along with the names of all its related Contacts in a single query?

// The Solution (Inner Join)

SELECT Name, (SELECT LastName FROM Contacts)

FROM Account

Scenario 04

Querying by Date Literals

Question: How do you find all Contacts whose birthday is recorded as today's date?

Pro Tip: Using the TODAY literal automatically handles timezones and formatting for you.

// The Solution

SELECT Name, Birthdate

FROM Contact

WHERE Birthdate = TODAY

Scenario 05

Filtering by Picklist Values

Question: How do you retrieve all Accounts that are publicly owned and have a 'Hot' rating?

Database Tip: When filtering by text or picklist values in SOQL, always wrap the values in single quotes.

// The Solution

SELECT Name, Ownership, Rating

FROM Account

WHERE Ownership = 'Public'

AND Rating = 'Hot'

Scenario 06

Tracking Inbound Leads

Question: How do you retrieve all Leads that are in the 'Working - Contacted' status and came from the 'Web' source?

Developer Note: For fields containing spaces like Working - Contacted, ensure the string inside the single quotes matches the picklist value exactly.

// The Solution

SELECT Name, Status, LeadSource

FROM Lead

WHERE Status = 'Working - Contacted'

AND LeadSource = 'Web'

Scenario 07

Searching by Individual Name

Question: How do you retrieve all Contacts whose name is recorded exactly as 'Jane'?

Database Fact: While SOQL keywords like SELECT are case-insensitive, the string filter 'Jane' is often treated with precision depending on your org's collation settings.

// The Solution

SELECT Name, Email

FROM Contact

WHERE Name = 'Jane'

Scenario 08

Broadening Your Search

Question: How do you retrieve all Accounts where the Industry is 'Banking' OR the Ownership is 'Private'?

Logic Tip: Unlike the AND operator which requires both conditions to be true, the OR operator returns a record if either one of the conditions is met.

// The Solution

SELECT Name, Industry, Ownership

FROM Account

WHERE Industry = 'Banking'

OR Ownership = 'Private'

Scenario 09

Filtering with Collections

Question: How do you retrieve Accounts belonging to any of these three industries: 'Banking', 'Technology', or 'Business'?

Optimization Tip: Using IN is much cleaner and faster than writing multiple OR statements for the same field.

// The Solution

SELECT Id, Name, Industry, Ownership

FROM Account

WHERE Industry IN ('Banking', 'Business', 'Technology')

Scenario 10

Filtering with Wildcards

Question: How do you retrieve all Cases where the Subject line starts with the word 'Follow'?

Wildcard Tip: The % symbol represents zero or more characters. Placing it after your text finds records starting with that string.

// The Solution

SELECT Subject, Status, Priority

FROM Case

WHERE Subject LIKE 'Follow%'

Scenario 11

Ranking by Revenue

Question: How do you display all Opportunities in your org, ensuring the ones with the highest revenue appear at the top?

Sorting Tip: The ORDER BY clause is always placed at the end of your query. Use DESC for highest-to-lowest and ASC for lowest-to-highest.

// The Solution

SELECT Amount, Id, Name

FROM Opportunity

ORDER BY Amount DESC

Scenario 12

Handling Overdue Deals

Question: How do you display exactly 10 Opportunities where the Close Date has already passed (is in the past)?

Efficiency Tip: The LIMIT operator is vital for performance. It prevents the database from returning thousands of records when you only need a small sample for your UI.

// The Solution

SELECT Name, CloseDate, StageName

FROM Opportunity

WHERE CloseDate < TODAY

LIMIT 10

Scenario 13

Sorting & Skipping Records

Question: How do you retrieve all Accounts sorted alphabetically by Name, but excluding the first 5 records from the results?

Pro Tip: The OFFSET clause allows you to skip a specific number of rows before beginning to return records. This is essential for building "Load More" or "Next Page" buttons.

// The Solution

SELECT Name, Industry, Ownership

FROM Account

ORDER BY Name ASC

OFFSET 5

Scenario 14

Lead Status Distribution

Question: How do you retrieve a count of how many Leads exist for every different Status in your organization?

Syntax Rule: When using an aggregate function like COUNT() with a field like Status, you must include that field in the GROUP BY clause.

// The Solution

SELECT Status, COUNT(Id)

FROM Lead

GROUP BY Status

Scenario 15

Relative Monthly Tracking

Question: How do you find all Cases that were created within the current calendar month?

Date Literal: Using THIS_MONTH is dynamic; it automatically adjusts every time the month changes without you needing to update your code.

// The Solution

SELECT Subject, CreatedDate, Status

FROM Case

WHERE CreatedDate = THIS_MONTH

Scenario 16

Fixed Range Filtering

Question: How do you retrieve Tasks created between October 7th and November 15th?

Format Rule: For specific dates, SOQL requires the YYYY-MM-DD format. Since CreatedDate is a DateTime field, we append the time suffix T00:00:00Z.

// The Solution

SELECT Subject, CreatedDate

FROM Task

WHERE CreatedDate >= 2025-10-07T00:00:00Z

AND CreatedDate <= 2025-11-15T23:59:59Z