Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you explicitly find a record where a field is NULL?

Tags:

go

go-gorm

From the documentation:

When query with struct, GORM will only query with those fields has non-zero value, that means if your field’s value is 0, '', false or other zero values, it won’t be used to build query conditions.

Here is an example of what I am trying to do :

type Dog struct {
  ID uuid.UUID
  OwnerID *uuid.UUID
}

The owner ID pointer may be nil.

db.Where("owner_id", nil).Find(&dogs)

But that returns all dogs (I expected this from the doc). I tried doing:

db.Where("owner_id", "NULL").Find(&dogs)

But that returns an empty list.

Is there a way to explicitly search for a NULL value field?

like image 367
pdube Avatar asked Mar 06 '23 21:03

pdube


1 Answers

According to the docs, this should work:

db.Where("owner_id IS NULL").Find(&dogs)
like image 62
mbuechmann Avatar answered Mar 09 '23 06:03

mbuechmann