Handle sql.ErrNoRows and Close *sql.Rows in database/sql
Check sql.ErrNoRows cleanly with errors.Is, close *sql.Rows with defer rows.Close(), check rows.Err(), and use bound parameters. After this, SQL queries will not leak pooled connections or hide missing rows.
Skip ahead: If you already use parameterized queries, skip to "Case 2: close *sql.Rows and check rows.Err()" or the safety table below.
Three database/sql mistakes cause most Go database outages: treating sql.ErrNoRows as an internal 500 error, forgetting defer rows.Close() until the connection pool runs dry, and building SQL strings with fmt.Sprintf. Verified on golang:trixie (Go 1.27.4).
Case 1: distinguish sql.ErrNoRows from real failures
This self-contained program uses a minimal in-memory database/sql/driver so you can run QueryRowContext and inspect sql.ErrNoRows locally:
package main
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
)
type memDriver struct{}
type memConn struct{}
type memRows struct {
idx int
data [][]driver.Value
}
func (memDriver) Open(string) (driver.Conn, error) { return memConn{}, nil }
func (memConn) Prepare(string) (driver.Stmt, error) { return nil, nil }
func (memConn) Close() error { return nil }
func (memConn) Begin() (driver.Tx, error) { return nil, nil }
func (memConn) QueryContext(_ context.Context, _ string, args []driver.NamedValue) (driver.Rows, error) {
if len(args) > 0 && args[0].Value == int64(99) {
return &memRows{}, nil
}
return &memRows{data: [][]driver.Value{{int64(1), "Ana Reyes"}}}, nil
}
func (r *memRows) Columns() []string { return []string{"id", "name"} }
func (r *memRows) Close() error { return nil }
func (r *memRows) Next(dest []driver.Value) error {
if r.idx >= len(r.data) {
return io.EOF
}
copy(dest, r.data[r.idx])
r.idx++
return nil
}
func init() { sql.Register("mem", memDriver{}) }
func findCustomer(ctx context.Context, db *sql.DB, id int64) (string, error) {
var name string
err := db.QueryRowContext(ctx, "SELECT id, name FROM customers WHERE id = $1", id).Scan(&id, &name)
if errors.Is(err, sql.ErrNoRows) {
return "", fmt.Errorf("customer %d: %w", id, sql.ErrNoRows)
}
return name, err
}
func main() {
db, _ := sql.Open("mem", "")
defer db.Close()
for _, id := range []int64{1, 99} {
name, err := findCustomer(context.Background(), db, id)
fmt.Printf("id=%d -> name=%q err=%v\n", id, name, err)
}
}
id=1 -> name="Ana Reyes" err=<nil>
id=99 -> name="" err=customer 99: sql: no rows in result set
Wrapping with %w lets callers check errors.Is(err, sql.ErrNoRows) and return 404 Not Found instead of 500 Internal Server Error.
Case 2: close *sql.Rows and check rows.Err()
For multi-row queries using db.QueryContext, always follow this exact sequence:
rows, err := db.QueryContext(ctx, "SELECT id, name FROM customers WHERE active = $1", true)
if err != nil {
return nil, err
}
defer rows.Close()
var names []string
for rows.Next() {
var id int64
var name string
if err := rows.Scan(&id, &name); err != nil {
return nil, err
}
names = append(names, name)
}
if err := rows.Err(); err != nil {
return nil, err
}
Calling rows.Err() after the loop catches network drops or context cancellations that ended rows.Next() early.
Case 3: open *sql.DB once and tune the pool
- Never call
sql.Openper request:*sql.DBis already a concurrency-safe connection pool. - Call
db.PingContext(ctx)at startup:sql.Openonly parses the DSN and does not test connectivity. - Bound pool size: set
db.SetMaxOpenConns(25)anddb.SetConnMaxLifetime(5 * time.Minute)so a traffic spike does not overwhelm PostgreSQL.
database/sql checklist
| Operation | Use | Avoid |
|---|---|---|
| Single row lookup | QueryRowContext + errors.Is(err, sql.ErrNoRows) | Treating missing rows as 500 |
| Multi-row scan | defer rows.Close() + rows.Err() | Returning before closing rows |
| User values in SQL | Bound placeholders ($1 or ?) | fmt.Sprintf string interpolation |
| Pool lifecycle | One shared *sql.DB at startup | sql.Open inside handlers |
⚠ Warning: Never write defer rows.Close() before checking if err != nil—when QueryContext fails, rows is nil and calling rows.Close() panics.
Common mistakes
- Using
Queryinstead ofExecContextforINSERT/UPDATE:Queryreturns an open*sql.Rowsthat leaks a connection if you discard it; usedb.ExecContextwhen no rows are returned. - Scanning nullable SQL columns into plain
string: usesql.NullStringor*stringfor nullable columns.
What happens if you skip this
One early return inside a rows.Next() loop without defer rows.Close() leaks a pooled connection on every error until every endpoint blocks waiting for a free database connection.
Related course: Go Intermediate.
About
Check sql.ErrNoRows cleanly with errors.Is, close *sql.Rows with defer rows.Close(), check rows.Err(), and use bound parameters. After this, SQL queries will not leak pooled connections or hide missing rows.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.