Skip to content

Go SQL Transaction: Partial Updates

DodaTech Updated 2026-06-24 1 min read

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!
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

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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

**Is sql.Tx safe for concurrent use?**

No. A single transaction should only be used from one goroutine.

Can I use prepared statements with transactions?

Yes. Use tx.Prepare() or tx.Stmt().

What happens if Commit fails?

Transaction already closed. Log the error and check retry.


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