How to Handle NULL Values in Go SQL Queries

Handle SQL NULL values in Go by scanning into sql.Null* types and checking the Valid field before accessing the data.

Go does not have SQL NULL values; use sql.NullString, sql.NullInt64, or sql.NullTime to handle missing data. Scan query results into these types and check the Valid field before accessing the value.

var n sql.NullString
err := db.QueryRow("SELECT name FROM users WHERE id = ?", id).Scan(&n)
if err != nil { return err }
if n.Valid {
    fmt.Println(n.String)
} else {
    fmt.Println("Name is NULL")
}