Sobes.tech
Junior — Middle

Have you ever used the SELECT FOR UPDATE command in your projects to lock rows during transactions?

sobes.tech AI

Answer from AI

Yes, the SELECT FOR UPDATE command is often used to lock selected rows in a database during a transaction to prevent race conditions and ensure data integrity.

In Go, when working with databases through database/sql or ORM, you can execute such a query to lock rows for subsequent updates:

// Example of using SELECT FOR UPDATE in Go
func updateUserBalance(db *sql.DB, userID int, amount float64) error {
    tx, err := db.Begin()
    if err != nil {
        return err
    }
    defer tx.Rollback()

    var balance float64
    err = tx.QueryRow("SELECT balance FROM users WHERE id = ? FOR UPDATE", userID).Scan(&balance)
    if err != nil {
        return err
    }

    newBalance := balance + amount
    _, err = tx.Exec("UPDATE users SET balance = ? WHERE id = ?", newBalance, userID)
    if err != nil {
        return err
    }

    return tx.Commit()
}

Here, SELECT FOR UPDATE locks the user row so that other transactions cannot modify it until the current transaction completes. This prevents issues with concurrent access, such as double spending.

Have you ever used the SELECT FOR UPDATE command in… - sobes.tech