Skip to content

Go SQL Null Types: Zero vs NULL

DodaTech Updated 2026-06-24 1 min read

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?
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

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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

**Can I use pointers instead of Null types?**

Yes. *string, *int also handle NULL.

What about json serialization of Null types?

sql.Null* types have custom json marshal/unmarshal.

Are there Null types for all types?

sql provides NullString, NullInt64, NullFloat64, NullBool, NullTime.


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