Go (Golang) Tutorial 0/45 lessons ~6 min read Lesson 33

    Working with PostgreSQL/MySQL

    The database/sql package provides a generic SQL interface with connection pooling.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    The database/sql package provides a generic SQL interface with connection pooling. Drivers like pgx (PostgreSQL) and go-sql-driver/mysql register via blank import. Go favors raw SQL or lightweight query builders over heavy ORMs — though sqlc and GORM are popular choices.

    Production database code uses context for query cancellation, prepared statements for repeated queries, and transactions for atomic operations. Connection pool tuning (SetMaxOpenConns, SetMaxIdleConns) prevents exhausting database connections under load.

    This lesson connects to PostgreSQL, runs parameterized queries, and handles sql.ErrNoRows — patterns asked in every Go backend interview.

    The story

    A Uber trip-history service connects to PostgreSQL through database/sql with a pooled *sql.DB — not a single connection. The pool manages up to 25 open connections, reuses idle ones, and health-checks the database before a Kubernetes liveness probe marks the pod ready.

    sql.Open doesn't connect immediately; the first query verifies connectivity. Always pass context.Context to QueryContext for cancellation during deploys.

    Understanding the topic

    Key concepts

    • sql.Open returns *sql.DB — connection pool, not single connection.
    • db.QueryContext(ctx, sql, args...) for SELECT returning rows.
    • db.ExecContext for INSERT/UPDATE/DELETE.
    • rows.Scan(&dest...) maps columns to Go variables.
    • sql.ErrNoRows when QueryRow finds nothing — check with errors.Is.
    • tx.BeginTx → Commit/Rollback for transactions.
    Visual overview
    Handler
    sql.DB
    Connection Pool
    pgx / mysql driver
    PostgreSQL

    Step-by-step explanation

    1. Import driver: _ "github.com/jackc/pgx/v5/stdlib".
    2. Open with DSN connection string from env.
    3. PingContext verifies connectivity at startup.
    4. Query with $1 placeholders (Postgres) or ? (MySQL).
    5. Always close rows: defer rows.Close().
    6. Configure pool limits matching database max_connections.

    Practical code example

    PostgreSQL connection with parameterized query and context:

    go
    package main
    import (
    "context"
    "database/sql"
    "errors"
    "fmt"
    "os"
    "time"
    _ "github.com/jackc/pgx/v5/stdlib"
    )
    type User struct {
    ID int64
    Email string
    }
    type UserRepo struct {
    db *sql.DB
    }
    func NewUserRepo(db *sql.DB) *UserRepo {
    return &UserRepo{db: db}
    }
    func (r *UserRepo) GetByEmail(ctx context.Context, email string) (User, error) {
    const q = `SELECT id, email FROM users WHERE email = $1`
    var u User
    err := r.db.QueryRowContext(ctx, q, email).Scan(&u.ID, &u.Email)
    if errors.Is(err, sql.ErrNoRows) {
    return User{}, fmt.Errorf("user %s: %w", email, err)
    }
    return u, err
    }
    func openDB(dsn string) (*sql.DB, error) {
    db, err := sql.Open("pgx", dsn)
    if err != nil {
    return nil, err
    }
    db.SetMaxOpenConns(25)
    db.SetMaxIdleConns(5)
    db.SetConnMaxLifetime(5 * time.Minute)
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    return db, db.PingContext(ctx)
    }
    func main() {
    dsn := os.Getenv("DATABASE_URL")
    if dsn == "" {
    dsn = "postgres://user:pass@localhost:5432/app?sslmode=disable"
    }
    db, err := openDB(dsn)
    if err != nil {
    panic(err)
    }
    defer db.Close()
    repo := NewUserRepo(db)
    u, err := repo.GetByEmail(context.Background(), "alice@example.com")
    fmt.Println(u, err)
    }

    Line-by-line code explanation

    • _ "github.com/jackc/pgx/v5/stdlib" is a blank import. It is only imported for its side effect of registering a database/sql driver named pgx, which is what lets sql.Open("pgx", ...) work later.
    • db *sql.DB is the field in UserRepo that holds the database handle. A sql.DB is a pool of connections, not a single connection, so it is meant to be created once and shared.
    • const q = `SELECT id, email FROM users WHERE email = $1` is the SQL text. The $1 placeholder is filled in by the driver, so the email is sent as data and never pasted into the query string.
    • err := r.db.QueryRowContext(ctx, q, email).Scan(&u.ID, &u.Email) runs the query for at most one row, using ctx so it can be cancelled, and copies the two columns into the fields of u.
    • if errors.Is(err, sql.ErrNoRows) { detects the case where no user matched. The function then returns an empty User and an error that mentions the email and wraps the original error with %w, so callers can still test for sql.ErrNoRows.
    • db, err := sql.Open("pgx", dsn) prepares a connection pool for the pgx driver using the connection string. It does not actually connect yet.
    • db.SetMaxOpenConns(25) limits the pool to 25 open connections. The next two lines allow 5 idle connections to be kept and close any connection that is older than 5 minutes.
    • return db, db.PingContext(ctx) opens a real connection to check that the database is reachable, giving up after the 5-second timeout in ctx. It returns the pool together with the ping result, which is nil if everything worked.
    • dsn := os.Getenv("DATABASE_URL") reads the connection string from the environment. If the variable is empty, main falls back to a local Postgres URL, and it panics if the database cannot be opened.

    Key takeaway: The query uses a $1 placeholder, so the email is passed as data and never joined into the SQL string. sql.Open only prepares the pool, which is why the code pings the database with a 5-second timeout. When no row matches, the error is wrapped with %w so callers can still check for sql.ErrNoRows with errors.Is.

    Real-world use

    Where you'll use this in production

    • User authentication and session storage in PostgreSQL.
    • Order and inventory persistence in e-commerce backends.
    • Analytics aggregation queries against read replicas.
    • Migration scripts with golang-migrate or goose.

    Best practices

    • Parameterized queries only — prevent SQL injection.
    • Pass context.Context to all Query/Exec calls.
    • Configure connection pool for expected concurrency.
    • Close rows; check rows.Err() after iteration.
    • Use transactions for multi-statement atomic operations.
    • Health check: db.PingContext in readiness probe.

    Common mistakes

    • String concatenation in SQL — injection vulnerability.
    • Not closing sql.Rows — connection leak.
    • sql.Open error ignored — Open doesn't connect until Ping.
    • Default unlimited connections exhausting Postgres.
    • Not handling sql.ErrNoRows — conflating with real errors.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionsql.DB vs sql.Conn?+

    Answer

    DB is pool; Conn is single reserved connection from pool for session-level ops.
    2BeginnerQuestionsql.ErrNoRows handling?+

    Answer

    errors.Is(err, sql.ErrNoRows) — map to 404 or domain NotFound, not 500.
    3IntermediateQuestionConnection pool settings?+

    Answer

    SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime — tune to DB limits and load.
    4IntermediateQuestionsqlc vs GORM vs raw SQL?+

    Answer

    sqlc generates type-safe code from SQL; GORM full ORM; raw sql best control and performance.
    5AdvancedQuestionDesign repository layer for testability.+

    Answer

    UserRepository interface; postgres impl with *sql.DB; mock for unit tests; integration tests with testcontainers.

    Summary

    database/sql provides pooled connections with driver plugins. Always use parameterized queries and context. Configure pool limits; Ping at startup. Handle sql.ErrNoRows as domain not-found, not server error. Next lesson: full CRUD operations with transactions.

    Ready to mark this lesson complete?Track your journey across the entire course.