Firmino Changani

Golang/SQL - Fixing the error - Converting NULL to string is unsupported error

Converting NULL to string is unsupported error

The error above is thrown whenever a Go program tries to scan a query result that contains at least one column whose value is NULL to a struct defined with primitive types instead of sql.NullString type.

To solve this issue at the query level, the SQL function COALESCE comes in handy.

 1package demo
 2
 3type User struct {
 4    Id string
 5    FirstName string
 6    LastName string
 7}
 8
 9func findUserByEmail(ctx context.Context, email string) {
10    user := &User{}
11	row := DbConn.QueryRowContext(ctx, `
12		SELECT id, COALESCE(first_name, '') as first_name, COALESCE(last_name, '') as last_name
13		FROM users
14		WHERE email = $1
15	`, email)
16	err := row.Scan(&user.Id, &user.FirstName, &user.LastName)
17
18    // ...
19}

When the query above is executed, the function COALESCE will replace the NULL value of the columns first_name and last_name returned by the database for the value passed as second argument, which is an empty string.

References

#golang

Reply to this post by email ↪