# sql: Rows are closed, cannot call LastInsertId on result

- **ID:** `go/sql-rows-err-lastinsertid`
- **Domain:** go
- **Category:** data_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Calling Result.LastInsertId() on a sql.Result from an INSERT that used a SELECT or RETURNING clause, or after rows have been consumed.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Go 1.15 | active | — | — |
| Go 1.16 | active | — | — |
| Go 1.17 | active | — | — |
| Go 1.18 | active | — | — |
| Go 1.19 | active | — | — |
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |
| Go 1.23 | active | — | — |

## Workarounds

1. **Use db.Exec() for INSERT statements without RETURNING; use db.QueryRow() with RETURNING and scan into a variable** (90% success)
   ```
   Use db.Exec() for INSERT statements without RETURNING; use db.QueryRow() with RETURNING and scan into a variable
   ```
2. **Access LastInsertId immediately after Exec() before any rows iteration** (85% success)
   ```
   Access LastInsertId immediately after Exec() before any rows iteration
   ```
3. **For PostgreSQL with RETURNING, use a separate SELECT currval() or lastval() query** (80% success)
   ```
   For PostgreSQL with RETURNING, use a separate SELECT currval() or lastval() query
   ```

## Dead Ends

- **** — Rows.Close() closes the result set, making LastInsertId unavailable; order is wrong. (90% fail)
- **** — db.Exec() returns a Result that supports LastInsertId, but if the INSERT has a RETURNING clause, it still fails. (60% fail)
- **** — The result is tied to the original query; reconnecting doesn't recover the last insert ID. (95% fail)
