Check if the parameter is null in the where clause from go sqlx

1.3k views Asked by At

Given we have a record in the postgresql database like this:

name(varchar) nickname(nullable varchar)
John          null

We want to update that record based on the nullable nickname value like this:

type Contact struct {
  Name     string         `db:"name"`
  Nickname sql.NullString `db:"nickname"`
}

func update() {
  db, _ := sqlx.Connect("postgres", "connection_string")

  c := Contact{
    Name: "Doe",
  }
  q := "UPDATE contact SET name = :name WHERE :nickname = '' AND nickname is null OR nickname = :nickname"

  db.NamedExec(db.Rebind(q), c)
}

The query above will update a record only if the c.Nickname is a string value (assuming we have a matching record in the db). How can I achieve this kind of logic: if c.Nickname == nil use nickname is null else use nickname = c.Nickname?

Edit:

I tried this query UPDATE contact SET name = :name WHERE CAST(:nickname as varchar) is null AND nickname is null OR nickname = :nickname, it is working as I expected but still want to see if there is better alternatives

0

There are 0 answers