pgx is a pure Go driver and toolkit for PostgreSQL providing a native high-performance interface with PostgreSQL-specific features plus a database/sql compatibility adapter.
pgx is a pure Go driver and toolkit for PostgreSQL. It provides both a native high-performance PostgreSQL interface and a database/sql-compatible adapter. The native interface exposes PostgreSQL-specific features such as LISTEN/NOTIFY, COPY protocol, pipeline mode, batch queries, large objects, and a comprehensive type system.
github.com/jackc/pgx/v5go get github.com/jackc/pgx/v5import "github.com/jackc/pgx/v5" // main package
import "github.com/jackc/pgx/v5/pgxpool" // connection pool
import "github.com/jackc/pgx/v5/pgconn" // low-level connection
import "github.com/jackc/pgx/v5/pgtype" // type system
import "github.com/jackc/pgx/v5/stdlib" // database/sql adapter
import "github.com/jackc/pgx/v5/tracelog" // logging tracer
import "github.com/jackc/pgx/v5/multitracer" // combine tracers
import "github.com/jackc/pgx/v5/pgproto3" // wire protocol
import "github.com/jackc/pgx/v5/pgtype/zeronull" // zero-value ↔ NULL types
import "github.com/jackc/pgx/v5/pgconn/ctxwatch" // context watcher
import "github.com/jackc/pgx/v5/log/testingadapter" // test logger
import "github.com/jackc/pgx/v5/pgxtest" // testing utilitiesUse pgxpool for concurrent applications:
import "github.com/jackc/pgx/v5/pgxpool"
pool, err := pgxpool.New(ctx, "postgres://user:pass@localhost/mydb")
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// Query
var name string
err = pool.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", 42).Scan(&name)
// Execute
_, err = pool.Exec(ctx, "UPDATE users SET status = $1 WHERE id = $2", "active", 42)See: Connection Pool
Use pgx.Conn for scripts, CLIs, or single-goroutine applications:
import "github.com/jackc/pgx/v5"
conn, err := pgx.Connect(ctx, "postgres://user:pass@localhost/mydb")
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
// Query with row collection
rows, _ := conn.Query(ctx, "SELECT id, name FROM users WHERE active = $1", true)
type User struct {
ID int64 `db:"id"`
Name string `db:"name"`
}
users, err := pgx.CollectRows(rows, pgx.RowToStructByName[User])See: Direct Connection
Use the stdlib adapter for compatibility with database/sql:
import _ "github.com/jackc/pgx/v5/stdlib"
import "database/sql"
db, err := sql.Open("pgx", "postgres://user:pass@localhost/mydb")
defer db.Close()
rows, err := db.Query("SELECT name FROM users WHERE id = $1", 42)See: database/sql Adapter
| Task | Pool Method | Conn Method | See |
|---|---|---|---|
| Execute non-SELECT | pool.Exec(ctx, sql, args...) | conn.Exec(ctx, sql, args...) | Querying |
| Query multiple rows | pool.Query(ctx, sql, args...) | conn.Query(ctx, sql, args...) | Querying |
| Query single row | pool.QueryRow(ctx, sql, args...) | conn.QueryRow(ctx, sql, args...) | Querying |
| Start transaction | pool.Begin(ctx) | conn.Begin(ctx) | Transactions |
| Batch queries | pool.SendBatch(ctx, batch) | conn.SendBatch(ctx, batch) | Batch |
| Bulk insert | pool.CopyFrom(ctx, ...) | conn.CopyFrom(ctx, ...) | COPY |
Use pgxpool.Pool when:
Use pgx.Conn when:
Use database/sql when:
Connection Pool (pgxpool) — Thread-safe pool for concurrent applications
func New(ctx context.Context, connString string) (*Pool, error)
func (p *Pool) Acquire(ctx context.Context) (*Conn, error)
func (p *Pool) Close()Direct Connection (pgx.Conn) — Single connection with full control
func Connect(ctx context.Context, connString string) (*Conn, error)
func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error)
func (c *Conn) Close(ctx context.Context) errorQuerying — Execute queries and scan results
func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error)
func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row
func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error)
func RowToStructByName[T any](row CollectableRow) (T, error)Transactions — Transaction management with isolation levels
func (c *Conn) Begin(ctx context.Context) (Tx, error)
func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error)
func BeginFunc(ctx context.Context, db interface{ Begin(ctx context.Context) (Tx, error) }, fn func(Tx) error) errorBatch Queries — Multiple queries in one round trip
func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults
func (b *Batch) Queue(query string, arguments ...any) *QueuedQueryCOPY Protocol — Bulk loading with binary COPY
func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
func CopyFromRows(rows [][]any) CopyFromSource
func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSourcePostgreSQL type encoding/decoding via pgtype package. Supports all standard types, arrays, composites, ranges, enums, and custom types.
Common Types: Nullable Types — Bool, Int, Float, Text, Date, Timestamp, UUID
Collections: Arrays & Slices — Generic Array[T] and FlatArray[T]
Advanced: Ranges & Multiranges | JSON Types | Geometric Types | Custom Types
database/sql Adapter — Use pgx with database/sql interface
func OpenDB(config pgx.ConnConfig, opts ...OptionOpenDB) *sql.DB
func OpenDBFromPool(pool *pgxpool.Pool, opts ...OptionOpenDB) *sql.DBTracing & Logging — Instrument queries and connections
type QueryTracer interface {
TraceQueryStart(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context
TraceQueryEnd(ctx context.Context, conn *Conn, data TraceQueryEndData)
}Low-Level Connection (pgconn) — Direct wire protocol access for advanced use cases
Full Documentation | Pipeline Mode
Wire Protocol (pgproto3) — Message types for building proxies and tools
Full Documentation
Testing Utilities (pgxtest) — Test helpers and multi-mode testing
Full Documentation
type QueryExecMode int32
const (
QueryExecModeCacheStatement QueryExecMode // default: auto-prepare, cache statements
QueryExecModeCacheDescribe QueryExecMode // cache descriptions only
QueryExecModeDescribeExec QueryExecMode // describe every time, two round trips
QueryExecModeExec QueryExecMode // extended protocol, text params, no cache
QueryExecModeSimpleProtocol QueryExecMode // simple protocol, client-side interpolation
)Override default mode by passing as first argument:
rows, err := conn.Query(ctx, "SELECT ...", pgx.QueryExecModeSimpleProtocol, arg1, arg2)Set default in ConnConfig.DefaultQueryExecMode.
type NamedArgs map[string]any
type StrictNamedArgs map[string]anyUse @name placeholders instead of $1, $2:
conn.Query(ctx, "SELECT * FROM widgets WHERE foo = @foo AND bar = @bar",
pgx.NamedArgs{"foo": 1, "bar": 2})var ErrNoRows error // no rows in result set (wraps sql.ErrNoRows)
var ErrTooManyRows error // more rows than expected
var ErrTxClosed error // transaction already closed
var ErrTxCommitRollback error // commit resulted in rollbackCheck with errors.Is(err, pgx.ErrNoRows). Inspect PostgreSQL errors with errors.As(err, &pgconn.PgError{}).
postgres://user:password@host:port/database?param1=value1¶m2=value2host=localhost port=5432 user=myuser password=secret dbname=mydb sslmode=requirepgx Parameters:
default_query_exec_mode: execution mode (default: cache_statement)statement_cache_capacity: prepared statement cache size (default: 512)description_cache_capacity: description cache size (default: 512)pgxpool Parameters:
pool_max_conns: maximum connections (default: max(4, NumCPU))pool_min_conns: minimum idle connections (default: 0)pool_max_conn_lifetime: max connection age (default: 1h)pool_max_conn_idle_time: max idle time (default: 30m)pool_health_check_period: health check interval (default: 1m)Environment Variables: Same as libpq — PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD, PGSSLMODE, PGSSLCERT, PGSSLKEY, PGSSLROOTCERT, etc.
const (
TextFormatCode = 0
BinaryFormatCode = 1
)PostgreSQL supports text and binary formats. pgx automatically uses binary format where supported for better performance.
Install with Tessl CLI
npx tessl i tessl/golang-github-com-jackc-pgx-v5@5.8.0