Databases in Go (Golang): PostgreSQL, SQL and pgx
Postgres through database/sql. No ORM, so you write and see every query that runs.
This section connects a Go program to PostgreSQL through database/sql, the database interface in the standard library, with pgx as the driver behind it. There is no ORM: you write each SQL query yourself, so you always know exactly what runs against the database, and the skill carries over to any language or framework you use later.
The first lesson covers the everyday mechanics: why *sql.DB is a connection pool rather than one connection, reading one row and many rows, placeholders that stop SQL injection, and nullable columns. The second covers the problems that appear once there is real data: the N+1 query loop, transactions that either commit completely or roll back completely, and reading a query plan to find a missing index.
- 01Postgres with database/sqlNo ORM. Learn what each query does, because SQL outlives every ORM.
- 02Joins, transactions, and the N+1 problemA performance bug that turns up in almost any codebase that talks to a database.
What you will be able to do
- Run Postgres locally in Docker and connect to it with one dependency, the
pgxdriver. - Write queries that cannot be injected, that stop when the client goes away, and that never leak a connection.
- Turn an endpoint that makes one query per row into one that makes a single query, with a join or one batch query.
- Group writes in a transaction that rolls back on any error.
The order to study it in
- You need Core language (structs, errors, interfaces) and
contextfrom Concurrency first. You do not need to know Postgres already; knowing what SELECT, INSERT and WHERE do is enough to follow along. - Read Postgres with database/sql first, then Joins, transactions, and the N+1 problem.
- Then put it to work: the second Practice projects lesson puts the CRUD API on a real database, and step 5 of Project 1 — URL shortener moves its storage to Postgres.
What each lesson covers
By the end of this section you will be able to do everything below. Each lesson has runnable Go examples you can edit and run in the browser.
1. Postgres with database/sql
- Explain why
*sql.DBis a connection pool and configure its limits. - Write single-row and multi-row queries that close rows and check
rows.Err(). - Fix SQL injection by using placeholders, and handle nullable columns.
Remember: Learn SQL, not an ORM.
database/sqlshows you exactly which queries run, and that is a skill that outlives every library.- Explain why
2. Joins, transactions, and the N+1 problem
- Spot an N+1 query loop and fix it with a join or one batch query.
- Write a transaction with a deferred rollback that commits only on success.
- Read an
EXPLAIN ANALYZEplan to find a missing index.
Remember: The database is where your latency lives. One join beats twenty round trips, and one index beats a month of Go micro-optimisation.