When duplicate clause

Official Content
This documentation is valid for:

Allows to specify the code to be executed when a body of a For Each command or New command is trying to update or create (respectively) a record with a value for a candidate Key (in for each case) and/or primary key (in new case) attribute that has already exists for another record. 

It only makes sense in procedures (because it has to do with updates).


When duplicate


GeneXus uses the unique index to ensure the uniqueness of that candidate key, as well as the primary index for the primary key. In case it finds duplicates, if this clause is programmed in the For Each/New command, it will execute its related code (<CodeWhenDuplicate>).

If the clause is not included, and you try to update an attribute that is a candidate key (for each) or assign value to a candidate or primary key (new) and a record with that value already exists, no code will be executed.

About New command: most of the times an update of some attributes of that existing record is needed. In these cases a For Each command is needed. Inside, the attributes to be updated are assigned. Although not so common, other commands can be executed as well. That is:

      <CodeWhenDuplicate> ::=  [<AnotherCode>]

 For each
     { <attribute> = <expr> } ...



  • Inside For each: If another For Each command is included into the <CodeWhenDuplicate>, and its table has same common attribute with the external For Each (that of <MainCode>), this attribute will be considered as instantiated, acting as a filters in the When Duplicate For Each.

For more detailed information for each command, see the sintax section in For Each command, and New command.


If the CustomerName attribute is a candidate Key (there exists a unique index) in the Customer table, and we are trying to update it for many records accessed by means of a for each:

for each Customer

    CustomerName = &customer

when duplicate

    msg( ' The customer ' + &customer + 'already exists')


when there already exists a record with the value contained in &customer, the for each main code is not executed. Instead, the when duplicate code will be executed.