26

I've been strugguling with SQL NULL values in Golang recently. After trying to unsuccessfully unmarshal JSON objects using Decode() and sql.NullString, I came to this answer on StackOverflow :

Assigning null to JSON fields instead of empty strings in Golang

The solution using a string pointer seems to work perfectly with Decode() and nil values. So what is the difference between sql.NullString and *string ? Is it just about nil checking ?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • A NULL coming from sql is not the same that a Go nil. Take a look to [NullString](https://golang.org/pkg/database/sql/#NullString) – Yandry Pozo Oct 17 '16 at 17:52

1 Answers1

28

SQL has different null values than Golang.

If you look at the definition of sql.NullString then this is what you get:

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}

As you can see, sql.NullString is a way to represent null string coming from SQL (which correspond to "NULL"). On the other hand, a nil *string is a pointer to a string which is nil, so the two are different.

T. Claverie
  • 11,380
  • 1
  • 17
  • 28
  • That's pretty smart and clean – Juan Ricardo Aug 21 '19 at 01:55
  • 1
    Is thr any advantage using `sql.NullString` over using `*string`? – Akh Dec 26 '19 at 20:49
  • 19
    [From Russ Cox](https://groups.google.com/g/golang-nuts/c/vOTFu2SMNeA/m/GB5v3JPSsicJ): `There's no effective difference. We thought people might want to use NullString because it is so common and perhaps expresses the intent more clearly than *string. But either will work.` – sepehr Oct 20 '20 at 22:58
  • thanks @sepehr that quotes makes sense. The answer is misleading. Strictly speaking a null is not a nil, but at a higher level they both represent the very same concept. –  Jan 02 '21 at 09:59
  • `nil` has no type, `sql.NullString` does, so it's better to use `sql.NullString`, but people don't want to do the extra typing so they just defaulted to `*string`, which IMHO is an ugly hack. – Timo Huovinen Nov 23 '22 at 10:55