Go PostgreSQL work becomes simple and fast with pgx, the most popular PostgreSQL driver for Go. In this post, you will connect with a connection pool and then insert and read rows. Also, you will map rows into structs and handle errors like “not found” and “duplicate key”. Finally, we will wrap two writes in a transaction.
Earlier, you used the standard database/sql package in the Go database tutorial. Here we go one step further with a driver built only for PostgreSQL. We also pass a context to every call, as you learned in Go context for beginners.
What Is Go PostgreSQL with pgx?
In short, PostgreSQL is a free, powerful relational database, and many Go backends use it. Meanwhile, pgx is a Go library that talks to PostgreSQL directly in its own network protocol. As a result, it supports PostgreSQL features that the generic database/sql package cannot see.
For example, think of a universal TV remote versus the remote that came with your TV. Indeed, the universal one handles the basics for many brands. However, the original remote has every special button. Similarly, database/sql works with many databases, while pgx knows every PostgreSQL feature.
Why Go PostgreSQL with pgx Matters
In fact, most real Go services store data in PostgreSQL. So learning one good driver pays off in almost every project. Specifically, here is what pgx gives you.
- Speed: pgx speaks the binary protocol, so it sends and reads data efficiently.
- A built-in pool:
pgxpoolshares connections safely, so many goroutines can query at once. - Struct mapping: helpers turn rows into Go structs, so you skip the manual loop.
- Rich types: arrays, JSONB, UUIDs and time zones work without extra code.
- Clear errors: you can read the exact PostgreSQL error code, such as a unique violation.
In short, Go PostgreSQL code with pgx is shorter, faster and easier to debug.
How Go PostgreSQL with pgx Works
First, your program creates a pool with a connection string. After that, each query borrows a connection from the pool. Then pgx sends your SQL and its arguments separately, so values can never break the SQL. Finally, the connection goes back into the pool for the next query.

Note the placeholders. In PostgreSQL they look like $1, $2 and $3, rather than the ? used by some other databases. Also, because values travel separately from the SQL text, pgx protects you from SQL injection automatically.
Key Parts of Go PostgreSQL Code
In practice, most Go PostgreSQL code uses only a handful of methods. So this table lists them with what each one returns.
| Method | Use it for | Returns |
|---|---|---|
pgxpool.New | Create the pool once at startup | *pgxpool.Pool and an error |
pool.QueryRow | One row, such as get by ID | A row you call Scan on |
pool.Query | Many rows | pgx.Rows and an error |
pool.Exec | INSERT, UPDATE, DELETE without results | A command tag and an error |
pool.Begin | Start a transaction | pgx.Tx and an error |
The Connection String
pgx reads a URL such as postgres://postgres:secret@localhost:5432/library?sslmode=disable. Store it in an environment variable, so passwords never live in your code. We covered this in Go environment variables for configuration.
Type Mapping
Also, pgx converts PostgreSQL types to Go types for you. For example, here are the most common pairs.
| PostgreSQL type | Go type |
|---|---|
BIGINT, BIGSERIAL | int64 |
INTEGER | int32 or int |
TEXT, VARCHAR | string |
BOOLEAN | bool |
TIMESTAMPTZ | time.Time |
Any column that can be NULL | A pointer such as *string, or pgtype.Text |
Go PostgreSQL with pgx vs database/sql
Both options work, so which should you pick? To help, the table below compares them.
| Feature | pgx (native) | database/sql |
|---|---|---|
| Databases supported | PostgreSQL only | Many, through drivers |
| Placeholders | $1, $2 | Depends on the driver |
| Connection pool | pgxpool | Built into sql.DB |
| Rows to structs | pgx.CollectRows helpers | Manual Scan loop |
| PostgreSQL-only types | Full support | Limited |
| Error details | *pgconn.PgError with codes | Driver specific |

So when should you use which? Pick pgx when you know your project uses PostgreSQL, which is most of the time. On the other hand, choose database/sql if the same code must also run on MySQL or SQLite.
Hands-On: A Book Store with Go PostgreSQL
Now let’s build a small book store with Go PostgreSQL. First we create a table and add books. Then we list them by author, update prices and handle errors.
Step 1: Create the Table
First, run this SQL in psql against a database named library.
CREATE TABLE books (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
isbn TEXT NOT NULL UNIQUE,
price INTEGER NOT NULL
);
Here, BIGSERIAL gives every book an automatic ID. Also, UNIQUE on isbn stops two books from sharing the same ISBN.
Step 2: Connect with a Pool
Then add pgx to your module with go get github.com/jackc/pgx/v5 and create the pool.
type Book struct {
ID int64 `db:"id"`
Title string `db:"title"`
Author string `db:"author"`
ISBN string `db:"isbn"`
Price int `db:"price"`
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalf("create pool: %v", err)
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
log.Fatalf("cannot reach database: %v", err)
}
fmt.Println("connected")
}
However, pgxpool.New only prepares the pool. So Ping is the real check that the database answers. Create the pool once and share it everywhere, because it is safe for many goroutines. For example, in a web server, you create it in main and pass it to your handlers. That way, every Go PostgreSQL query reuses the same small set of connections.
Step 3: Insert and Query Rows
Next, these two functions add a book and list books by author.
func createBook(ctx context.Context, pool *pgxpool.Pool, b Book) (int64, error) {
var id int64
err := pool.QueryRow(ctx,
`INSERT INTO books (title, author, isbn, price)
VALUES ($1, $2, $3, $4) RETURNING id`,
b.Title, b.Author, b.ISBN, b.Price).Scan(&id)
return id, err
}
func booksByAuthor(ctx context.Context, pool *pgxpool.Pool, author string) ([]Book, error) {
rows, err := pool.Query(ctx,
`SELECT id, title, author, isbn, price FROM books
WHERE author = $1 ORDER BY id`, author)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByName[Book])
}
RETURNING id asks PostgreSQL to send back the new ID, so we read it with QueryRow and Scan. This saves a second query, which is a common Go PostgreSQL pattern for inserts. Meanwhile, pgx.CollectRows loops over the rows and fills one Book per row using the db tags. Also, it closes the rows for you.
Step 4: Update, Not Found and Duplicates
This part shows how to read the result of an update. Also, it shows how to recognise two very common errors.
tag, err := pool.Exec(ctx,
`UPDATE books SET price = price + $1 WHERE author = $2`, 50, "Asha")
if err != nil {
log.Fatal(err)
}
fmt.Println("updated rows:", tag.RowsAffected())
var title string
err = pool.QueryRow(ctx, `SELECT title FROM books WHERE id = $1`, 99).Scan(&title)
if errors.Is(err, pgx.ErrNoRows) {
fmt.Println("book 99: not found")
}
_, err = createBook(ctx, pool, Book{Title: "Copy", Author: "X", ISBN: "978-1-111", Price: 1})
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
fmt.Println("duplicate ISBN:", pgErr.ConstraintName)
}
Here, code 23505 is PostgreSQL’s code for a unique violation. So in an API, you can turn it into a 409 Conflict instead of a vague 500 error.
So after inserting three books, the program prints the following.
connected
Asha's books: [{1 Go Basics Asha 978-1-111 499} {2 Go Testing Asha 978-1-222 599}]
updated rows: 2
book 99: not found
duplicate ISBN: books_isbn_key
We also ran the same SQL in PostgreSQL 16 to confirm these results. For example, the duplicate insert failed with duplicate key value violates unique constraint "books_isbn_key". Then pgx adds (SQLSTATE 23505) at the end of that message.
Step 5: A Transaction
However, sometimes two writes must succeed or fail together. For instance, when a customer buys a book, we record the sale and reduce stock in one step.
func sellBook(ctx context.Context, pool *pgxpool.Pool, bookID int64) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) // does nothing after a successful Commit
if _, err := tx.Exec(ctx,
`INSERT INTO sales (book_id) VALUES ($1)`, bookID); err != nil {
return err
}
if _, err := tx.Exec(ctx,
`UPDATE stock SET qty = qty - 1 WHERE book_id = $1`, bookID); err != nil {
return err
}
return tx.Commit(ctx)
}
So if either statement fails, the function returns early. Then the deferred Rollback undoes everything. Otherwise, Commit saves both changes at once.
Handling NULL Values
So far, every column was NOT NULL. However, real tables often allow missing values, such as an optional subtitle. If you scan a NULL into a plain string, pgx returns an error, because a Go string cannot be “nothing”.
var subtitle *string
err := pool.QueryRow(ctx,
`SELECT subtitle FROM books WHERE id = $1`, 1).Scan(&subtitle)
if err != nil {
log.Fatal(err)
}
if subtitle == nil {
fmt.Println("no subtitle")
} else {
fmt.Println("subtitle:", *subtitle)
}
Here, a pointer can be nil, so it holds a NULL safely. Alternatively, pgtype.Text has a Valid field that tells you whether a value exists. Both work, so pick one style and use it across your Go PostgreSQL code.
Common Mistakes with Go PostgreSQL
- Using question mark placeholders: PostgreSQL then reports a syntax error. So use
$1,$2and so on instead. - **Building SQL with
fmt.Sprintf**: user input can then break or attack your query. Instead, always pass values as arguments. - Opening a new pool per request: the server runs out of connections fast. So create one pool at startup.
- Ignoring the no-rows error: a missing record turns into a 500 error. So check
pgx.ErrNoRowswitherrors.Isand return 404. - Forgetting the context timeout: one slow query can block a handler forever. Instead, use the request context or
context.WithTimeout.
Best Practices for Go PostgreSQL
- Keep SQL in small, named functions, because they are easy to test and reuse.
- Map unique violations to clear messages, so users see “ISBN already exists”.
- **Use
dbtags on structs**, sinceRowToStructByNamematches them to column names. - Size the pool on purpose, because the default may not fit your server. For example, add
pool_max_conns=20to the URL. - Run schema changes with migrations, so every environment has the same tables.
Practice Task
Add a function deleteBook(ctx, pool, id) that returns a custom ErrNotFound when no row was deleted.
Hint: check tag.RowsAffected() == 0 after Exec. Then write a small test that deletes the same ID twice and expects the error the second time.
Official Resources
These pages cover the driver and the database in detail, so bookmark them.
Quick Recap
- Go PostgreSQL work with pgx uses a shared
pgxpoolcreated once. - Always use
$1-style placeholders and pass values as arguments. - Then
QueryRowreads one row,Queryreads many andExecchanges data. pgx.CollectRowswithRowToStructByNamefills structs from rows.- Check
pgx.ErrNoRowsand code23505for clear API errors. - Finally, wrap related writes in a transaction with
Begin,RollbackandCommit.
What’s Next?
So far, we created our table by hand in psql. However, in real projects that does not scale. Next, we will manage schema changes safely with database migrations.
Next lesson: Go Database Migrations with golang-migrate


