SQLite from Go: connections, drivers and types · 3 MIN READ
NULLs and time values: sql.Null, pointers, COALESCE and a time format you choose
Scan nullable columns with sql.NullString, sql.Null[T] and pointers, write NULL-aware SQL, and store times in a format that sorts and that SQLite's date functions understand.
Two things trip up nearly every Go program that talks to SQLite: a NULL arriving in a plain string, and time values stored in whatever format the driver happened to choose. SQLite has no date type, so the format is your decision. Make both explicit in the schema and in the scan targets and the surprises go away.
sqlite · A MAP OF THE IDEA
- Mark optional columns
- Scan into Null or *T
- Store UTC, one format
- Query with IS, coalesce
Useful when
- Missing values stay distinguishable from zero values.
- Fixed-width UTC text and Unix integers sort and index well.
Watch out
- Driver default time formats differ and may not parse in SQL.
- NOT IN with a NULL in the list matches nothing.
Implementation & operation cost: A layout constant with two conversion functions, and Null types or pointers wherever the schema allows NULL.
NULL in, Go value out
database/sql refuses to scan NULL into string, int64 or bool and returns an error naming the column. For nullable columns, scan into sql.NullString, sql.NullInt64, sql.NullTime and friends, the generic sql.Null[T] added in Go 1.22, or a pointer such as *int64 that stays nil for NULL. Writing works the other way: a nil argument or a Null value with Valid false stores NULL. Pick one convention per codebase; pointers read well in structs that become JSON, Null types make the validity check explicit.
A table with optional columns and two time formats
The program stores a joined time as fixed-width UTC text and a last-seen time as Unix seconds, inserts one complete and one sparse row, and reads them back with Null types and a pointer. It then shows NULL comparisons, SQLite's date functions reading both formats, and what modernc.org/sqlite writes when you pass a time.Time directly, with and without _time_format=sqlite.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"time"
_ "modernc.org/sqlite"
)
// One fixed-width UTC layout: text comparison then matches time order.
const layout = "2006-01-02T15:04:05.000Z"
func main() {
ctx := context.Background()
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
if _, err := db.ExecContext(ctx, `CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
nickname TEXT, -- optional
score INTEGER, -- optional
joined_at TEXT NOT NULL, -- UTC, fixed-width text
seen_unix INTEGER -- optional, Unix seconds
)`); err != nil {
log.Fatal(err)
}
joined := time.Date(2026, 3, 1, 9, 30, 0, 0, time.FixedZone("CET", 3600))
seen := time.Date(2026, 11, 29, 18, 0, 0, 0, time.UTC)
insert := "INSERT INTO users (name, nickname, score, joined_at, seen_unix) VALUES (?, ?, ?, ?, ?)"
// A nil interface or an invalid sql.Null value is stored as NULL.
if _, err := db.ExecContext(ctx, insert, "Ada", "countess", 42, joined.UTC().Format(layout), seen.Unix()); err != nil {
log.Fatal(err)
}
if _, err := db.ExecContext(ctx, insert, "Brian", nil, sql.Null[int64]{}, joined.Add(time.Hour).UTC().Format(layout), sql.NullInt64{}); err != nil {
log.Fatal(err)
}
// Scanning NULL into a plain string is an error, not an empty string.
var nick string
err = db.QueryRowContext(ctx, "SELECT nickname FROM users WHERE name = 'Brian'").Scan(&nick)
fmt.Println("plain string:", err)
rows, err := db.QueryContext(ctx, "SELECT name, nickname, score, joined_at, seen_unix FROM users ORDER BY joined_at")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name, joinedText string
var nickname sql.NullString
var score sql.Null[int64]
var seenUnix *int64 // a pointer is nil for NULL
if err := rows.Scan(&name, &nickname, &score, &joinedText, &seenUnix); err != nil {
log.Fatal(err)
}
joinedAt, err := time.Parse(layout, joinedText)
if err != nil {
log.Fatal(err)
}
seenText := "never"
if seenUnix != nil {
seenText = time.Unix(*seenUnix, 0).UTC().Format(time.RFC3339)
}
fmt.Printf("%s nickname=%q valid=%t score=%d valid=%t joined=%s seen=%s\n",
name, nickname.String, nickname.Valid, score.V, score.Valid, joinedAt.Format(time.RFC3339), seenText)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
// NULL is not equal to anything, including NULL; use IS, IS NOT, COALESCE.
var eq, is sql.NullBool
var label string
if err := db.QueryRowContext(ctx,
"SELECT NULL = NULL, NULL IS NULL, coalesce((SELECT nickname FROM users WHERE name = 'Brian'), '(none)')").Scan(&eq, &is, &label); err != nil {
log.Fatal(err)
}
fmt.Printf("NULL = NULL valid=%t, NULL IS NULL=%t, coalesce=%s\n", eq.Valid, is.Bool, label)
var missing int
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM users WHERE nickname <> 'countess'").Scan(&missing); err != nil {
log.Fatal(err)
}
fmt.Println("rows where nickname <> 'countess':", missing)
// SQLite's date functions read both storage forms.
var day, fromUnix string
if err := db.QueryRowContext(ctx,
"SELECT date(joined_at), datetime(seen_unix, 'unixepoch') FROM users WHERE name = 'Ada'").Scan(&day, &fromUnix); err != nil {
log.Fatal(err)
}
fmt.Println("date(joined_at):", day, "| datetime(seen_unix, 'unixepoch'):", fromUnix)
// Passing a time.Time directly lets the driver choose the text format.
for _, dsn := range []string{":memory:", ":memory:?_time_format=sqlite"} {
tdb, err := sql.Open("sqlite", dsn)
if err != nil {
log.Fatal(err)
}
var stored string
var day sql.NullString
if err := tdb.QueryRowContext(ctx, "SELECT CAST(? AS TEXT), date(?)", joined, joined).Scan(&stored, &day); err != nil {
log.Fatal(err)
}
fmt.Printf("%-28s time.Time stored as %q, date() valid=%t\n", dsn, stored, day.Valid)
tdb.Close()
}
}The first line is the error database/sql returns for NULL into string. Ada has every value; Brian has invalid Null values and a nil pointer, printed as never. The joined time 09:30 in CET is stored and printed as 08:30Z. NULL = NULL is itself NULL (valid=false), and nickname <> 'countess' matches 0 rows because the comparison with Brian's NULL is unknown. date() and datetime(..., 'unixepoch') read both formats. Passed as time.Time, the driver writes Go's String format, which date() cannot parse; with _time_format=sqlite it writes 2026-03-01 09:30:00+01:00, which it can.
Three-valued logic in SQL
Any comparison with NULL yields NULL, which WHERE treats as false. That is why nickname <> 'countess' skips rows whose nickname is NULL, and why NOT IN with a subquery that returns a NULL matches nothing. Use IS NULL and IS NOT NULL, the null-safe IS and IS NOT comparisons (a IS b is true when both are NULL), coalesce(x, default) for display and ifnull or nullif where they read better. Aggregates skip NULLs: count(col) counts non-NULL values while count(*) counts rows, and avg ignores missing scores rather than treating them as zero.
Choosing a time representation
Store instants in UTC, in one format per column, and document it in the schema. Unix seconds or milliseconds in an INTEGER column are compact, compare as numbers and work with datetime(x, 'unixepoch') or unixepoch(). ISO 8601 text such as 2026-03-01T08:30:00.000Z is readable in any browser and sorts correctly only if every value has the same width and zone: time.RFC3339Nano drops trailing zeros, so 08:30:00.5Z and 08:30:00.25Z sort in the wrong order. Format and parse in Go with one layout constant rather than relying on the driver default, which differs between drivers. Keep calendar dates, such as a birthday, as YYYY-MM-DD text without a zone.
const layout = "2006-01-02T15:04:05.000Z" // fixed width, always UTC
func toDB(t time.Time) string { return t.UTC().Format(layout) }
func fromDB(s string) (time.Time, error) { return time.Parse(layout, s) }Two small functions own the conversion in both directions. Because the layout always has three fractional digits and the literal Z, string order equals time order, so ORDER BY joined_at and range queries with >= and < work on the text column and can use an index.
TAKE THIS WITH YOU
Scan nullable columns into sql.Null types or pointers, write NULL-aware SQL with IS and coalesce, and store times in UTC in one explicit format per column, either Unix integers or fixed-width ISO 8601 text, converted by your own code rather than the driver default.
Check your understanding
Why does WHERE nickname <> 'countess' skip rows whose nickname is NULL?
Go to the source
Progress stays in this browser. No account needed.