Go SQL Transaction: Partial Updates
In this tutorial, you'll learn about Go SQL Transaction: Partial Updates. We cover key concepts, practical examples, and best practices.
Database transactions -- Use sql.Tx for atomic multi-step database operations with Commit and Rollback.
The Problem
Running multiple SQL statements without a transaction can leave the database inconsistent. Use db.Begin() to start a transaction.
Wrong
db.Exec("UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, from)
db.Exec("UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, to)
Output:
// First succeeds, second fails -- money lost!
Right
tx, err := db.Begin()
if err != nil { return err }
defer tx.Rollback()
tx.Exec("UPDATE ...", amount, from)
tx.Exec("UPDATE ...", amount, to)
return tx.Commit()
Output:
// Both succeed or neither -- atomic!
Prevention
- Use tx.Begin() to start a transaction
- Always defer tx.Rollback() -- no-op after Commit
- Use tx.Exec(), tx.Query(), tx.QueryRow() within tx
- Call tx.Commit() only after all operations succeed
- Rollback on any error
Common Mistakes with sql transaction
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro