Search code examples
goexistsgo-gorm

Select exists with GORM


I want to check if a row exists in a database table or not. I first used this approach:

type MyStruct struct {
    ID    uint32
    Key   string
    Value string
}

var result MyStruct

err := db.
    Where("id = ? AND `key` = ? AND `value` = 0", myID, myKey).
    First(&result).
    Error

if err != nil {
    if err == gorm.ErrRecordNotFound {
        logrus.Error("ErrRecordNotFound")
    }
    logrus.Errorf("Other DB error: %s", err.Error())
}

But I want to achieve this by writing a raw SQL. I tried following:

var result bool

db.Raw("SELECT EXISTS(SELECT 1 FROM my_table WHERE id = ? AND `key` = ? AND `value` = ?)",
    myID, myKey, "0").Scan(&result)

But I get this error:

unsupported destination, should be slice or struct.

I also tried to use method Exec and got the same error.

Note that the variable db is a *gorm.DB instance.


Solution

  • You can try the following approach

    var exists bool
    err = db.Model(model).
             Select("count(*) > 0").
             Where("id = ?", id).
             Find(&exists).
             Error