Full List of Data Types In Salesforce Apex

Full List of Data Types In Salesforce Apex

On January 4, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Full List of Data Types In Salesforce Apex
Data types in Salesforce Apex

Table of Contents

What are data types?

A data type in programming specifies the kind of data a variable can hold, such as numbers, text, or complex structures, defining its operations and storage. A data type is like a label for data, telling the computer what kind of information (like numbers or letters) it is and how to use it. A data type in programming is like a category for information. It tells the computer what kind of data it’s dealing with and how it can be used. For example, if you have a data type called “number,” you can do math with it, like adding or subtracting. If you have a data type called “text” (often referred to as “string”), it’s like a word or sentence, and you can do things like find the length of the word or combine it with other words.

Check out these top Salesforce interview questions and answers for extensive knowledge and informative details about Salesforce Admin, Developer, Integration, and LWC modules.

What are the data types available in Salesforce Apex?

Here is a list of data types supported by Apex:

In Salesforce Apex, data types are used to define the kind of data a variable can hold. Apex is a strongly-typed language, meaning that the data type of a variable is checked during compile time. The data types in Apex can be broadly categorized into Primitive, sObject, Collection, and Enum. Here’s a brief overview of each:

Read more: Variables in Salesforce Apex

CRS Info Solutions offers a comprehensive and dynamic Salesforce training career building program for beginners, covering admin, developer, and LWC concepts.

Primitive Data Types:

  • Boolean: Represents true or false values.
  • Integer: Represents a 32-bit number without a decimal point.
  • Long: Represents a 64-bit number without a decimal point.
  • Decimal: Represents a 64-bit number with a decimal point. It’s used for precise calculations, like currency.
  • Double: Represents a 64-bit number with a decimal point. It’s similar to Decimal but has double precision.
  • Date: Represents a date value, consisting of a day, month, and year.
  • Datetime: Represents a specific date and time, including time zone.
  • Time: Represents a specific time, without a date.
  • String: Represents a sequence of characters, like words or sentences.
  • ID: Represents a Salesforce record’s unique identifier.
  • Blob: Represents binary data, used for storing files or images.

Read more: Strings in Salesforce Apex

sObject Data Types:

Represent any object that can be stored in the Salesforce platform database. This includes standard objects like Account, Contact, Lead, Opportunity, and custom objects.

Collection Data Types:

List (or Array): An ordered collection of elements that can contain duplicates.

Set: An unordered collection of elements that does not contain duplicates.

Map: A collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, and values can be any type.

Enum (Enumerated) Data Types:

Represents a set of named constants. Enums are used when a variable can only take one out of a small set of possible values.

Let’s discuss the Primitive data types, sObject, and enums in detail.

Read more: Arrays in Salesforce Apex

Primitive Data Types


The Integer data type in Apex is designed to store whole numbers, ranging from negative to positive values, without any decimal points. It’s a 32-bit number commonly used for counting or iterating in loops. Its value ranges between -2,147,483,648 and 2,147,483,647.

Example of Integer Data Type: Imagine a scenario in an e-commerce application where the system needs to track the number of items in a shopping cart. An Integer variable, itemCount , can be utilized for this purpose. As users add or remove items from their cart, itemCount is updated to reflect the current total.
For example1:
Integer itemCount = 3;
itemCount = itemCount + 2; // Adding 2 more items


Readmore: Record Types in Salesforce

Integer quantity = 100;
System.debug(‘The value of the quantity variable is: ’+quantity);

The system.debug statement prints the value of the quantity variable.

Collection is one of the important concept, checkout: Collections in Salesforce Apex


A boolean variable can only be assigned a true, false, or null value. A boolean variable is used in control statements to determine the flow of a program. It’s commonly utilized in decision-making structures to control the flow of code execution.
Example of Boolean Data Type: Consider a scenario where an application needs to verify if a user is eligible for a discount. A Boolean variable, isDiscountApplicable , can be used to store this information. If certain conditions are met, such as the user having a membership, isDiscountApplicable would be set to true , indicating eligibility for the discount.
Example 1:

Boolean isDiscountApplicable = (userMembershipStatus == 'Active');

Example 2:

Boolean isCheck= true;

In the above statement, we have declared the isCheck variable and initialized it to true.

Read more: Database methods – Salesforce Apex


A variable of date datatype is used to store a date. A date variable doesn’t have any information about time. A DateTime variable can be used to store time along with the date. In Apex, the Date data type is specifically used to represent dates, holding information about the day, month, and year. It’s perfect for scenarios where you need to work with dates, perform calculations, or compare different dates without the time component being a factor.

Example of Date Data Type: Imagine I’m creating a project management tool where I need to track project deadlines. I’d use a Date variable, projectDeadline , to store this information. For example:

Date projectStart = Date.newInstance(2024, 1, 1); Date projectDeadline = projectStart.addDays(30); // Setting the project deadline 30 days from the start date

In this situation, I set the projectDeadline to 30 days after the project’s start date. The Date data type ensures that I’m accurately handling and manipulating the dates for the project timeline.

Date deliveryDate= system.today();

Read more: Constants – Salesforce Apex


In Apex, the Long data type is used for storing large whole numbers. It’s a 64-bit number, providing a wider range than Integer for scenarios requiring the representation of very large or small values without decimal precision.

Example of Long Data Type: Let’s say I’m working on a financial application where I need to handle large transaction amounts in cents to avoid floating point errors. I’d use a Long variable, totalTransactionAmountInCents , to store these values.

For instance:
Long totalTransactionAmountInCents = 2500000000L; totalTransactionAmountInCents = totalTransactionAmountInCents + 100000000L; // Adding 1,000,000 cents
Here, I initially have 2,500,000,000 cents, and after adding 1,000,000 more cents, totalTransactionAmountInCents reflects the new total.

Long turnOver= 21474838973344648L;

Read more: Decision Making in Salesforce Apex

Decimal Data Type:

The Decimal data type in Apex is used for numbers that require high precision, such as financial calculations or measurements. It’s a 64-bit number and is particularly useful when you need accuracy for numbers with decimal points.

Example of Decimal Data Type: Let’s say I’m developing a billing system where precise calculations are crucial. I’d use a Decimal variable, itemPrice , to store the price of each item.

For example:

Decimal itemPrice = 19.99; Decimal taxRate = 0.08; 
Decimal totalPrice = itemPrice + (itemPrice * taxRate); // Calculating total price including tax

In this case, I calculate the total price by adding the item price and the tax. The Decimal data type ensures that the calculations are precise.

Double Data Type:

In Apex, the Double data type is ideal for numbers that require a large range and can have decimal points. It’s a 64-bit number, similar to Decimal, but it’s more suitable for scientific calculations or when you’re dealing with very large or very small numbers and precision is less critical compared to Decimal.

Readmore: Validation Rules in Salesforce

Example of Double Data Type: Suppose I’m working on an astronomy application where I need to handle astronomical distances. I’d use a Double variable, distanceToStars , to store these massive values.

For instance:

Double distanceToStars = 4.22; // Distance to the nearest star in light-years 
Double speedOfLight = 299792.458; // Speed of light in km/s 
Double timeInYears = distanceToStars / speedOfLight; // Calculating time in years

Here, I calculate the time it takes for light to travel from the nearest star to Earth, using Double to handle the vast distances and speeds involved.

Read more: Loops in Salesforce Apex

Time Data Type:

The Time data type in Apex is tailored for situations where only the time of day matters, independent of any specific date. It’s ideal for tracking daily routines, store hours, or any scenario where the focus is solely on the time, not the date.

Example of Time Data Type: Let’s say I’m setting up a scheduler for daily reminders in an application. I’d use a Time variable, reminderTime , to consistently trigger reminders at a specific time each day.

For instance:

Time reminderTime = Time.newInstance(14, 30, 0, 0); // 2:30 PM 
System.debug('Daily reminder set for: ' + reminderTime);

In this scenario, reminderTime is set to 2:30 PM, utilizing the Time data type to ensure the reminder triggers at the exact same time every day, independent of the date.

Read more: Classes in Salesforce Apex


Enum Data Type: In Apex, the Enum data type is a special construct used to define a collection of constants, providing a clear and concise way to represent a fixed set of values. Enums are great for enhancing code readability and ensuring values are restricted to predefined options, reducing errors and simplifying decision-making processes in code.

Example of Enum Data Type: When I’m coding the status levels for a ticketing system in my Salesforce app, I use an Enum to represent the possible states.

For instance:

public Enum TicketStatus { NEW, OPEN, PENDING, RESOLVED, CLOSED }TicketStatus currentStatus = TicketStatus.NEW;

Here, currentStatus holds a value from the predefined set of statuses in TicketStatus , ensuring consistency and clarity in tracking the lifecycle of a ticket.

public enum CompassDirection{North, South, East,West}
CompassDirection obj = CompassDirection.East;

Read more: Objects in Salesforce Apex

String Data Type:

The String data type in Apex is used to handle text. It can store anything from a single character to a lengthy paragraph, making it incredibly versatile for holding names, addresses, or any other textual information that an application might need to process or display.

Example of String Data Type: If I’m developing a customer management system, I’d use a String variable, customerName , to store a customer’s full name.

For instance:

String customerName = 'Jane Doe';
System.debug('Processing information for customer: ' + customerName);

Here, customerName holds the text ‘Jane Doe’. Using the String data type allows me to easily manage and manipulate text-based data like customer names in the system.

ID Data Type:

In Apex, the ID data type uniquely identifies Salesforce records. It’s crucial for associating data with specific records, such as accounts, contacts, or custom objects. Each ID is unique, ensuring precise identification and secure handling of Salesforce records within the platform.

Example of ID Data Type: When I’m coding a function to update contact information, I use an ID variable, contactId , to pinpoint the exact contact record.

For example:

ID contactId = '0031N00001bXkQ9QAK';
Contact contactRecord = [SELECT Name, Email FROM Contact WHERE Id = :contactId];

In this snippet, contactId uniquely identifies a contact record, allowing my code to fetch and interact with the correct data securely and efficiently.

Readmore: Custom Page Layouts in Salesforce

Blob Data Type:

In Apex, the Blob data type is utilized to store binary data, which can be anything from file content to images. It’s especially handy when you need to handle complex data that doesn’t fit traditional text or numerical types, ensuring versatility and robustness in data management within Salesforce.

Example of Blob Data Type:

Suppose I’m creating a feature to handle file uploads in a Salesforce application. I’d use a Blob variable, fileContent , to store the binary data of the uploaded file.

For instance:

Blob fileContent = Blob.valueOf('Hello, this is a sample file content.'); 
Attachment fileAttachment = new Attachment(Body = fileContent, Name = 'SampleFile.txt'); 
insert fileAttachment;

In this scenario, fileContent holds the binary content of a file, allowing me to manage and store it as an attachment in Salesforce efficiently and securely.

Checkout: Interfaces in Salesforce Apex

sObject Data Type:

In Apex, the sObject data type represents Salesforce objects, both standard and custom. It’s a versatile data type used to interact with any record in Salesforce, encompassing fields, relationships, and metadata. sObjects are fundamental for CRUD operations, enabling robust data management and manipulation.

Example of sObject Data Type: When I’m working with account records in a Salesforce application, I use the sObject data type to represent these records.

For instance:

Readmore: Record Types in Salesforce

Account myAccount = new Account(Name='Acme Corporation', Industry='Technology'); insert myAccount;

Here, myAccount is an sObject variable representing an Account record. Using sObject allows me to create, query, and manipulate Salesforce records efficiently, making it an essential tool in my Apex development toolkit.

//Declaring a sObject variable of type contact
Contact contact = new Contact();//Assignment of values to the contact fields
contact.FirstName =Test;
contact.LastName =Name;

Readmore: Decision Making in Salesforce Apex

Collection Data Types:

In Apex, Collection data types include Lists, Sets, and Maps. These are powerful structures for storing and organizing data efficiently. Lists maintain an ordered collection of elements, Sets ensure unique elements, and Maps hold key-value pairs, allowing for fast retrieval based on keys.

Example of Collection Data Types: When managing a set of customer names in my Salesforce app, I use a List for ordered storage, a Set to avoid duplicates, and a Map for quick access. For instance:

List<String> customerNames = new List<String>{'Alice', 'Bob'}; 
Set<String> uniqueCustomerNames = new Set<String>{'Alice', 'Bob'}; 
Map<Id, String> customerIdToName = new Map<Id, String>{'001xx000003NG5qAAG' => 'Alice'};

Readmore: Permission Sets in Salesforce

Set Data Type:

In Apex, the Set data type is a collection that stores unique elements, preventing any duplicates. It’s incredibly useful when you need to ensure that each element appears only once, regardless of the order. Sets are often used for filtering and fast existence checks, thanks to their efficient data handling.

Example of Set Data Type: When I need to track unique customer IDs in my Salesforce app to avoid processing duplicates, I use a Set.

For instance:

Set<Id> uniqueCustomerIds = new Set<Id>(); 
uniqueCustomerIds.add('001xx000003NG5qAAG'); // This won't be added again

Here, uniqueCustomerIds ensures that each customer ID is stored only once, making my data processing more efficient and reliable.

Map Data Type:

In Apex, the Map data type is a collection that associates unique keys with individual values. It’s extremely efficient for retrieving values when you know the key, making it ideal for situations where quick access and data association are crucial. Maps are frequently used for relationship handling and data structuring in complex applications.

Example of Map Data Type: When I’m handling product inventory in my Salesforce app, I use a Map to link product IDs with their stock counts.

For instance:

Map productStockCount = new Map();
productStockCount.put('a045000000XtXYZ', 150);
productStockCount.put('a045000000XtXYZ', 120); // Updates the stock count

Readmore: Role in Salesforce

In this example, productStockCount efficiently keeps track of each product’s stock, allowing me to quickly update or retrieve the stock count based on the product ID.

Read more: Constants in Salesforce Apex

Top 5 Interview questions on Salesforce Apex Data types for beginners

Can you explain what primitive data types are in Apex and give an example of how and when you might use each type?

In Apex, understanding and effectively using primitive data types is fundamental to writing efficient and reliable code. These types include Integer, Boolean, String, among others, each tailored for specific kinds of data. For example, I use Integers for numerical operations that don’t require decimals, perfect for scenarios like counting loop iterations or managing quantities. The Boolean data type is my go-to when I need to control the flow of my program based on certain conditions, as it can only hold true or false values. For textual data, such as user names or messages, I rely on the String data type because of its flexibility and ease of use in various operations like concatenation or comparison.

Readmore: Data Loader Management in Salesforce

When precision is critical, especially in scenarios like financial calculations, I prefer using the Decimal data type to avoid the common pitfalls of floating-point arithmetic, ensuring accuracy down to the last decimal. Each primitive data type in Apex has its purpose and understanding when and how to use each type is key to writing clean, efficient, and bug-free code. As a developer, I find that having a solid grasp of these data types allows me to implement solutions that are not only effective but also scalable and maintainable.

Read more: What is Apex?

How do you choose between using a List, a Set, or a Map in Apex, and what are the key differences between these collection types?

Choosing the right collection type in Apex, whether it’s a List, a Set, or a Map, is crucial for writing efficient and readable code. When I need to maintain an ordered collection of elements and possibly contain duplicates, I go for a List. It’s incredibly handy when the sequence matters, like when I’m processing records in a specific order or when I need to access elements by their index. Sets are my choice when I need to ensure uniqueness among the elements, as it automatically filters out any duplicates. This is especially useful when I’m dealing with large datasets and need to prevent processing the same record more than once, enhancing the performance by avoiding unnecessary operations.

Readmore: Classic Email Templates in Salesforce

Maps are particularly powerful when I need to establish a one-to-one relationship between a unique key and its corresponding value. They enable me to quickly retrieve data without needing to iterate through the entire collection, significantly optimizing performance. For instance, when I’m working with a large set of data and need to retrieve specific records based on a unique identifier, a Map makes it incredibly efficient. The key aspect is to understand the nature of the data and the operations I need to perform. By carefully choosing the appropriate collection type, I can ensure my code is not only efficient but also clear and maintainable, making it easier for others (and future me) to understand and work with.

What is an sObject in Apex, and how does it differ from primitive data types?

In Apex, sObjects are quite special, and understanding them is key to effectively working with Salesforce’s data model. An sObject can represent any record in Salesforce, whether it’s a standard object like Account or Contact, or a custom object unique to a specific organization. These sObjects are more than just primitive data types; they’re complex structures that encapsulate fields, relationships, and record data. For instance, when I’m working on automating a sales process, I use sObjects to interact with Account or Opportunity records, allowing me to read and manipulate the data just like I would interact with a complex data structure in traditional programming.

Readmore: Approval Process in Saleforce

What makes sObjects really stand out is their dynamic nature. Unlike primitive data types that represent singular values like numbers or strings, an sObject can hold a wealth of information, similar to a row in a database table. Each field of an sObject can be thought of as a column in the table, holding specific attributes about the record. This structure is incredibly powerful in Salesforce development, as it allows me to not only access and manipulate data in a straightforward manner but also leverage Salesforce’s robust data security model. Whether I’m querying data, updating records, or creating new ones, working with sObjects ensures that I’m interacting with Salesforce data in a way that’s both efficient and aligned with best practices.

Readmore: Security in Salesforce Apex

In Apex, what is an Enum, and can you provide a scenario where using an Enum would be advantageous?

In Apex, Enums, short for Enumerated types, are a game-changer when it comes to enhancing code clarity and ensuring consistency. Enums allow me to define a set of named constants, making my code more readable and less error-prone. For instance, when I’m dealing with a set of predefined categories or statuses in an application, such as order statuses (Pending, Shipped, Delivered), using Enums ensures that only valid values are used throughout the code. This not only makes the code self-documenting but also significantly reduces the risk of typos or invalid values, as the compiler can check for errors at compile time.

Readmore: Relationship Fields in Salesforce.

The beauty of using Enums in Apex is the clarity it brings to the decision-making structures in my code. Instead of relying on hard-coded string or integer values, Enums make the code more intuitive. For example, when I implement business logic that varies based on a record’s status, using Enums allows me to write switch statements or conditional logic that is easy to understand and maintain. The ability to iterate over the values of an Enum or retrieve the name of a specific Enum value further enhances the flexibility and power of my code. In essence, Enums in Apex help me write code that is not only robust and less prone to errors but also a lot more aligned with the business logic it represents.

Can you describe a situation where you would use a Long data type instead of an Integer, and why?

When I’m developing in Apex and faced with the choice between using a Long or an Integer data type, my decision hinges on the range of values I expect to handle. Integer, being a 32-bit number, is suitable for most scenarios where the numbers aren’t exceedingly large. It’s my go-to for indexing, counting, or any other operation where the numbers stay within a reasonable range. However, when I anticipate the numbers to exceed the capacity of Integer, that’s when I lean towards using a Long. This 64-bit data type can handle much larger numbers, making it ideal for situations where the Integer’s limit might be a constraint, like processing high-volume data or dealing with system-generated unique identifiers that require a broader range.

Choosing the right data type is crucial for not just ensuring the accuracy of my computations but also for optimizing the performance of the application. Using a Long when an Integer would suffice could lead to unnecessary consumption of resources, while opting for an Integer when the numbers could exceed its limit risks data overflow and inaccuracies. That’s why, when I’m in doubt or expect large numerical values, I prefer the safety net that Long provides. It’s about striking the right balance based on the application’s requirements, ensuring the data is handled efficiently, accurately, and effectively.

Readmore: Arrays in Salesforce Apex

You can read the previous article Salesforce Apex Tutorial – Chapter 3: Apex Examples and next article Salesforce Apex Tutorial – Chapter 5: Apex Variables.

Kick start your Salesforce learning, Explore our Salesforce training in Bangalore.

Comments are closed.