Query Relational Data Safely With database/sql
Run parameterized queries with QueryRowContext and QueryContext, handle sql.ErrNoRows, and always close rows. After this, you can integrate SQL databases without leaks or injection bugs.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
Go's standard database/sql package gives you a concurrency-safe connection pool (*sql.DB) that works across PostgreSQL, MySQL, and SQLite drivers with one consistent API. Yet three small omissions cause almost every database/sql outage in real services: string-concatenating SQL inputs, treating sql.ErrNoRows like a 500 crash, and leaking connections by omitting defer rows.Close() or rows.Err().
Skip ahead
If you already verify startup connectivity with db.PingContext, handle sql.ErrNoRows cleanly, close every *sql.Rows, and check rows.Err(), take the section quiz or continue to "Wrap HTTP Handlers With Middleware."
Experiment 1: Why sql.Open succeeds even when your database is down
Many Go beginners are baffled when sql.Open("pgx", badDSN) returns err == nil even with a wrong password or unreachable host. That is by design: sql.Open only initializes the pool handle lazily without opening a TCP socket. Always call db.PingContext(ctx) during startup so bad credentials fail fast before your server starts accepting traffic:
db, err := sql.Open("pgx", dsn)
if err != nil {
return fmt.Errorf("open db: %w", err)
}
defer db.Close()
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := db.PingContext(pingCtx); err != nil {
return fmt.Errorf("ping db: %w", err)
}
Experiment 2: Parameterized queries and mapping sql.ErrNoRows to 404
Never build SQL with fmt.Sprintf("... WHERE id = %s", id)—it invites SQL injection and defeats database query-plan caching. Always pass bind placeholders ($1 in PostgreSQL, ? in SQLite/MySQL).
When fetching a single row with db.QueryRowContext, a missing record is not an infrastructure error—Scan returns sql.ErrNoRows so you can translate it to a domain sentinel error (like ErrUserNotFound) and return 404 Not Found cleanly:
var ErrUserNotFound = errors.New("user not found")
func getUserEmail(ctx context.Context, db *sql.DB, id int64) (string, error) {
var email string
err := db.QueryRowContext(ctx, "SELECT email FROM users WHERE id = $1", id).Scan(&email)
if errors.Is(err, sql.ErrNoRows) {
return "", ErrUserNotFound
}
if err != nil {
return "", fmt.Errorf("query user %d: %w", id, err)
}
return email, nil
}
Experiment 3: Multi-row queries—why both defer rows.Close() and rows.Err() are mandatory
When reading multiple rows with db.QueryContext, two lines prevent silent connection leaks and silently truncated results:
func listActiveUsers(ctx context.Context, db *sql.DB) ([]User, error) {
rows, err := db.QueryContext(ctx, "SELECT id, email FROM users WHERE active = $1", true)
if err != nil {
return nil, fmt.Errorf("list users: %w", err)
}
defer rows.Close()
var out []User
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Email); err != nil {
return nil, fmt.Errorf("scan user: %w", err)
}
out = append(out, u)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate users: %w", err)
}
return out, nil
}
Trace what breaks if you skip either line:
- Skip
defer rows.Close(): If row 3 hits aScanerror and returns early, that database connection stays pinned open outside the pool—after 25 errors, your entire API freezes waiting for a connection! - Skip
rows.Err(): If the network drops orctxtimes out after row 12 of 500,rows.Next()simply returnsfalse. Without checkingrows.Err(), your function returns those 12 partial rows witherr == nilas if they were the entire table!
Experiment 4: Handling nullable SQL columns without panicking
Scanning a SQL NULL into a plain Go string fails with converting NULL to string is unsupported. Either handle it in SQL with COALESCE(nickname, ''), or scan into sql.NullString (or *string) when you need to distinguish NULL from an empty string.
Common mistakes
- Calling
defer rows.Close()before checkingif err != nil: IfQueryContextfails,rowsisniland deferredrows.Close()panics on exit. - Opening a new
sql.Openinside every HTTP handler:*sql.DBis a long-lived concurrency-safe pool—open it once at startup and pass it into handlers. - Using
Queryinstead ofQueryContext: Ignores request timeouts and client disconnects.
💡 Tip
Once your queries grow beyond a dozen hand-written rows.Scan(...) blocks, check out sqlc—it compiles plain .sql files into type-safe Go functions at build time using go generate, eliminating scan-order typos completely.
What happens if you skip this step
A single missing defer rows.Close() slowly drains your connection pool until every endpoint hangs, and a missing rows.Err() check silently ships truncated customer lists whenever a database connection resets mid-query.
During a for rows.Next() loop over 1,000 invoices, the request's ctx times out after row 40. What does rows.Next() return on iteration 41, and how does your code catch that the result is incomplete?
About
Run parameterized queries with QueryRowContext and QueryContext, handle sql.ErrNoRows, and always close rows. After this, you can integrate SQL databases without leaks or injection bugs.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.