Skip to content

Commit 1ec3d97

Browse files
committed
Merge pull request VividCortex#76 from Dynom/patch-1
Added an alternative approach by suggesting COALESCE()
2 parents 87313f9 + 33d00c7 commit 1ec3d97

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

nulls.md

+17
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,22 @@ you need more convincing:
3737
If you need to define your own types to handle NULLs, you can copy the design of
3838
`sql.NullString` to achieve that.
3939

40+
If you can't avoid having NULL values in your database, there is another work around that most database systems support, namely `COALESCE()`. Something like the following might be something that you can use, without introducing a myriad of `sql.Null*` types.
41+
<pre class="prettyprint lang-go">
42+
rows, err := db.Query(`
43+
SELECT
44+
name,
45+
COALESCE(other_field, '') as other_field
46+
WHERE id = ?
47+
`, 42)
48+
49+
for rows.Next() {
50+
err := rows.Scan(&name, &otherField)
51+
// ..
52+
// If `other_field` was NULL, `otherField` is now an empty string. This works with other data types as well.
53+
}
54+
</pre>
55+
56+
4057
**Previous: [Handling Errors](errors.html)**
4158
**Next: [Working with Unknown Columns](varcols.html)**

0 commit comments

Comments
 (0)