Interview Question: In my Salesforce org, I have Contact records where some share the exact same name. If I run a query filtering by name, which record will be returned first?
Select Id,Name, CreatedDate,OtherPhone From Contact Where Name= 'Billi Jonh'
What will be result of above SOQL?
The order of this query results is not guaranteed. It could vary depending on internal indexing, query optimization.
By default, Salesforce SOQL does not guarantee any specific order of records unless you explicitly use an ORDER BY clause.
A SOQL query without ORDER BY has no fixed order. The database may return records in the order of an index, the order they were stored, or any other order that is cheap for it. The order can change between runs, between orgs and as data grows. Never write code that depends on it.
How to get a predictable result
SELECT Id, Name, CreatedDate, OtherPhone
FROM Contact
WHERE Name = 'Billi Jonh'
ORDER BY CreatedDate ASC, Id ASC
LIMIT 1
ORDER BY CreatedDate returns the oldest record first. Adding Id as a second sort field breaks ties when two records have the same timestamp. LIMIT 1 keeps only the first row.
Finding duplicates
SELECT Name, COUNT(Id) total
FROM Contact
GROUP BY Name
HAVING COUNT(Id) > 1
This query lists every name that appears more than once, with the number of records.
How to answer in an interview
Say that the order is not guaranteed without ORDER BY, give the reason, and show that you would add ORDER BY with a tie-breaker. Mention that a filter on Name with several matches usually points to a data quality issue, which you can solve with duplicate rules.
FAQ
Does the default order follow CreatedDate? It often looks that way, but you cannot rely on it.
Can I order by several fields? Yes. Separate them with commas and add ASC or DESC to each.