function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shreya Singh 36Shreya Singh 36 

I want to find ID and name for all accounts whose industry is media, and when each account is being returned, I want it to return the last name of every contact whose created-by its alias by 'x.'

Arun Kumar 1141Arun Kumar 1141
Hi Shreya,

To complete the same task, use this code.
 
List accList = [Select Id, Name, (SELECT lastname from contacts where createdBy.alias='x') from account where industry='media' ];

system.debug(accList);

Please mark it as best answer if it helps you

Thanks
SubratSubrat (Salesforce Developers) 
Hello Shreya ,

To fetch the ID and name for all accounts in the "Media" industry and retrieve the last name of every contact whose created by alias is 'x', you can use the following SOQL query:
SELECT Id, Name, (SELECT LastName FROM Contacts WHERE CreatedBy.Alias = 'x' ORDER BY CreatedDate DESC LIMIT 1)
FROM Account
WHERE Industry = 'Media'

This query uses a subquery to fetch the last name of the contacts associated with each account. The subquery filters the contacts based on their CreatedBy field's alias value being 'x' and retrieves only the most recently created contact using ORDER BY CreatedDate DESC LIMIT 1.

Hope this helps !
Thank you.