postgresqlgopgx

How to scan a boolean, which may be NULL?


I try to scan a boolean result into a boolean pointer:

var expired bool
db.QueryRow(context.Background(), sql, id, n).Scan(&expired)

The code fails with the following error:

can't scan into dest[0]: cannot scan NULL into *bool

Which Go type do I have to use to scan a SQL boolean, which can be true, false and NULL?


Solution

  • My preference is using a pointer for bool

    var expired *bool
    db.QueryRow(context.Background(), sql, id, n).Scan(&expired)
    

    As bool only have false and true values, it does not provide a way to represent NULL.

    sql.NullBool is alse a good choice.