21

Can anyone confirm this: in a SOQL Where clause, when comparing an ID field to a 15-character string variable, the comparison works.

I didn't expect it to work, but it does and I am surprised. I can't find any documentation to confirm it. I thought 18-character ID was always in effect, and comparing 18-char ID to 15-char string would fail.

Example (Country__c is a lookup field):

String tmpID = 'a1he0000000EkAi';
Account acct = [select ID from Account where Country__c = :tmpID];
13

SOQL always accepts 15- and 18-character Id values. You can test this in any program-- data loader, excel connector, Apex Code. The system does this for compatibility with older code that may only use 15-character Id values. Apex Code specifically tries to cast a string to an Id automatically when used as a value on a field that expects an Id. It also tries to convert a string to an Id automatically if either operand in a comparison operation is an Id.

16

Any valid 18-character Force.com record identifier.
For example: ID id='00300000003T2PGAA0';

Note that if you set ID to a 15-character value, Apex automatically converts the value to its 18-character representation. All invalid ID values are rejected with a runtime exception.

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_primitives.htm

  • Change from "String tmpID" to "Id tmpID" – Nathan Williams Oct 12 '13 at 14:45
11

This comparison actually uses the Id class. This means that it really isn't doing a String comparison, but rather a comparison of those two objects. The Id class will actually take into account the size of the Id (15 or 18) and ensure when it is compared with another Id that both are the same type.

In short, it doesn't matter if you pass 15 or 18 length Ids. When compared, it takes that into consideration and adjusts accordingly.

  • 1
    Good point. Take advantage of the Id class and change from "String tmpID" to "Id tmpID" – Nathan Williams Oct 12 '13 at 14:46
  • 2
    I think the point is that Apex is smart enough to cast a String into an Id on the fly when necessary, so it's not strictly required to explicitly do this in your code. – Jeremy Nottingham Oct 16 '13 at 21:21
5

The 3 character difference between a 15 and 18 character Id is only to make them case insensitive. So if the first 15 characters are the same (including casing) they are considered the same Id. See What are Salesforce ID's composed of?

Hence it makes sense that SOQL allows you to use them interchangeably for equality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.