[SalesForce] How To Check For Duplicates Using SOQL and Apex

I am currently developing a csv importer for our Salesforce to deal with our way of quoting items, and I am currently trying to make it so that if the product has been added in, it detects whether there's duplicate.

This is a snipped of the code i've got so far, however, the Select statement I can't seem to get working.

         for(Integer i=1; i < csvFileLines.size(); i++){
           Product2 proObj = new Product2() ;
           String[] csvRecordData = csvFileLines[i].split(',');
           proObj.name = csvRecordData[0] ;
           if([SELECT Count() FROM Product2 WHERE Name = :proObj.name[i]]==0) {                                                                                       
           productlist.add(proObj);
           }   
         }

Best Answer

If "Name" is a unique field for these records, you can use the Database class with the insert method.

insert(recordsToInsert, dmlOptions)

You can put this in a try-catch block and after enabling dmlOptions flag to allow the partial success of DML operation. This way it won't insert records that are already in the database but those that are new will successfully be inserted.

Or you can form a list of names from your CSV file, then query

[SELECT Id, Name FROM Product2 WHERE Name IN:listOfNamesFromCsv]

and then remove from your CSV-formed list of names duplicates of just use loop and check if your query has such a name, then add names to list and insert to the database by the end of the method.

P.S. Be aware of using SOQL and DML operations inside loops. This is bad practice.

Related Topic