liveBook · Manning

Missing value

As explained in 100 Go Mistakes and How to Avoid Them

A null value is a database value representing the absence of a value rather than a value of the column's declared type.

A SQL NULL means a column has no value. It is not the same as the zero value of the column’s Go destination. If an employee’s department is NULL, scanning it into a string fails rather than producing an empty string. section 10.4.4

A nullable department

A query reads an employee’s department and age. With `department` declared as `string`, `rows.Scan(&department, &age)` can fail with `converting NULL to string is unsupported`. Declaring `department` as `*string` and scanning into `&department` instead makes it nil when the column is NULL. section 10.4.4

var (
    department sql.NullString    #1
    age        int
)
for rows.Next() {
    err := rows.Scan(&department, &age)
    // ...
}

Alternatively, scan the department into `sql.NullString`. Check `Valid` before using `String`: `Valid` reports whether the column was not NULL. section 10.4.4

Choose a pointer when a nil destination expresses absence clearly; choose an `sql.NullXXX` type when an explicit validity field makes that intent clearer. Neither approach turns NULL into an ordinary string value. section 10.4.4

The same distinction matters outside SQL. In a Go configuration struct, an omitted integer field becomes 0, so a plain `int` cannot distinguish a missing port from one deliberately set to 0; a `*int` can. Do not assume nil always means a missing database value, though: a nil channel also has its own blocking behavior. section 2.11.1 section 9.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Works through a failing Scan and two nullable destinations, without examining driver internals or writes.
Examples
Uses an employee department-and-age query, its NULL-to-string error, and scans into *string and sql.NullString.
What it assumes
Assumes familiarity with Go variables and Query/Scan; introduces the relevant nullable destination forms and sql.NullString fields.
What you can do after
Diagnose/debug NULL-related Scan failures and select a pointer or sql.NullXXX destination for a nullable column.
How it connects
Connects SQL NULL with Go pointers, sql.NullString, struct zero values, and optional configuration fields.

Also explained in

Compare how 35 books explain missing value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.