       INSERT INTO codes
       (referenced_relation, record_id, code_category, code_prefix, code_prefix_separator, code, code_suffix, code_suffix_separator, code_date, code_date_mask)
       (SELECT 'specimen_parts', new_part_id, code_category, code_prefix, code_prefix_separator, code, code_suffix, code_suffix_separator, code_date, code_date_mask
-      FROM codes
-      WHERE referenced_relation = 'specimen_parts'
-        AND record_id = part_id
-        AND code_category = 'main'
-        AND full_code_order_by IN (recPartsDetails.main_code, recPartsDetails.rbins_code, recPartsDetails.inventory_code, recPartsDetails.batch_main_code)
+       FROM codes
+       WHERE referenced_relation = 'specimen_parts'
+         AND record_id = part_id
+         AND code_category = 'main'
+         AND (full_code_order_by IN (recPartsDetails.main_code, recPartsDetails.rbins_code, recPartsDetails.inventory_code, recPartsDetails.batch_main_code)
+              OR
+              CASE WHEN coalesce(new_code_id,0) = 0 THEN true ELSE id = new_code_id END
+             )
       );
       GET DIAGNOSTICS code_count = ROW_COUNT;
       IF code_count = 0 THEN

      WHERE referenced_relation = 'specimen_parts'
        AND record_id = part_id
        AND code_category = 'main'
        AND full_code_order_by IN (recPartsDetails.main_code, recPartsDetails.rbins_code, recPartsDetails.inventory_code, recPartsDetails.batch_main_code);
      GET DIAGNOSTICS code_count = ROW_COUNT;
      IF code_count = 0 THEN
        IF createCodes (new_part_id, recPartsDetails.old_main_code) < 0 THEN


      IF coalesce(new_code_id,'') = '' THEN
        RAISE NOTICE 'No update occured for code: %', recPartsDetails.main_code;
        SELECT createNewPart(part_id, recPartsDetails) INTO new_part_id;
        IF new_part_id < 0 THEN
          return false;
        END IF;
      ELSE
        RAISE NOTICE 'At least one update occured for code: % ', recPartsDetails.main_code;
        SELECT createNewPart(part_id, recPartsDetails, new_code_id) INTO new_part_id;
        IF new_part_id < 0 THEN
          return false;
        END IF;
      END IF;
      select array_agg(coalesce(code_prefix, '') || case when code_prefix is null then '' else coalesce(code_prefix_separator, ' ') end || coalesce(code, '') || case when code_suffix is null then '' else coalesce(code_suffix_separator, ' ') end || coalesce(code_suffix, '')) into recActualCodes from codes where code_category = 'main' and referenced_relation = 'specimen_parts' and record_id = part_id;
      select array_agg(coalesce(code_prefix, '') || case when code_prefix is null then '' else coalesce(code_prefix_separator, ' ') end || coalesce(code, '') || case when code_suffix is null then '' else coalesce(code_suffix_separator, ' ') end || coalesce(code_suffix, '')) into recTransferedCodes from codes where code_category = 'main' and referenced_relation = 'specimen_parts' and record_id = new_part_id;
