Why does upsert cause a DUPLICATE_VALUE error?

So, if I understood correctly, you are passing the same key twice in the list, correct? If that's the case, this is documented

Upserting Records

If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated.


I think the issue is related to the uniqueness of the 'Name' field. This field is just a user-friendly name for the object that is shown in layouts, related lists, etc. But this field is not guaranteed to be unique.

For instance, you can have 2 contacts with the same First and Last name. It may be erroneous information, but SF will not prevent you from doing that.

Your issue is that by doing

upsert flights Name;

you're telling Salesforce to use the 'Name' field as an external ID. If you just do

upsert flights;

you will not see the error (but this may not be what you want... see below).

From the trailhead lesson on DML:

The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce

Suggested solution

If you want an absolutely unique field to identify your records, I would recommend not using the out-of-the-box 'Name' field. Instead, create a custom field (for isntance, 'FlightName') and set the metadata on that field to be External ID and/or Unique.