Formula Field

Formula Field Practice Problems

32 free Salesforce Apex challenges · Full problem statements, best-practice notes, and step-by-step hints · Solve live on ApexArena

This guide walks through 32 cross-object and conditional formula-field exercises. Each entry below includes the full problem statement, the governor-limit and best-practice constraints it's testing, and a numbered approach to solving it — then you can open the same problem in ApexArena's browser-based Apex editor and get instant pass/fail feedback against real test cases.

On this page
  1. 1. Formula: Sales Commission Calculator
  2. 2. Formula: Cross-Object Formula — Parent Account Industry
  3. 3. Formula: Multi-Tier Discount with CASE()
  4. 4. Formula: Opportunity Days Open & Age Category
  5. 5. BLANKVALUE and ISNULL: Null Handling in Formulas
  6. 6. Text Functions: UPPER, LOWER, LEFT, RIGHT, MID, LEN
  7. 7. Number Functions: FLOOR, CEILING, ABS, MOD, MAX, MIN
  8. 8. Compound Logical: OR, AND, NOT for Lead Qualification
  9. 9. ISPICKVAL: Conditional Logic on Picklist Fields
  10. 10. Date Arithmetic: DATEVALUE, DATE, YEAR, MONTH, DAY
  11. 11. VLOOKUP: Auto-Fill Fields from a Custom Metadata Object
  12. 12. Advanced CASE() + Nested IF: SLA Tier Calculator
  13. 13. Formula: Full Mailing Address Concatenation
  14. 14. Formula: Days Until Contract Expiration With Urgency Flag
  15. 15. Formula: HYPERLINK to an External Legacy System
  16. 16. Formula: Full Name Formatter With Blank FirstName Handling
  17. 17. Formula: Probability-Weighted Opportunity Amount
  18. 18. Formula: Account Tier Badge From Revenue and Headcount
  19. 19. Formula: Days Since Last Activity (Null-Safe, Whole Number)
  20. 20. Formula: Lead Score Tier Using CASE()
  21. 21. Formula: Two-Level Cross-Object Field — Contact's Account Owner Email
  22. 22. Formula: Use TEXT() to Concatenate a Picklist Value
  23. 23. Formula: Rounded Weighted Forecast With Blank-Safe Inputs
  24. 24. Formula: Territory Code From Country and State
  25. 25. Formula: Deal Risk Flag From Stage, Age, and Amount
  26. 26. Formula: Sales Target Achievement Percentage
  27. 27. Formula: Display Discount Percentage From List Price and Sale Price
  28. 28. Formula: Calculate Gross Profit From Revenue and Cost
  29. 29. Formula: Display a Human-Readable Quarter Name From Close Date
  30. 30. Formula: Renewal Priority Score for Expiring Contracts
  31. 31. Formula: Product Margin Percentage With Cost and Discount Tiers
  32. 32. Formula: Customer Lifetime Value (CLV) Estimate
Easy Formula

1. Formula: Sales Commission Calculator

Problem #305 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field named Commission__c on the Opportunity object that calculates the sales representative's commission:

  • If StageName equals 'Closed Won' → commission = 5% of Amount
  • Otherwise → commission = 0

Field Details

  • Object: Opportunity
  • Return type: Currency
  • Formula uses the IF() function

Syntax

IF(logical_test, value_if_true, value_if_false)
Approach
  • 1IF() takes three arguments: condition, true-value, false-value.
  • 2String comparisons in formulas use = not ==.
  • 3Multiply Amount by 0.05 to get 5%.
Medium Formula

2. Formula: Cross-Object Formula — Parent Account Industry

Problem #306 · Salesforce Apex Coding Challenge

Problem Statement

Write a cross-object formula field named Account_Industry__c on the Contact object that:

  • Returns the Industry field from the parent Account
  • If the Account's Industry is blank, returns the text 'No Industry'
  • Uses the cross-object formula syntax: Account.Industry

Cross-Object Formula Syntax

To access a field on a related object, use dot notation through the relationship name:

RelationshipName.FieldName

For standard lookup relationships: Account.Industry, Owner.Name, etc.

Key Functions

  • ISBLANK(value) — returns true if the value is null or empty string
Approach
  • 1Cross-object formula: Account.Industry traverses the Contact's Account lookup.
  • 2ISBLANK() checks for null or empty — better than = null for text fields.
  • 3IF(ISBLANK(Account.Industry), "No Industry", Account.Industry)
Medium Formula

3. Formula: Multi-Tier Discount with CASE()

Problem #307 · Salesforce Apex Coding Challenge

Problem Statement

Write a formula field Discount_Pct__c on Opportunity that returns the discount percentage based on the Amount:

Amount RangeDiscount
≥ 50,00015%
≥ 20,00010%
≥ 10,0008%
≥ 5,0005%
< 5,0000%

Return Type

Percent field — return the number (e.g., 15 for 15%)

Use nested IF() or CASE()

Both approaches are valid. Nested IF() is often clearer for range-based logic.

Approach
  • 1Nested IF: IF(Amount >= 50000, 15, IF(Amount >= 20000, 10, ...))
  • 2Check from the highest tier downward — the first matching condition wins.
  • 3Return the number (15, not 0.15) for a Percent field.
Medium Formula

4. Formula: Opportunity Days Open & Age Category

Problem #308 · Salesforce Apex Coding Challenge

Problem Statement

Write two formula fields on the Opportunity object:

1. Days_Open__c (Number)

Calculate how many days the opportunity has been open:

  • If the opportunity is closed (IsClosed = true): CloseDate - CreatedDate
  • If still open: TODAY() - DATEVALUE(CreatedDate)
  • Use ROUND(..., 0) to get a whole number

2. Age_Category__c (Text)

Categorize the opportunity age using Days_Open__c:

  • ≥ 90 days → 'Stale'
  • ≥ 30 days → 'Aging'
  • ≥ 7 days → 'Active'
  • < 7 days → 'New'

Date Formula Functions

  • TODAY() — returns today's date
  • DATEVALUE(datetime) — converts DateTime to Date
  • ROUND(number, decimal_places) — rounds to whole number
Approach
  • 1DATEVALUE() converts CreatedDate (DateTime) to Date so subtraction works.
  • 2TODAY() returns today as a Date — no conversion needed.
  • 3Use IsClosed (Boolean checkbox field) in the IF condition, not a string compare.
Easy Formula Field

5. BLANKVALUE and ISNULL: Null Handling in Formulas

Problem #309 · Salesforce Apex Coding Challenge

Problem Statement

A Contact object has a text field Nickname__c (can be blank) and a number field Years_Known__c (can be null).

Create two formula fields:

  • Display_Name__c — returns Nickname__c if not blank, otherwise returns FirstName
  • Known_Years__c — returns Years_Known__c if not null, otherwise returns 0

Functions to Use

  • BLANKVALUE(field, substitute) — returns field unless blank, then returns substitute
  • ISNULL(field) — returns TRUE if field is null
  • IF(condition, true_val, false_val)
Approach
  • 1BLANKVALUE is the right tool for text fields — use it for Display_Name__c.
  • 2For number fields that can be null, use BLANKVALUE or IF(ISNULL(...), 0, field).
  • 3ISNULL does not work reliably on text fields in Salesforce — prefer ISBLANK for text.
Easy Formula Field

6. Text Functions: UPPER, LOWER, LEFT, RIGHT, MID, LEN

Problem #310 · Salesforce Apex Coding Challenge

Problem Statement

A Lead object has a text field Raw_Code__c (format: AB-12345-XY).

Create three formula fields:

  • Code_Upper__c — returns Raw_Code__c in ALL CAPS
  • Code_Prefix__c — returns the first 2 characters of Raw_Code__c
  • Code_Suffix__c — returns the last 2 characters of Raw_Code__c

Functions to Use

  • UPPER(text) / LOWER(text)
  • LEFT(text, num_chars) / RIGHT(text, num_chars)
  • MID(text, start_num, num_chars)
  • LEN(text)
Approach
  • 1UPPER(Raw_Code__c) converts the entire string to uppercase.
  • 2LEFT(Raw_Code__c, 2) gets the first two characters.
  • 3RIGHT(Raw_Code__c, 2) gets the last two characters.
Easy Formula Field

7. Number Functions: FLOOR, CEILING, ABS, MOD, MAX, MIN

Problem #311 · Salesforce Apex Coding Challenge

Problem Statement

An Opportunity has fields Raw_Score__c (decimal, can be negative) and Bonus__c (number).

Create three formula fields:

  • Floor_Score__c — the largest integer ≤ Raw_Score__c
  • Abs_Score__c — the absolute value of Raw_Score__c
  • Remainder__c — remainder when Raw_Score__c is divided by 7

Functions

  • FLOOR(number) — round down to nearest integer
  • CEILING(number) — round up to nearest integer
  • ABS(number) — absolute value
  • MOD(number, divisor) — remainder after division
  • MAX(n1, n2, ...) / MIN(n1, n2, ...)
Approach
  • 1FLOOR(Raw_Score__c) rounds down to the nearest integer.
  • 2ABS(Raw_Score__c) returns the non-negative value.
  • 3MOD(Raw_Score__c, 7) gives the remainder when divided by 7.
Medium Formula Field

8. Compound Logical: OR, AND, NOT for Lead Qualification

Problem #314 · Salesforce Apex Coding Challenge

Problem Statement

A Lead object has these fields:

  • AnnualRevenue (currency)
  • NumberOfEmployees (integer)
  • Industry (text)
  • IsConverted (boolean)

Create a checkbox formula field Is_Qualified__c that returns TRUE when the lead is not converted AND meets at least one of these criteria:

  • AnnualRevenue ≥ 1,000,000
  • NumberOfEmployees ≥ 200
  • Industry = "Technology"
Approach
  • 1Use NOT(IsConverted) to exclude converted leads.
  • 2Wrap the three criteria in OR(condition1, condition2, condition3).
  • 3Combine with AND(NOT(IsConverted), OR(...)).
Medium Formula Field

9. ISPICKVAL: Conditional Logic on Picklist Fields

Problem #315 · Salesforce Apex Coding Challenge

Problem Statement

An Opportunity has a picklist field StageName.

Create a formula field Stage_Group__c (Text) that maps stages to groups:

  • "Prospecting" or "Qualification" → "Early"
  • "Needs Analysis" or "Value Proposition" or "Id. Decision Makers" → "Mid"
  • "Perception Analysis" or "Proposal/Price Quote" or "Negotiation/Review" → "Late"
  • "Closed Won" → "Won"
  • "Closed Lost" → "Lost"

Key Function

  • ISPICKVAL(field, value) — returns TRUE if picklist field equals the given value
Approach
  • 1You cannot use = to compare picklist values — you must use ISPICKVAL().
  • 2Nest IF() statements or use a CASE() expression for multiple stages.
  • 3OR(ISPICKVAL(StageName, "Prospecting"), ISPICKVAL(StageName, "Qualification")) handles the Early group.
Medium Formula Field

10. Date Arithmetic: DATEVALUE, DATE, YEAR, MONTH, DAY

Problem #316 · Salesforce Apex Coding Challenge

Problem Statement

A Contract object has a StartDate (Date) field.

Create two formula fields:

  • Contract_Year__c (Number) — the year portion of StartDate
  • Anniversary_Date__c (Date) — the date exactly one year after StartDate using DATE(YEAR(StartDate)+1, MONTH(StartDate), DAY(StartDate))

Date Functions

  • YEAR(date) / MONTH(date) / DAY(date)
  • DATE(year, month, day) — construct a date from parts
  • DATEVALUE(text_or_datetime) — convert to Date
  • TODAY() — today's date
Approach
  • 1YEAR(StartDate) extracts just the year as a number.
  • 2DATE(YEAR(StartDate)+1, MONTH(StartDate), DAY(StartDate)) shifts the year by 1.
  • 3No DATEVALUE needed here since StartDate is already a Date (not DateTime).
Hard Formula Field

11. VLOOKUP: Auto-Fill Fields from a Custom Metadata Object

Problem #317 · Salesforce Apex Coding Challenge

Problem Statement

You have a custom object Region_Config__c with fields:

  • Region_Code__c (Text, external ID) — e.g., "NA", "EMEA", "APAC"
  • Tax_Rate__c (Percent)
  • Currency_Symbol__c (Text)

On the Opportunity object there is a text field Region__c.

Create two formula fields on Opportunity:

  • Lookup_Tax_Rate__c — the Tax_Rate__c from Region_Config__c where Region_Code__c = Region__c
  • Lookup_Currency__c — the Currency_Symbol__c from the same lookup

Key Function

  • VLOOKUP(field_to_return, lookup_field, lookup_value)
Approach
  • 1VLOOKUP syntax: VLOOKUP($ObjectType..Fields., $ObjectType..Fields., ) — substitute the actual object and field names from the problem.
  • 2The first argument is the field you want to return.
  • 3The second argument is the lookup key field on the target object.
  • 4The third argument is the value on the current record to match against.
Hard Formula Field

12. Advanced CASE() + Nested IF: SLA Tier Calculator

Problem #318 · Salesforce Apex Coding Challenge

Problem Statement

A Case object has these fields:

  • Priority (picklist: "High", "Medium", "Low")
  • Account.Industry (text via relationship)
  • CreatedDate (DateTime)

Create a formula field SLA_Tier__c (Text) using these rules:

  • If Priority = "High" AND Account.Industry = "Healthcare" → "Platinum"
  • If Priority = "High" → "Gold"
  • If Priority = "Medium" AND Account.Industry = "Technology" → "Silver"
  • If Priority = "Medium" → "Bronze"
  • Otherwise → "Standard"

Also create SLA_Hours__c (Number) using CASE() to map Priority to response hours: High→4, Medium→8, Low→24.

Approach
  • 1For SLA_Tier__c, use nested IF() since you need compound AND conditions.
  • 2ISPICKVAL(Priority, "High") is required — you cannot use Priority = "High" for picklist.
  • 3Cross-object formula: Account.Industry accesses the parent Account's Industry.
  • 4For SLA_Hours__c, CASE(Priority, "High", 4, "Medium", 8, "Low", 24, 0) is clean but picklist requires CASE with ISPICKVAL or nested IF.
Easy Formula Field

13. Formula: Full Mailing Address Concatenation

Problem #402 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Full_Mailing_Address__c on Contact that concatenates MailingStreet, MailingCity, MailingState, and MailingPostalCode into one readable line — without leaving stray double-commas or trailing separators when a component is blank.

Field Details

  • Object: Contact
  • Return type: Text Area (Long)
  • Example output: 123 Main St, Springfield, IL 62704

Functions to Use

  • IF(ISBLANK(field), "", field & separator) — appends a field plus its trailing separator only when the field actually has a value.
  • BLANKVALUE(field, "") — simpler form for the last component, which needs no trailing separator.
Approach
  • 1For every component except the last, wrap it as IF(ISBLANK(field), "", field & ", ") so a blank field contributes nothing at all.
  • 2The & operator concatenates strings in Salesforce formulas — not +.
  • 3The last component (MailingPostalCode) needs no trailing separator, so BLANKVALUE(MailingPostalCode, "") is enough on its own.
Medium Formula Field

14. Formula: Days Until Contract Expiration With Urgency Flag

Problem #403 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Expiration_Urgency__c on the standard Contract object that classifies how close the Contract's EndDate is to expiring:

  • EndDate already passed → "Expired"
  • Expires within the next 7 days → "Urgent"
  • Expires within the next 30 days → "Soon"
  • Otherwise → "OK"

Field Details

  • Object: Contract
  • Return type: Text

Functions to Use

  • Nested IF() — check the most urgent case first, then fall through.
  • TODAY() and Date arithmetic (TODAY() + 7) to build the comparison windows.
Approach
  • 1Order the checks from most urgent to least urgent — nested IF() falls through to the next check only when the current one is false.
  • 2A Date field plus an Integer (TODAY() + 7) is valid formula arithmetic and returns a Date 7 days later.
  • 3The final ELSE branch of the innermost IF() is just the plain string "OK", with no further condition.
Hard Formula Field

15. Formula: HYPERLINK to an External Legacy System

Problem #404 · Salesforce Apex Coding Challenge

Problem Statement

An Account has a custom text field External_Id__c storing its Id in a legacy external system. Write a Formula field Legacy_System_Link__c that renders a clickable link to that record — but shows nothing (not a broken link) when External_Id__c is blank.

Field Details

  • Object: Account
  • Return type: Text (formula renders as a link)
  • Link target: https://legacy.example.com/accounts/<External_Id__c>, opened in a new tab, labeled "View in Legacy System".

Functions to Use

  • HYPERLINK(url, label, target)target of "_blank" opens the link in a new tab/window.
  • IF(ISBLANK(field), "", ...) to suppress the link entirely when there's no external Id to link to.
Approach
  • 1Wrap the whole HYPERLINK() call in IF(ISBLANK(External_Id__c), "", ...) so a missing Id never produces a dead link.
  • 2HYPERLINK() takes three arguments: the URL, the visible label, and the target ("_blank" for a new tab).
  • 3Build the URL by concatenating the fixed base path with External_Id__c using &.
Easy Formula Field

16. Formula: Full Name Formatter With Blank FirstName Handling

Problem #425 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Display_Full_Name__c on Contact that combines FirstName and LastName with a single space between them — but returns just LastName (no leading space) when FirstName is blank.

Field Details

  • Object: Contact
  • Return type: Text
Approach
  • 1IF(ISBLANK(FirstName), LastName, ...) handles the no-first-name case cleanly.
  • 2The & operator concatenates strings; " " as a literal string adds the space between names.
  • 3Concatenating a blank FirstName directly (FirstName & " " & LastName) without the IF guard would leave a stray leading space.

Halfway there — solve them live

Every problem above runs in a real in-browser Apex editor with instant pass/fail feedback and best-practice linting. No Salesforce org needed.

Create Free Account →
Easy Formula Field

17. Formula: Probability-Weighted Opportunity Amount

Problem #426 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Weighted_Amount__c on Opportunity that multiplies Amount by Probability to produce a probability-weighted forecast value — treating a blank Amount as 0 instead of erroring.

Field Details

  • Object: Opportunity
  • Return type: Currency
  • Probability is a Percent field stored as a whole number (e.g. 60 for 60%), so it must be divided by 100 before multiplying.
Approach
  • 1BLANKVALUE(Amount, 0) avoids an error from multiplying against a blank Amount.
  • 2Probability is stored as a whole number (60 means 60%), so divide by 100 before multiplying.
  • 3The full formula is BLANKVALUE(Amount, 0) * (Probability / 100).
Medium Formula Field

18. Formula: Account Tier Badge From Revenue and Headcount

Problem #427 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Account_Tier__c on Account that combines AnnualRevenue and NumberOfEmployees into a tier label:

  • Both AnnualRevenue >= 10,000,000 and NumberOfEmployees >= 500"Platinum"
  • Either threshold alone → "Gold"
  • Neither → "Standard"

Field Details

  • Object: Account
  • Return type: Text
Approach
  • 1Check the AND() (both-thresholds) case first — it must come before the OR() case or Platinum accounts would incorrectly land in Gold.
  • 2AND(AnnualRevenue >= 10000000, NumberOfEmployees >= 500) is the Platinum condition.
  • 3OR(AnnualRevenue >= 10000000, NumberOfEmployees >= 500) catches the remaining single-threshold accounts for Gold.
Medium Formula Field

19. Formula: Days Since Last Activity (Null-Safe, Whole Number)

Problem #428 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Days_Since_Last_Activity__c on Lead that returns the whole number of days since LastActivityDate. If the Lead has never had any activity (LastActivityDate is blank), return -1 as a sentinel instead of erroring.

Field Details

  • Object: Lead
  • Return type: Number, 0 decimal places
Approach
  • 1Subtracting two Date values (TODAY() - LastActivityDate) already returns a whole number of days — no ROUND() needed.
  • 2ISBLANK(LastActivityDate) must be checked first, since subtracting against a blank Date would otherwise error.
  • 3Return -1 as the sentinel for "no activity yet" so it's clearly distinguishable from 0 ("activity today").
Medium Formula Field

20. Formula: Lead Score Tier Using CASE()

Problem #429 · Salesforce Apex Coding Challenge

Problem Statement

A Lead has a custom Number field Lead_Score__c (0–100). Write a Formula field Score_Tier__c that buckets it into a letter tier using CASE():

  • 80–100 → "A"
  • 50–79 → "B"
  • 20–49 → "C"
  • 0–19 → "D"

Key Technique

CASE() only matches exact values, not ranges — so first derive an integer "bucket" with FLOOR(Lead_Score__c / 20), then CASE() over that whole-number bucket instead of the raw score.

Approach
  • 1CASE() matches exact values only — it cannot test a range like "between 80 and 100" directly.
  • 2FLOOR(Lead_Score__c / 20) turns the 0-100 score into a small integer bucket (0-5) that CASE() can match exactly.
  • 3The final argument to CASE() (with no matching value before it) is the default/else result.
Hard Formula Field

21. Formula: Two-Level Cross-Object Field — Contact's Account Owner Email

Problem #430 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Account_Owner_Email__c on Contact that displays the Email of the User who owns this Contact's parent Account — traversing two relationship levels. Show "No Account Owner" when there's nothing to display (e.g. the Contact has no parent Account).

Field Details

  • Object: Contact
  • Return type: Text

Key Technique

Formula fields can traverse relationships with dot notation just like SOQL: Account.Owner.Email reaches two levels up in a single expression.

Approach
  • 1Account.Owner.Email traverses two relationship levels directly in the formula, the same way SOQL dot notation does.
  • 2ISBLANK(Account.Owner.Email) is true both when there is no parent Account and when the Account somehow has no Owner email.
  • 3Wrap the whole thing in IF() so a missing chain shows a friendly placeholder instead of a blank field.
Medium Formula Field

22. Formula: Use TEXT() to Concatenate a Picklist Value

Problem #431 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Stage_Summary__c on Opportunity that concatenates the Opportunity Name and its StageName picklist into one summary line, e.g. "Acme Renewal - Negotiation/Review".

Key Technique

Picklist fields like StageName cannot be joined with the & concatenation operator directly — attempting Name & StageName is a compile error in a real formula field. Wrap the picklist in TEXT(StageName) first to convert it to a plain string.

Approach
  • 1A picklist field cannot be concatenated with & directly — TEXT(StageName) converts it to a plain string first.
  • 2The full formula is Name & " - " & TEXT(StageName).
  • 3This TEXT() conversion is required specifically because StageName is a picklist, not because of any general text-field rule.
Medium Formula Field

23. Formula: Rounded Weighted Forecast With Blank-Safe Inputs

Problem #432 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Rounded_Forecast__c on Opportunity that computes Amount * (Probability / 100), rounded to 2 decimal places — treating either a blank Amount or blank Probability as 0.

Field Details

  • Object: Opportunity
  • Return type: Currency, 2 decimal places
Approach
  • 1Guard both Amount and Probability with BLANKVALUE(field, 0) before doing any arithmetic.
  • 2ROUND(value, 2) rounds the final result to 2 decimal places.
  • 3The full formula is ROUND(BLANKVALUE(Amount, 0) * (BLANKVALUE(Probability, 0) / 100), 2).
Hard Formula Field

24. Formula: Territory Code From Country and State

Problem #433 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Territory_Code__c on Account that builds a short territory code like "US-CA" by combining BillingCountryCode and BillingStateCode with a hyphen. Show "UNASSIGNED" when either piece is missing.

Field Details

  • Object: Account
  • Return type: Text
Approach
  • 1OR(ISBLANK(BillingCountryCode), ISBLANK(BillingStateCode)) covers either piece being missing.
  • 2BillingCountryCode & "-" & BillingStateCode builds the code once both are guaranteed present.
  • 3Return the fallback "UNASSIGNED" string when the OR() guard is true.
Hard Formula Field

25. Formula: Deal Risk Flag From Stage, Age, and Amount

Problem #434 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field At_Risk__c (Checkbox) on Opportunity that flags a deal as at-risk when all of the following hold:

  • The Opportunity is still open.
  • It's been open more than 90 days (based on CreatedDate).
  • Amount is at least 50,000.

Field Details

  • Object: Opportunity
  • Return type: Checkbox
Approach
  • 1NOT(IsClosed) keeps this limited to still-open deals.
  • 2CreatedDate is a DateTime — subtracting it from TODAY() (a Date) still works in formulas and yields the age in days.
  • 3AND() all three conditions together — every one must hold for the deal to be flagged.
Medium Formula Field

26. Formula: Sales Target Achievement Percentage

Problem #497 · Salesforce Apex Coding Challenge

Problem Statement

An Opportunity has a custom currency field Sales_Target__c representing the owning rep's assigned target for that deal's period. Write a Formula field Target_Achievement_Percent__c that shows what percentage of Sales_Target__c the Opportunity's Amount represents.

Field Details

  • Object: Opportunity
  • Return type: Percent
  • If Sales_Target__c is blank or zero, return 0 instead of dividing by zero.

Functions to Use

  • IF(OR(ISBLANK(...), ... = 0), 0, ...) — guards the division.
  • Division (/) and multiplication by 100 to express the ratio as a percentage.
Approach
  • 1Always guard a formula division with a blank/zero check on the denominator — an unguarded divide-by-zero makes the whole field show #Error!.
  • 2OR(ISBLANK(Sales_Target__c), Sales_Target__c = 0) catches both the "never set" and the "explicitly zero" cases in one check.
  • 3A Percent field type in Salesforce already displays the stored number with a % sign, so the formula itself should return the ratio multiplied by 100, e.g. 0.5 amount/target becomes 50.
Medium Formula Field

27. Formula: Display Discount Percentage From List Price and Sale Price

Problem #498 · Salesforce Apex Coding Challenge

Problem Statement

An OpportunityLineItem has the standard fields ListPrice (from its Pricebook Entry) and UnitPrice (the actual, possibly discounted, price on the line item). Write a Formula field Discount_Percent_Display__c that shows how much the line has been discounted below list price, as a percentage.

Field Details

  • Object: OpportunityLineItem
  • Return type: Percent
  • If ListPrice is blank or zero, return 0 rather than dividing by zero.

Functions to Use

  • IF(OR(ISBLANK(...), ... = 0), 0, ...) to guard the division.
  • (ListPrice - UnitPrice) / ListPrice, scaled by 100, to get the discount percentage.
Approach
  • 1The discount amount is ListPrice - UnitPrice; dividing that by ListPrice gives the discount as a fraction of the original price.
  • 2Guard the division with OR(ISBLANK(ListPrice), ListPrice = 0) so a missing Pricebook Entry price never breaks the field.
  • 3Multiply the final ratio by 100, since the underlying number, not just the field format, should represent the percentage value.
Medium Formula Field

28. Formula: Calculate Gross Profit From Revenue and Cost

Problem #499 · Salesforce Apex Coding Challenge

Problem Statement

An Opportunity has a custom currency field Total_Cost__c tracking the total cost of goods/services for the deal. Write a Formula field Gross_Profit__c that computes Amount minus Total_Cost__c.

Field Details

  • Object: Opportunity
  • Return type: Currency
  • If Total_Cost__c is blank, treat it as 0 so Gross_Profit__c still equals the full Amount.

Functions to Use

  • BLANKVALUE(field, substitute) — returns substitute when field is blank, otherwise the field's own value.
Approach
  • 1BLANKVALUE(Total_Cost__c, 0) is a compact way to substitute 0 for a blank number field, without needing a full IF(ISBLANK(...)) wrapper.
  • 2Subtraction on two Currency-typed values returns a Currency result automatically — no extra conversion function needed.
  • 3This formula does not need any conditional branching beyond the blank guard — keep it as a single subtraction expression.
Medium Formula Field

29. Formula: Display a Human-Readable Quarter Name From Close Date

Problem #500 · Salesforce Apex Coding Challenge

Problem Statement

Write a Formula field Close_Quarter_Label__c on Opportunity that turns the standard CloseDate field into a readable label like "Q3 2026", based on standard calendar quarters (Q1 = Jan–Mar, Q2 = Apr–Jun, Q3 = Jul–Sep, Q4 = Oct–Dec).

Field Details

  • Object: Opportunity
  • Return type: Text
  • Example: a CloseDate of August 15, 2026 should display as "Q3 2026".

Functions to Use

  • MONTH(CloseDate) and CEILING(month / 3) to derive the quarter number (1–4) from the month.
  • CASE() to map the quarter number to its display digit.
  • YEAR(CloseDate) plus TEXT() to turn the year number into a string for concatenation, and & to build the final label.
Approach
  • 1CEILING(MONTH(CloseDate) / 3) turns any month 1-12 into its quarter number 1-4 (e.g. month 8 -> 8/3 = 2.67 -> CEILING -> 3).
  • 2CASE() maps the numeric quarter to the digit you want to display, with a fallback default for safety.
  • 3YEAR(CloseDate) returns a Number — wrap it in TEXT() before concatenating with & , since a Number cannot be directly joined with a String using &.
Expert Formula Field

30. Formula: Renewal Priority Score for Expiring Contracts

Problem #501 · Salesforce Apex Coding Challenge

Problem Statement

A Contract has a custom currency field Monthly_Value__c and a custom checkbox At_Risk__c, plus the standard ContractTerm (months) and EndDate fields. Write a Formula field Renewal_Priority_Score__c that scores how urgently this Contract should be worked for renewal, from 0-100, combining three factors:

  • Value (up to 50 points): total contract value (ContractTerm * Monthly_Value__c) scaled against a $100,000 ceiling — a Contract worth $100,000+ total earns the full 50 points, proportionally less below that.
  • Urgency (up to 40 points): already expired = 40, expiring within 30 days = 35, within 90 days = 20, otherwise = 5.
  • Risk bonus (10 points): a flat 10 points added when At_Risk__c is checked.

Field Details

  • Object: Contract
  • Return type: Number, 0 decimal places

Functions to Use

  • MIN() to cap the value component at 50 points.
  • CASE(TRUE, condition1, result1, condition2, result2, ..., default) — the "CASE on TRUE" pattern for scoring tiered ranges.
  • IF() for the flat risk bonus, and ROUND() to produce a clean whole-number score.
Approach
  • 1MIN(50, valueExpression) is a simple, robust way to cap a scaled score at its maximum points without a full IF/ELSE.
  • 2CASE(TRUE, cond1, result1, cond2, result2, defaultResult) evaluates each condition in order and returns the first true match — a clean way to express tiered scoring bands.
  • 3IF(At_Risk__c, 10, 0) adds a flat bonus directly, since the checkbox is already boolean; wrap the whole sum in ROUND(..., 0) for a clean integer score.
Expert Formula Field

31. Formula: Product Margin Percentage With Cost and Discount Tiers

Problem #502 · Salesforce Apex Coding Challenge

Problem Statement

An OpportunityLineItem has the standard fields TotalPrice (net revenue for the line, i.e. UnitPrice * Quantity) and Quantity, plus a custom currency field Unit_Cost__c (cost per unit). Write a Formula field Margin_Percent__c that computes the true margin percentage: (TotalPrice - TotalCost) / TotalPrice, where TotalCost = Unit_Cost__c * Quantity.

Field Details

  • Object: OpportunityLineItem
  • Return type: Percent, 2 decimal places
  • If TotalPrice is blank or zero, return 0 instead of dividing by zero.
  • If Unit_Cost__c is blank, treat cost as 0 (100% margin on that line) rather than erroring.

Functions to Use

  • BLANKVALUE(Unit_Cost__c, 0) to safely default a missing cost.
  • IF(OR(ISBLANK(...), ... = 0), 0, ...) to guard the division by TotalPrice.
  • ROUND(..., 2) to keep the percentage to two decimal places.
Approach
  • 1Compute TotalCost first as BLANKVALUE(Unit_Cost__c, 0) * Quantity, so a missing per-unit cost never breaks the whole formula.
  • 2Guard the outer division with IF(OR(ISBLANK(TotalPrice), TotalPrice = 0), 0, ...) exactly like any other formula-field division.
  • 3ROUND(value, 2) rounds to two decimal places — apply it to the final percentage, not to any intermediate value.
Master Formula Field

32. Formula: Customer Lifetime Value (CLV) Estimate

Problem #503 · Salesforce Apex Coding Challenge

Problem Statement

An Account has custom fields Avg_Annual_Revenue__c (Currency), Expected_Lifetime_Years__c (Number), and Customer_Tier__c (picklist: Platinum, Gold, Silver, Bronze). Write a Formula field CLV_Estimate__c that estimates Customer Lifetime Value as:

CLV = Avg_Annual_Revenue__c * Expected_Lifetime_Years__c * Retention_Multiplier

where the Retention Multiplier depends on Customer_Tier__c:

  • "Platinum" → 1.5
  • "Gold" → 1.2
  • "Silver" → 1.0
  • anything else (e.g. Bronze, or blank) → 0.8

Field Details

  • Object: Account
  • Return type: Currency, 2 decimal places
  • A blank Avg_Annual_Revenue__c or Expected_Lifetime_Years__c should contribute 0 to the product rather than causing an error.

Functions to Use

  • BLANKVALUE(field, 0) to safely default the two numeric inputs.
  • CASE(Customer_Tier__c, "Platinum", 1.5, "Gold", 1.2, "Silver", 1.0, 0.8)CASE() works directly on a picklist's text value without needing ISPICKVAL(), since it is comparing against literal string labels.
  • ROUND(..., 2) for a clean currency amount.
Approach
  • 1BLANKVALUE(Avg_Annual_Revenue__c, 0) and BLANKVALUE(Expected_Lifetime_Years__c, 0) keep a blank numeric input from breaking the whole multiplication.
  • 2CASE(Customer_Tier__c, "Platinum", 1.5, "Gold", 1.2, "Silver", 1.0, 0.8) maps the picklist's text value straight to a multiplier, with 0.8 as the default for Bronze or anything unmatched.
  • 3Multiply all three factors together, then wrap the whole expression in ROUND(..., 2) for a clean currency value.

Practice All 32 Problems Free

Write and run real Apex code right in your browser — instant pass/fail feedback, best-practice linting, and governor limit monitoring. No Salesforce org needed.

Create Free Account → Explore All Problems
More Practice Topics
About ApexArena

ApexArena is a free, browser-based Salesforce Apex coding practice platform covering every major topic tested on the Salesforce Platform Developer I (PD1) and Platform Developer II (PD2) certification exams. All problems run directly in your browser with instant pass/fail feedback, best-practice linting (SOQL in loops, DML in loops, empty catch blocks), and governor limit monitoring — no Salesforce Developer Edition org required.

Related tutorials: Apex Triggers · SOQL · Batch Apex · Interview Q&A · Governor Limits