How do I handle NULL values using database/sql with Postgres?

Go, Golang, database/sql, Postgres, NULL values, handling NULL, database interaction
Learn how to effectively handle NULL values in Go using the database/sql package with PostgreSQL.
package main import ( "database/sql" "encoding/json" "fmt" "log" _ "github.com/lib/pq" ) type User struct { ID int `json:"id"` Name string `json:"name"` Email *string `json:"email"` // Email is a pointer to handle NULL values } func main() { connStr := "user=username dbname=mydb sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() // Querying a user var user User row := db.QueryRow("SELECT id, name, email FROM users WHERE id = $1", 1) err = row.Scan(&user.ID, &user.Name, &user.Email) if err != nil { if err == sql.ErrNoRows { fmt.Println("No user found with that ID") } else { log.Fatal(err) } } // Handle NULL email if user.Email != nil { fmt.Printf("User Email: %s\n", *user.Email) } else { fmt.Println("User Email: NULL") } // Convert User to JSON userJson, err := json.Marshal(user) if err != nil { log.Fatal(err) } fmt.Println(string(userJson)) }

Go Golang database/sql Postgres NULL values handling NULL database interaction