Search code examples
gogo-gorm

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


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?


Solution

  • According to the docs, this should work:

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