In this article you will learn how to get List of all present and deleted records from salesforce object using apex query. Following code will retrieves deleted and present records from Account object.
List records = [SELECT Id from Account ALL ROWS];
ALL ROWS keyword in a SOQL query retrieves all the records from the database, including those that have been deleted.
The following code will return only deleted records from Account object.
List deletedRec = [SELECT Id from Account where isDeleted = true ALL ROWS];
Check out how to write a Trigger to permanently delete a record using emptyRecycleBin.
How ALL ROWS works
A normal SOQL query skips deleted records. Adding ALL ROWS at the end tells Salesforce to include records that are in the Recycle Bin, and records that are archived, such as old Tasks and Events. Each record has an IsDeleted field, which is true for a deleted record.
More examples
// Count the deleted Accounts
Integer deletedCount = [SELECT COUNT() FROM Account WHERE IsDeleted = true ALL ROWS];
// Restore them
List<Account> deleted = [SELECT Id FROM Account WHERE IsDeleted = true ALL ROWS];
undelete deleted;
Points to note
Deleted records stay in the Recycle Bin for 15 days. After that they are removed, and ALL ROWS cannot find them.
ALL ROWS is used in Apex. In the API, the call that does the same thing is queryAll.
Records deleted with Hard Delete or emptied from the Recycle Bin do not come back in these queries.
FAQ
Can I filter by who deleted a record? Not with this query. The Recycle Bin page shows who deleted each record and when.
Does undelete bring back the child records? Children deleted along with the parent are restored with it in most cases. Check the records after the undelete.