Go

sql.NullString — Nullable DB Columns

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Plain `string` can't represent SQL NULL. Use `sql.NullString` (and its siblings `NullInt64`, `NullBool`, etc.) for columns where NULL is a real value distinct from empty.
Go
Raw
package main

import (
    "database/sql"
    "fmt"
)

type User struct {
    ID    int
    Name  string
    Email sql.NullString          // can be NULL in the DB
}

func main() {
    var u User

    // After a Scan, check Valid before using String
    rows, _ := (*sql.DB)(nil).Query("SELECT id, name, email FROM users WHERE id = ?", 42)
    for rows.Next() {
        rows.Scan(&u.ID, &u.Name, &u.Email)
        if u.Email.Valid {
            fmt.Println("has email:", u.Email.String)
        } else {
            fmt.Println("no email")
        }
    }

    // Insert / update — set Valid=true to write a value, false to write NULL
    u.Email = sql.NullString{String: "a@x.com", Valid: true}
    u.Email = sql.NullString{Valid: false}                     // → NULL

    // Convert NullString to *string for JSON
    var emailPtr *string
    if u.Email.Valid { emailPtr = &u.Email.String }
    _ = emailPtr
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.