Sobes.tech
Middle

There is a table with a unique key on the phone number. How to make it so that when inserting a duplicate record, instead of an error, the existing record is updated (INSERT ON CONFLICT DO UPDATE)?

sobes.tech AI

Answer from AI

In PostgreSQL, to insert a record with an update on conflict by a unique key, the INSERT ... ON CONFLICT ... DO UPDATE construct is used. In Go, using the database/sql package or ORM (e.g., pgx, gorm), you can execute such a query directly.

Example SQL query:

INSERT INTO users (phone, name, email) VALUES ($1, $2, $3)
ON CONFLICT (phone) DO UPDATE SET
  name = EXCLUDED.name,
  email = EXCLUDED.email;

Here, phone is the unique key. When attempting to insert a duplicate by phone, the existing record's name and email fields will be updated.

Example in Go using database/sql:

query := `
INSERT INTO users (phone, name, email) VALUES ($1, $2, $3)
ON CONFLICT (phone) DO UPDATE SET
  name = EXCLUDED.name,
  email = EXCLUDED.email;
`
_, err := db.Exec(query, phone, name, email)
if err != nil {
    // handle error
}

Thus, inserting a duplicate record will not result in an error, and the data will be updated.

There is a table with a unique key on the phone… - sobes.tech