How can I retrieve the last insert id using the pgx library in Go when using the Exec() function?

1 Answers
Answered by suresh

To retrieve the last insert id using the pgx library in Go when using the Exec() function, you can use the `RETURNING` clause in your SQL query and then use the `queryRow` method to fetch the last insert id.

Here is an example implementation:

```go
package main

import (
"context"
"fmt"

"github.com/jackc/pgx/v4"
)

func getLastInsertID() (int, error) {
conn, err := pgx.Connect(context.Background(), "your_database_url")
if err != nil {
return 0, err
}
defer conn.Close(context.Background())

var lastInsertID int
err = conn.QueryRow(context.Background(), "INSERT INTO your_table (column1, column2) VALUES ($1, $2) RETURNING id", value1, value2).Scan(&lastInsertID)
if err != nil {
return 0, err
}

return lastInsertID, nil
}

func main() {
lastInsertID, err := getLastInsertID()
if err != nil {
fmt.Println("Error:", err)
return
}

fmt.Println("Last Insert ID:", lastInsertID)
}
```

In this code snippet, we first establish a connection to the PostgreSQL database using the pgx library. We then execute an `INSERT` query with the `RETURNING` clause to fetch the `id` of the last inserted record. Finally, we use the `Scan()` method to extract the last insert id and return it.

This approach allows you to retrieve the last insert id using the pgx library in Go when using the Exec() function while maintaining a clean and SEO-friendly coding style.

Answer for Question: How can I retrieve the last insert id using the pgx library in Go when using the Exec() function?