+ Start a Discussion
Andrey PetuhovAndrey Petuhov 

how to check if record name already exists or not

Hi friends, I just learing SF. Help me: I how do i check if name record already exists or not in the database. If record already exists, then do nothing, if not exists insert the record.
And then refresh page if record inserting.
My code:
------------------------------------------------
public class CarGarageController {
        public Car__c car { get; set; }
          public String carName { get; set; }
        public Car_Garage__c carGarage { get; set; }
        
        public CarGarageController () {
            getCars();
        }
    
           public void receiveCarName() {
           String carName=Apexpages.currentPage().getParameters().get('carName');
        }
    
          public PageReference insertCar() {
            carGarage = [
                SELECT Id
                FROM Car_Garage__c
                LIMIT 1
            ];

            car = new Car__c(Car_Garage__c=carGarage.id, Name=carName);
            insert car;
            return null;
        }         
        
        public List<Car__c> carList { get; set; }
    
        private void getCars() {
        carList = [
                SELECT Id, Name, Car_Garage__c, CreatedByID, CreatedDate
                FROM Car__c
                ORDER BY Name ASC
            ];
        }
}

------------------------------------------------
Thanks for answers!
Best Answer chosen by Andrey Petuhov
CharuDuttCharuDutt
Hii Andrey
Try The Below Trigger 
Trigger prevemtDuplication on contact(before insert, before update) {
Set<string> nameSet = new Set <string>() ;
If (trigger.IsBefore) {
    If(trigger. Is Insert || trigger.IsUpdate){
        For(Contact con : trigger.new){
                  NameSet.add(con.lastName);
               } 
           } 
      } 

List<Contact> lstcon = [select Id, lastName from Contact where lastName in :nameSet];

For(Contact con2 : trigger.new){
   If(lstcon.size()>0){
       con2.lastName.adderror('duplicate last name found');
   }
​​​​​​} 

Please Mark It As Best Answer If It Helps
THANK you! 

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Andrey,

>> https://help.salesforce.com/articleView?id=sf.duplicate_rules_map_of_reference.htm&type=5

By default there is duplicate rules that detect the duplicates before inserting the record you can read regarding these in the above link.

>> https://developer.salesforce.com/forums/?id=906F0000000Apt8IAC

You can try the above link that has a custom implementation of check duplicates on case trigger you can modify it to your implementation:
 
Trigger:
trigger CasesTrigger on Case (before insert, before update) {
    
    if(Trigger.isBefore){
		if(Trigger.isInsert){
			CaseDupeChecker.caseDupeCheck(Trigger.new);
		}
		else if(Trigger.isUpdate){
			CaseDupeChecker.caseDupeCheck(Trigger.new);
		}
	}
}
Class:
public class CaseDupeChecker {

	public static void caseDupeCheck(List<Case> cases){
		map <Id, Case> caseMap = new map <Id, Case>();
		
		for(Case case: cases){
			if(case.Global_Id__c != null){				
				if(caseMap.containsKey(case.Global_Id__c)){
					case.addError('Duplicate Case found in batch.');
				} else {
					caseMap.put(case.Global_Id__c, case);
				}
			}
		}
		
		if(!caseMap.isEmpty()){
			//Include the required fields on case object in order for the below query to execute successfully 
			list <Case> lstCas = [SELECT Id, Global_Id__c 
										  FROM Case
										  WHERE Global_Id__c IN: caseMap.keySet()];
			
			for (Case cas: lstCas){
				if(caseMap.containsKey(cas.Global_Id__c) && (cas.Id != caseMap.get(cas.Global_Id__c).Id)){
					caseMap.get(cas.Email__c).addError('Duplicate Case found in Salesforce: '+cas.Id);
				}
			}
		}
		
	}
}

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
CharuDuttCharuDutt
Hii Andrey
Try The Below Trigger 
Trigger prevemtDuplication on contact(before insert, before update) {
Set<string> nameSet = new Set <string>() ;
If (trigger.IsBefore) {
    If(trigger. Is Insert || trigger.IsUpdate){
        For(Contact con : trigger.new){
                  NameSet.add(con.lastName);
               } 
           } 
      } 

List<Contact> lstcon = [select Id, lastName from Contact where lastName in :nameSet];

For(Contact con2 : trigger.new){
   If(lstcon.size()>0){
       con2.lastName.adderror('duplicate last name found');
   }
​​​​​​} 

Please Mark It As Best Answer If It Helps
THANK you! 
This was selected as the best answer
Suraj Tripathi 47Suraj Tripathi 47
Hi Andrey
Try The Below Trigger 
 
Trigger prevemtDuplication on contact(before insert, before update) {
Set<string> nameSet = new Set <string>() ;
If (trigger.IsBefore) {
    If(trigger. Is Insert || trigger.IsUpdate){
        For(Contact con : trigger.new){
                  NameSet.add(con.lastName);
               } 
           } 
      } 

List<Contact> lstcon = [select Id, lastName from Contact where lastName in :nameSet];
Set<String> conName=new Set<String>();
for(Contact con:lstcon){
conName.add(con.Lastname);
}
For(Contact con2 : trigger.new){
   If(conName.contains(con2.Lastname)){
       con2.lastName.adderror('duplicate last name found');
   }
​​​​​​}
If you find this helpful please mark it as a best answer.

Thanks And Regards ,
Suraj Tripathi.