Go SQL Null Types: Zero vs NULL
In this tutorial, you'll learn about Go SQL Null Types: Zero vs NULL. We cover key concepts, practical examples, and best practices.
Handling NULL in Go SQL -- Use sql.NullString, sql.NullInt64 to properly handle nullable database columns.
The Problem
Scanning NULL into a plain Go type silently sets it to the zero value. Use sql.Null* types which have a Valid field.
Wrong
type User struct {
ID int
Name string
Email string // nullable in DB
}
rows.Scan(&u.ID, &u.Name, &u.Email)
Output:
// u.Email is "" -- is it empty string or NULL?
Right
type User struct {
ID int
Name string
Email sql.NullString
}
rows.Scan(&u.ID, &u.Name, &u.Email)
if u.Email.Valid {
fmt.Println("Email:", u.Email.String)
} else {
fmt.Println("Email not provided")
}
Output:
Email not provided
Prevention
- Use sql.NullString for nullable VARCHAR
- Use sql.NullInt64 for nullable INTEGER
- Use sql.NullFloat64 for nullable FLOAT
- Use sql.NullBool for nullable BOOLEAN
- Use sql.NullTime for nullable TIMESTAMP
Common Mistakes with sql null types
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro