21

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 ?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
  • 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

20

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
  • 9,953
  • 1
  • 12
  • 26
  • That's pretty smart and clean – Juan Ricardo Aug 21 '19 at 01:55
  • Is thr any advantage using `sql.NullString` over using `*string`? – Akh Dec 26 '19 at 20:49
  • 11
    [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. – mh-cbon Jan 02 '21 at 09:59