I am trying to query records (of a custom object) that were created by the current logged in user.

I am trying to use the Created By field to check this. However I can't figure out what the field really is or how to compare it. If I get the record thusly:

SELECT id, Name, CreatedById '+'FROM Reservation__c 

And then display this in a VF page I get a first name last name format with a link. I know that is listed as a lookup field, but is there a way to get the id number?

But on the same page if I use this VF markup:

Hello ID {! $User.Id }

I get an 18 digit user ID.

How can I get a CreatedBy ID that I can compare to the current user ID in Apex code?

  • 2
    It's an ID, but it can also be understood as a String
    – EricSSH
    Feb 24, 2016 at 22:26

1 Answer 1


CreatedById is an Id field just as Id is, so you can compare the two very simply.

To query records created by the current logged in user:

[SELECT Id, Name, CreatedById FROM Reservation__c WHERE CreatedById = :UserInfo.getUserId()];


Database.query('SELECT Id, Name, CreatedById FROM Reservation__c WHERE CreatedById = \'' + UserInfo.getUserId() + '\'');

... with all lookup and master-detail fields, the field itself (when queried) is an Id. Salesforce's UI recognizes that it's a reference and instead displays the corresponding record's Name field.

Standard fields toggle the Id demarcation at the end:

Id = CreatedById

Name = CreatedBy.Name

Custom fields toggle the __c for __r at the end:

Id = ParentRecord__c

Name = ParentRecord__r.Name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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