Loading

Salesforce Apex Error: 'System.ListException: Duplicate id in list'

Udgivelsesdato: Jun 2, 2026
Beskrivelse

In Salesforce Apex, a List can store duplicate values, including duplicate sObject IDs. However, if you attempt to perform a DML (Data Manipulation Language) operation — such as update or delete — on a List that contains sObjects with duplicate IDs, the platform throws the error: 'System.ListException: Duplicate id in list'.


This error most commonly occurs when programmatically constructing a list of records to update or delete and inadvertently adding the same record ID more than once. For example, a loop that queries and adds records to a list may add the same record under different conditions, resulting in duplicates.

Løsning

    Solution: Convert the List to a Map to Remove Duplicates

    To safely perform DML on a collection that may contain duplicate IDs, convert the List to a Map using the Map(Id, SObject) constructor or the putAll() method. A Map in Apex enforces unique keys — duplicate IDs are automatically overwritten with the last occurrence, leaving one entry per unique ID. After conversion, call DML operations on mapName.values() to process only unique records.

    Steps

    1. Create a Map<Id, SObject> — for example, Map<Id, Account> accMap = new Map<Id, Account>().
    2. Use accMap.putAll(yourList) to populate the map from your list. Duplicate IDs are automatically deduplicated.
    3. If the map is not empty, perform the DML operation on accMap.values() — for example, update accMap.values().

    Important Note

    This is one recommended approach to resolve this error and is not the only solution. Review your code logic to understand how duplicate IDs are being introduced, and test your fix in a sandbox environment before deploying to production.

    List Class

    Map Class




     

    Vidensartikelnummer

    000382864

     
    Indlæser
    Salesforce Help | Article