# sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is detached; merge() cannot proceed because the session already has a different instance with the same primary key

- **ID:** `python/sqlalchemy-orm-exc-detached-instance-merge-conflict`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Attempting to merge a detached instance when the session already tracks another instance with the same primary key, causing identity conflict.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **Expunge existing instance first** (85% success)
   ```
   Expunge the existing instance from session before merge: session.expunge(existing_instance); session.merge(detached_instance)
   ```
2. **Merge with clean session** (90% success)
   ```
   Use session.merge() with a new instance that does not conflict, or ensure the session is clean before merging.
   ```

## Dead Ends

- **Deleting existing instance** —  (60% fail)
- **Using add() instead** —  (70% fail)
