Build HTTP and database integrations
Scan Database Rows into Go Values with `database/sql`
Use database/sql Scan with ordered pointer destinations, sql.NullString, and complete Rows error handling.

To turn a database/sql query into typed Go values, select the columns you need, pass matching field pointers to Scan in that same order, and append a result only after scanning succeeds. For a nullable column, use a type such as sql.NullString so a SQL NULL remains distinguishable from an empty string. The job is not finished when Rows.Next stops: check Rows.Err before returning the collected values.
The examples below assume an existing *sql.DB. The database/sql package documentation notes that a database driver is also required.
Match selected columns to destinations
Suppose a users table has an integer id and a nullable name. This struct keeps the two selected values together:
type User struct {
ID int64
Name sql.NullString
}
The query selects id first and name second, so the scan passes &user.ID first and &user.Name second. Scan writes column values through the destination pointers. Choosing the right fields is only half the mapping: their order must also match the query.
Here is a complete function for reading multiple rows:
package users
import (
"context"
"database/sql"
"fmt"
)
type User struct {
ID int64
Name sql.NullString
}
func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) {
rows, err := db.QueryContext(ctx, "SELECT id, name FROM users")
if err != nil {
return nil, fmt.Errorf("query users: %w", err)
}
defer rows.Close()
var users []User
for rows.Next() {
var user User
if err := rows.Scan(&user.ID, &user.Name); err != nil {
return nil, fmt.Errorf("scan user: %w", err)
}
users = append(users, user)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate users: %w", err)
}
return users, nil
}
QueryContext can report an error immediately, before there are rows to scan. Once the query returns rows, the deferred Close covers both a normal return and an early return after a scan error. Each loop iteration creates a User, scans into its fields, and appends it only if Scan succeeds.
There is a separate error check after the loop because an ending Next loop does not, by itself, establish that the result is complete. As the Go database access tutorial explains, Rows.Err can reveal a query error that left results incomplete. Returning nil alongside any query, scan, or iteration error keeps callers from treating a partial slice as a successful result.
Keep NULL distinct from an empty name
A sql.NullString contains a String value and a Valid flag. Read String only when Valid is true. For example, after a successful call to ListUsers:
for _, user := range users {
if user.Name.Valid {
fmt.Println(user.Name.String)
} else {
fmt.Println("name is SQL NULL")
}
}
The Go SQL interface guide uses this same Valid check for a nullable name: when it is false, the database value was NULL. That distinction matters even if an application eventually displays NULL and an empty string similarly. The struct still carries enough information for the caller to make that choice. Other nullable destinations are available in database/sql, including sql.NullInt64 and sql.NullTime; choose one that represents the column you are reading rather than assuming every nullable value is a string.
When you expect one row
Use QueryRowContext(...).Scan(...) when the query is expected to return at most one row. Its query errors are reported by Scan, and no match produces sql.ErrNoRows. Handle that case separately if it has a different meaning for your caller:
func UserByID(ctx context.Context, db *sql.DB, id int64) (User, error) {
var user User
err := db.QueryRowContext(
ctx,
"SELECT id, name FROM users WHERE id = ?", id,
).Scan(&user.ID, &user.Name)
if err == sql.ErrNoRows {
return User{}, fmt.Errorf("user %d: not found: %w", id, err)
}
if err != nil {
return User{}, fmt.Errorf("query user %d: %w", id, err)
}
return user, nil
}
The ? placeholder follows the parameter style in the Go tutorial's example; use the placeholder syntax accepted by your driver. Even in this shorter form, the selected-column order and nullable destination still matter. Unlike the multi-row function, there is no Rows.Next loop or post-loop Rows.Err check: the single-row result is handled through Scan.





Comments
No comments yet.