I need select the Email off the most recently created Contact for all of my Accounts to export via the Data Loader. So far I have this but then I'm stuck. I keep thinking of functions like MAX(CreatedDate) but how the might help me just isn't turning on a light bulb, any ideas?

SELECT Email from Contact where Account in (Select Id from Account) Order By CreatedDate
  • Does select top works in Dataloader?
    – Saariko
    Nov 8, 2012 at 6:38
  • 1
    As in: SELECT TOP 5 Email From Contact? No, but could do this: SELECT Email from Contact limit 5 Nov 8, 2012 at 15:17

1 Answer 1

List <Account> accounts = [SELECT Id, (SELECT Email FROM Contacts ORDER BY CreatedDate DESC LIMIT 1) FROM Account];

Then you can use:

for(Account acc : accounts)
    if(acc.Contacts.size() > 0)
        String accountEmail = acc.Contacts[0].Email;
        // do whatever you need to do with the email...
  • I should have clarified, I need to do this for the dataloader and not in APEX, so I can't have nested queries in the select clause. Nov 8, 2012 at 4:58
  • 2
    That approach would work on workbench.developerforce.com (just the query that is, you might also be able to export the results as CSV from there) Nov 8, 2012 at 7:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .