Duplicate-key error (1062)

The MySQL error raised when an insert or update breaks a unique key. go-sql-driver/mysql returns it as *mysql.MySQLError with Number 1062; find it with errors.As, which also works through %w wrapping.

Minimal example

go
var me *mysql.MySQLError
if errors.As(err, &me) && me.Number == 1062 {
	// the row already exists
}

Learn this concept

Lesson 3.7 · Transactions in Go and MySQL

Used in exercises

Exercise 3.10 · POST /v1/orders: idempotent checkout Exercise 3.12 · POST /v1/orders/{id}/events: order lifecycle