{"id":376,"date":"2026-05-13T09:00:00","date_gmt":"2026-05-13T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/"},"modified":"2026-10-10T21:21:22","modified_gmt":"2026-10-10T15:51:22","slug":"go-postgresql-pgx","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/","title":{"rendered":"Go PostgreSQL with pgx: A Practical Guide"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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 &#8220;not found&#8221; and &#8220;duplicate key&#8221;. Finally, we will wrap two writes in a transaction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Earlier, you used the standard <code>database\/sql<\/code> package in <a href=\"https:\/\/smitabharat.com\/blog\/go-database-sql-tutorial\/\">the Go database tutorial<\/a>. 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 <a href=\"https:\/\/smitabharat.com\/blog\/go-context-beginners-guide\/\">Go context for beginners<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Is Go PostgreSQL with pgx?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>database\/sql<\/code> package cannot see.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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, <code>database\/sql<\/code> works with many databases, while pgx knows every PostgreSQL feature.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go PostgreSQL with pgx Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Speed<\/strong>: pgx speaks the binary protocol, so it sends and reads data efficiently.<\/li>\n\n\n\n<li><strong>A built-in pool<\/strong>: <code>pgxpool<\/code> shares connections safely, so many goroutines can query at once.<\/li>\n\n\n\n<li><strong>Struct mapping<\/strong>: helpers turn rows into Go structs, so you skip the manual loop.<\/li>\n\n\n\n<li><strong>Rich types<\/strong>: arrays, JSONB, UUIDs and time zones work without extra code.<\/li>\n\n\n\n<li><strong>Clear errors<\/strong>: you can read the exact PostgreSQL error code, such as a unique violation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In short, Go PostgreSQL code with pgx is shorter, faster and easier to debug.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How Go PostgreSQL with pgx Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-1024x640.png\" alt=\"Go PostgreSQL diagram showing handlers sharing a pgxpool connection pool with $1 placeholders\" class=\"wp-image-355\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Handlers borrow connections from one shared pgxpool, send SQL with $1 placeholders and return the connection when done.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Note the placeholders. In PostgreSQL they look like <code>$1<\/code>, <code>$2<\/code> and <code>$3<\/code>, rather than the <code>?<\/code> used by some other databases. Also, because values travel separately from the SQL text, pgx protects you from SQL injection automatically.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Key Parts of Go PostgreSQL Code<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In practice, most Go PostgreSQL code uses only a handful of methods. So this table lists them with what each one returns.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Method<\/th><th>Use it for<\/th><th>Returns<\/th><\/tr><\/thead><tbody><tr><td><code>pgxpool.New<\/code><\/td><td>Create the pool once at startup<\/td><td><code>*pgxpool.Pool<\/code> and an error<\/td><\/tr><tr><td><code>pool.QueryRow<\/code><\/td><td>One row, such as get by ID<\/td><td>A row you call <code>Scan<\/code> on<\/td><\/tr><tr><td><code>pool.Query<\/code><\/td><td>Many rows<\/td><td><code>pgx.Rows<\/code> and an error<\/td><\/tr><tr><td><code>pool.Exec<\/code><\/td><td>INSERT, UPDATE, DELETE without results<\/td><td>A command tag and an error<\/td><\/tr><tr><td><code>pool.Begin<\/code><\/td><td>Start a transaction<\/td><td><code>pgx.Tx<\/code> and an error<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">The Connection String<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">pgx reads a URL such as <code>postgres:\/\/postgres:secret@localhost:5432\/library?sslmode=disable<\/code>. Store it in an environment variable, so passwords never live in your code. We covered this in <a href=\"https:\/\/smitabharat.com\/blog\/go-environment-variables-config\/\">Go environment variables for configuration<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Type Mapping<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Also, pgx converts PostgreSQL types to Go types for you. For example, here are the most common pairs.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>PostgreSQL type<\/th><th>Go type<\/th><\/tr><\/thead><tbody><tr><td><code>BIGINT<\/code>, <code>BIGSERIAL<\/code><\/td><td><code>int64<\/code><\/td><\/tr><tr><td><code>INTEGER<\/code><\/td><td><code>int32<\/code> or <code>int<\/code><\/td><\/tr><tr><td><code>TEXT<\/code>, <code>VARCHAR<\/code><\/td><td><code>string<\/code><\/td><\/tr><tr><td><code>BOOLEAN<\/code><\/td><td><code>bool<\/code><\/td><\/tr><tr><td><code>TIMESTAMPTZ<\/code><\/td><td><code>time.Time<\/code><\/td><\/tr><tr><td>Any column that can be <code>NULL<\/code><\/td><td>A pointer such as <code>*string<\/code>, or <code>pgtype.Text<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Go PostgreSQL with pgx vs database\/sql<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both options work, so which should you pick? To help, the table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>pgx (native)<\/th><th>database\/sql<\/th><\/tr><\/thead><tbody><tr><td>Databases supported<\/td><td>PostgreSQL only<\/td><td>Many, through drivers<\/td><\/tr><tr><td>Placeholders<\/td><td><code>$1<\/code>, <code>$2<\/code><\/td><td>Depends on the driver<\/td><\/tr><tr><td>Connection pool<\/td><td><code>pgxpool<\/code><\/td><td>Built into <code>sql.DB<\/code><\/td><\/tr><tr><td>Rows to structs<\/td><td><code>pgx.CollectRows<\/code> helpers<\/td><td>Manual <code>Scan<\/code> loop<\/td><\/tr><tr><td>PostgreSQL-only types<\/td><td>Full support<\/td><td>Limited<\/td><\/tr><tr><td>Error details<\/td><td><code>*pgconn.PgError<\/code> with codes<\/td><td>Driver specific<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-1024x640.png\" alt=\"Go PostgreSQL diagram comparing native pgx with database\/sql\" class=\"wp-image-356\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">The native pgx interface talks to PostgreSQL directly, while database\/sql adds a generic layer that works with many databases.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>database\/sql<\/code> if the same code must also run on MySQL or SQLite.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hands-On: A Book Store with Go PostgreSQL<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Create the Table<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, run this SQL in <code>psql<\/code> against a database named <code>library<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE books (\n    id     BIGSERIAL PRIMARY KEY,\n    title  TEXT NOT NULL,\n    author TEXT NOT NULL,\n    isbn   TEXT NOT NULL UNIQUE,\n    price  INTEGER NOT NULL\n);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, <code>BIGSERIAL<\/code> gives every book an automatic ID. Also, <code>UNIQUE<\/code> on <code>isbn<\/code> stops two books from sharing the same ISBN.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Connect with a Pool<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Then add pgx to your module with <code>go get github.com\/jackc\/pgx\/v5<\/code> and create the pool.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Book struct {\n\tID     int64  `db:\"id\"`\n\tTitle  string `db:\"title\"`\n\tAuthor string `db:\"author\"`\n\tISBN   string `db:\"isbn\"`\n\tPrice  int    `db:\"price\"`\n}\n\nfunc main() {\n\tctx := context.Background()\n\tpool, err := pgxpool.New(ctx, os.Getenv(\"DATABASE_URL\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"create pool: %v\", err)\n\t}\n\tdefer pool.Close()\n\n\tif err := pool.Ping(ctx); err != nil {\n\t\tlog.Fatalf(\"cannot reach database: %v\", err)\n\t}\n\tfmt.Println(\"connected\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">However, <code>pgxpool.New<\/code> only prepares the pool. So <code>Ping<\/code> 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 <code>main<\/code> and pass it to your handlers. That way, every Go PostgreSQL query reuses the same small set of connections.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Insert and Query Rows<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Next, these two functions add a book and list books by author.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func createBook(ctx context.Context, pool *pgxpool.Pool, b Book) (int64, error) {\n\tvar id int64\n\terr := pool.QueryRow(ctx,\n\t\t`INSERT INTO books (title, author, isbn, price)\n\t\t VALUES ($1, $2, $3, $4) RETURNING id`,\n\t\tb.Title, b.Author, b.ISBN, b.Price).Scan(&amp;id)\n\treturn id, err\n}\n\nfunc booksByAuthor(ctx context.Context, pool *pgxpool.Pool, author string) ([]Book, error) {\n\trows, err := pool.Query(ctx,\n\t\t`SELECT id, title, author, isbn, price FROM books\n\t\t WHERE author = $1 ORDER BY id`, author)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pgx.CollectRows(rows, pgx.RowToStructByName[Book])\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>RETURNING id<\/code> asks PostgreSQL to send back the new ID, so we read it with <code>QueryRow<\/code> and <code>Scan<\/code>. This saves a second query, which is a common Go PostgreSQL pattern for inserts. Meanwhile, <code>pgx.CollectRows<\/code> loops over the rows and fills one <code>Book<\/code> per row using the <code>db<\/code> tags. Also, it closes the rows for you.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Update, Not Found and Duplicates<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This part shows how to read the result of an update. Also, it shows how to recognise two very common errors.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>tag, err := pool.Exec(ctx,\n\t`UPDATE books SET price = price + $1 WHERE author = $2`, 50, \"Asha\")\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Println(\"updated rows:\", tag.RowsAffected())\n\nvar title string\nerr = pool.QueryRow(ctx, `SELECT title FROM books WHERE id = $1`, 99).Scan(&amp;title)\nif errors.Is(err, pgx.ErrNoRows) {\n\tfmt.Println(\"book 99: not found\")\n}\n\n_, err = createBook(ctx, pool, Book{Title: \"Copy\", Author: \"X\", ISBN: \"978-1-111\", Price: 1})\nvar pgErr *pgconn.PgError\nif errors.As(err, &amp;pgErr) &amp;&amp; pgErr.Code == \"23505\" {\n\tfmt.Println(\"duplicate ISBN:\", pgErr.ConstraintName)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, code <code>23505<\/code> is PostgreSQL&#8217;s code for a unique violation. So in an API, you can turn it into a 409 Conflict instead of a vague 500 error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So after inserting three books, the program prints the following.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>connected\nAsha's books: [{1 Go Basics Asha 978-1-111 499} {2 Go Testing Asha 978-1-222 599}]\nupdated rows: 2\nbook 99: not found\nduplicate ISBN: books_isbn_key<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We also ran the same SQL in PostgreSQL 16 to confirm these results. For example, the duplicate insert failed with <code>duplicate key value violates unique constraint \"books_isbn_key\"<\/code>. Then pgx adds <code>(SQLSTATE 23505)<\/code> at the end of that message.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: A Transaction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func sellBook(ctx context.Context, pool *pgxpool.Pool, bookID int64) error {\n\ttx, err := pool.Begin(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback(ctx) \/\/ does nothing after a successful Commit\n\n\tif _, err := tx.Exec(ctx,\n\t\t`INSERT INTO sales (book_id) VALUES ($1)`, bookID); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tx.Exec(ctx,\n\t\t`UPDATE stock SET qty = qty - 1 WHERE book_id = $1`, bookID); err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit(ctx)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So if either statement fails, the function returns early. Then the deferred <code>Rollback<\/code> undoes everything. Otherwise, <code>Commit<\/code> saves both changes at once.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Handling NULL Values<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">So far, every column was <code>NOT NULL<\/code>. However, real tables often allow missing values, such as an optional subtitle. If you scan a <code>NULL<\/code> into a plain <code>string<\/code>, pgx returns an error, because a Go string cannot be &#8220;nothing&#8221;.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var subtitle *string\nerr := pool.QueryRow(ctx,\n\t`SELECT subtitle FROM books WHERE id = $1`, 1).Scan(&amp;subtitle)\nif err != nil {\n\tlog.Fatal(err)\n}\nif subtitle == nil {\n\tfmt.Println(\"no subtitle\")\n} else {\n\tfmt.Println(\"subtitle:\", *subtitle)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, a pointer can be <code>nil<\/code>, so it holds a <code>NULL<\/code> safely. Alternatively, <code>pgtype.Text<\/code> has a <code>Valid<\/code> field that tells you whether a value exists. Both work, so pick one style and use it across your Go PostgreSQL code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with Go PostgreSQL<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using question mark placeholders<\/strong>: PostgreSQL then reports a syntax error. So use <code>$1<\/code>, <code>$2<\/code> and so on instead.<\/li>\n\n\n\n<li>**Building SQL with <code>fmt.Sprintf<\/code>**: user input can then break or attack your query. Instead, always pass values as arguments.<\/li>\n\n\n\n<li><strong>Opening a new pool per request<\/strong>: the server runs out of connections fast. So create one pool at startup.<\/li>\n\n\n\n<li><strong>Ignoring the no-rows error<\/strong>: a missing record turns into a 500 error. So check <code>pgx.ErrNoRows<\/code> with <code>errors.Is<\/code> and return 404.<\/li>\n\n\n\n<li><strong>Forgetting the context timeout<\/strong>: one slow query can block a handler forever. Instead, use the request context or <code>context.WithTimeout<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go PostgreSQL<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Keep SQL in small, named functions<\/strong>, because they are easy to test and reuse.<\/li>\n\n\n\n<li><strong>Map unique violations to clear messages<\/strong>, so users see &#8220;ISBN already exists&#8221;.<\/li>\n\n\n\n<li>**Use <code>db<\/code> tags on structs**, since <code>RowToStructByName<\/code> matches them to column names.<\/li>\n\n\n\n<li><strong>Size the pool on purpose<\/strong>, because the default may not fit your server. For example, add <code>pool_max_conns=20<\/code> to the URL.<\/li>\n\n\n\n<li><strong>Run schema changes with migrations<\/strong>, so every environment has the same tables.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add a function <code>deleteBook(ctx, pool, id)<\/code> that returns a custom <code>ErrNotFound<\/code> when no row was deleted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hint: check <code>tag.RowsAffected() == 0<\/code> after <code>Exec<\/code>. Then write a small test that deletes the same ID twice and expects the error the second time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These pages cover the driver and the database in detail, so bookmark them.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/github.com\/jackc\/pgx\/v5\">pgx v5 package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/github.com\/jackc\/pgx\/v5\/pgxpool\">pgxpool package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.postgresql.org\/docs\/current\/errcodes-appendix.html\">PostgreSQL error codes<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go PostgreSQL work with pgx uses a shared <code>pgxpool<\/code> created once.<\/li>\n\n\n\n<li>Always use <code>$1<\/code>-style placeholders and pass values as arguments.<\/li>\n\n\n\n<li>Then <code>QueryRow<\/code> reads one row, <code>Query<\/code> reads many and <code>Exec<\/code> changes data.<\/li>\n\n\n\n<li><code>pgx.CollectRows<\/code> with <code>RowToStructByName<\/code> fills structs from rows.<\/li>\n\n\n\n<li>Check <code>pgx.ErrNoRows<\/code> and code <code>23505<\/code> for clear API errors.<\/li>\n\n\n\n<li>Finally, wrap related writes in a transaction with <code>Begin<\/code>, <code>Rollback<\/code> and <code>Commit<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">So far, we created our table by hand in <code>psql<\/code>. However, in real projects that does not scale. Next, we will manage schema changes safely with database migrations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next lesson: <a href=\"https:\/\/smitabharat.com\/blog\/go-database-migrations\/\">Go Database Migrations with golang-migrate<\/a><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Go PostgreSQL work becomes simple and fast with pgx, the most popular PostgreSQL driver for Go. In this post, you will connect with a&hellip;<\/p>\n","protected":false},"author":1,"featured_media":354,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[15],"tags":[11,70,23,21],"swapz_series":[],"class_list":["post-376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-lang","tag-go-lang","tag-go-postgresql","tag-go-tutorial","tag-golang-basics"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go PostgreSQL with pgx: Queries, Pools and Errors<\/title>\n<meta name=\"description\" content=\"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go PostgreSQL with pgx: Queries, Pools and Errors\" \/>\n<meta property=\"og:description\" content=\"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-05-13T03:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-10T15:51:22+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go PostgreSQL with pgx: A Practical Guide\",\"datePublished\":\"2026-05-13T03:30:00+00:00\",\"dateModified\":\"2026-10-10T15:51:22+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/\"},\"wordCount\":1409,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-postgresql-pgx-featured.png\",\"keywords\":[\"Go Lang\",\"Go PostgreSQL\",\"Go Tutorial\",\"Golang Basics\"],\"articleSection\":[\"Go Lang\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/\",\"name\":\"Go PostgreSQL with pgx: Queries, Pools and Errors\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-postgresql-pgx-featured.png\",\"datePublished\":\"2026-05-13T03:30:00+00:00\",\"dateModified\":\"2026-10-10T15:51:22+00:00\",\"description\":\"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-postgresql-pgx-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-postgresql-pgx-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go PostgreSQL featured image: cards for the pool, safe queries and unique violations\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-postgresql-pgx\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go PostgreSQL with pgx: A Practical Guide\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go PostgreSQL with pgx: Queries, Pools and Errors","description":"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/","og_locale":"en_US","og_type":"article","og_title":"Go PostgreSQL with pgx: Queries, Pools and Errors","og_description":"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.","og_url":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-05-13T03:30:00+00:00","article_modified_time":"2026-10-10T15:51:22+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go PostgreSQL with pgx: A Practical Guide","datePublished":"2026-05-13T03:30:00+00:00","dateModified":"2026-10-10T15:51:22+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/"},"wordCount":1409,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png","keywords":["Go Lang","Go PostgreSQL","Go Tutorial","Golang Basics"],"articleSection":["Go Lang"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/","url":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/","name":"Go PostgreSQL with pgx: Queries, Pools and Errors","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png","datePublished":"2026-05-13T03:30:00+00:00","dateModified":"2026-10-10T15:51:22+00:00","description":"Learn Go PostgreSQL with pgx: create a connection pool, insert and query rows, map rows to structs, handle errors and use transactions.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-postgresql-pgx-featured.png","width":2400,"height":1260,"caption":"Go PostgreSQL featured image: cards for the pool, safe queries and unique violations"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-postgresql-pgx\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go PostgreSQL with pgx: A Practical Guide"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=376"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/376\/revisions"}],"predecessor-version":[{"id":386,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/376\/revisions\/386"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/354"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=376"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}