Sobes.tech
Senior

Levels of transaction isolation in PostgreSQL.

sobes.tech AI

Answer from AI

PostgreSQL supports four standard transaction isolation levels defined in the SQL standard:

  1. Read Uncommitted — the lowest isolation level. In PostgreSQL, it effectively behaves like Read Committed, as it does not allow dirty reads.

  2. Read Committed (default) — a transaction sees only data that was committed at the start of each individual query. Non-repeatable reads and phantom reads are possible.

  3. Repeatable Read — a transaction sees data as it was at the start of the transaction. It guarantees repeatable reads but phantom reads are possible.

  4. Serializable — the highest isolation level, providing full transaction serialization, preventing phantom reads, and ensuring data consistency as if transactions were executed sequentially.

Example of setting the isolation level in Go using database/sql and pq driver:

import (
    "database/sql"
    _ "github.com/lib/pq"
)

func setIsolationLevel(db *sql.DB) error {
    tx, err := db.Begin()
    if err != nil {
        return err
    }
    defer tx.Rollback()

    // Setting the isolation level
    _, err = tx.Exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
    if err != nil {
        return err
    }

    // Further operations within the transaction

    return tx.Commit()
}
Levels of transaction isolation in PostgreSQL. — Golang - sobes.tech