Sub topic 18
Seeing Field Types in Apex, SOQL and Metadata
This chapter assumes you can open Developer Console or the Salesforce CLI and run anonymous Apex. It also assumes you know the field types from the earlier chapters. Here you learn to read a field's type from code and metadata instead of from the page layout. That matters because the UI can hide the real type. A Formula (Currency) field looks like a Currency field on a record page, but code treats it differently.
Three places to read a type
Each view answers a different question:
- Apex describe reports how the platform sees a field at runtime.
- SOQL shows how the type changes what you can filter, sort and aggregate.
- Metadata is the stored definition. It is the only view that distinguishes every setting, such as Lookup versus Master-Detail.
Reading types with Apex describe
Every field token, such as Account.AnnualRevenue, has a getDescribe() method. It returns a DescribeFieldResult, and its getType() method returns a Schema.DisplayType value.
Schema.DescribeFieldResult revenue = Account.AnnualRevenue.getDescribe();
System.debug(revenue.getType()); // CURRENCY
Schema.DescribeFieldResult accountType = Account.Type.getDescribe();
System.debug(accountType.getType()); // PICKLISTTo inspect a whole object, loop over the field map. The keys in the map are lowercase API names.
Map<String, Schema.SObjectField> fields = Schema.SObjectType.Opportunity.fields.getMap();
for (String apiName : fields.keySet()) {
Schema.DescribeFieldResult d = fields.get(apiName).getDescribe();
System.debug(d.getName() + ' | ' + d.getType()
+ ' | calculated=' + d.isCalculated()
+ ' | custom=' + d.isCustom());
}Describe returns a display type, not the label you picked in Setup. Several Setup types share one display type, and a few settings are visible only through other methods.
| Setup type | `getType()` result | Extra detail to check |
|---|---|---|
| Text | STRING | `getLength()` |
| Auto Number | STRING | `isAutoNumber()` is true |
| Text Area, Long Text Area | TEXTAREA | `getLength()` is above 255 for long text |
| Rich Text Area | TEXTAREA | `isHtmlFormatted()` is true |
| Number | DOUBLE | `getPrecision()`, `getScale()` |
| Currency, Percent | CURRENCY, PERCENT | `getScale()` |
| Checkbox | BOOLEAN | none |
| Date, Date/Time, Time | DATE, DATETIME, TIME | none |
| Picklist, Multi-select | PICKLIST, MULTIPICKLIST | `getPicklistValues()` |
| Email, Phone, URL | EMAIL, PHONE, URL | none |
| Lookup, Master-Detail | REFERENCE | `getReferenceTo()` |
| Geolocation | LOCATION | compound field |
| Formula, Roll-up Summary | The return type | `isCalculated()` is true |
Two patterns in the table matter in practice:
- A formula or roll-up summary field reports its result type, so its type name hides the fact that it is read-only. Check
isCalculated()before you write code that sets the field. - Lookup and master-detail fields both report REFERENCE. If you need to tell them apart, read the metadata.
What the type means in SOQL
Once you know the type, SOQL tells you which operations are allowed.
Multi-select picklists have their own operators. INCLUDES matches records that have the listed values selected. A semicolon inside one string means both values must be selected. Separate strings mean either option is enough.
SELECT Id, Name FROM Contact WHERE Interests__c INCLUDES ('Golf;Tennis', 'Chess')This query returns contacts who selected both Golf and Tennis, and also contacts who selected Chess. The query assumes a custom multi-select picklist named Interests__c on Contact. A plain = comparison on a multi-select works only for an exact, ordered match of the whole stored string, so use INCLUDES and EXCLUDES instead.
Other type-driven rules to remember:
- Long Text Area and Rich Text Area fields cannot appear in a
WHEREclause, anORDER BYclause or aGROUP BYclause. - Picklists sort by the order of the values in the picklist definition, not alphabetically. Use
toLabel(Field)to return the translated label. - Geolocation is a compound field. You query its parts as
Location__Latitude__sandLocation__Longitude__s, and you filter withDISTANCE()andGEOLOCATION(). - Encrypted fields allow only limited filtering, because the stored value is not plain text.
- Formula fields can be queried and filtered, but they cannot be written. Filtering on one that is not deterministic or not indexed can be slow on large objects.
Replacing a roll-up with an aggregate query
Roll-up summary fields need a master-detail relationship. When the relationship is a lookup, an aggregate query computes the same total in code.
List<AggregateResult> totals = [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE AccountId != null
GROUP BY AccountId
];
for (AggregateResult ar : totals) {
System.debug(ar.get('AccountId') + ': ' + ar.get('total'));
}Aggregate results are untyped. ar.get('total') returns an Object, which holds a Decimal here. Cast it before you do arithmetic. Unlike a roll-up field, this total is calculated when you run the query, so you must store or cache it yourself if other features need it.
Reading types in metadata
In Metadata API format, each custom field is a CustomField file. The type element holds the field type. The other elements depend on that type. Here is a Number field:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Priority_Score__c</fullName>
<label>Priority Score</label>
<type>Number</type>
<precision>5</precision>
<scale>2</scale>
<required>false</required>
</CustomField>Here precision is the total number of digits and scale is how many of them come after the decimal point. This field stores values up to 999.99. This is the same pair of numbers that Apex returns from getPrecision() and getScale().
Other types use different child elements. For example, a Text field has length, a Picklist has valueSet, a Lookup has referenceTo and relationshipName, and a Roll-up Summary has summaryOperation, summarizedField and summaryForeignKey. A Lookup is <type>Lookup</type>, while a master-detail field is <type>MasterDetail</type>.
A formula field uses the return type as its type and adds a formula element. Here is the formula from the Opportunity example in the formula chapter:
IF(ISPICKVAL(StageName, "Closed Won"), Amount, 0)In metadata, this field would have <type>Currency</type> and this expression inside <formula>. ISPICKVAL is needed because you cannot compare a picklist value with a plain equals sign.
Common errors
- Assuming REFERENCE means lookup. Master-detail fields also report REFERENCE. Use metadata to check the relationship type.
- Trusting the UI label. Apex and SOQL see the underlying type. Auto Number appears as STRING, and a formula appears as its return type.
- Writing to calculated fields. An attempt to set a formula or roll-up value in Apex fails at compile time or on save. Check
isCalculated()first. - Using
=on multi-select values. The comparison matches only the exact stored string. UseINCLUDESorEXCLUDES. - Ignoring precision and scale in code. A Number field with precision 5 and scale 2 rejects a value like
1234.5, because it has four digits before the decimal point and only three are allowed.
Exercise
A Contact field named Score_c shows as a plain number on the page layout, and `Contact.Score_c.getDescribe().isCalculated()` returns true. What does that tell you about the field, and what should your Apex code not do with it?
Show answer
The field is a formula field, or possibly a roll-up summary field, so its value is computed by the platform and not entered by users. Apex can read it and filter on it in SOQL, but code must not try to assign a value to it, because the save fails. To see the exact return type and formula, retrieve its metadata and read the type and formula elements.