Does db.Query return ErrNoRows?

Issue

I can’t seem to get ErrNoRows from my db.query when a sql query is expected to return no results.

results, err := database.Query("SELECT title FROM accountProject WHERE accountID=? AND MATCH(title) AGAINST(?)", accountID, query)
if err != nil {
    if err == sql.ErrNoRows {
        return errProjectDoesNotExist
    }
    return err
}

Solution

The value sql.ErrNoRows is not returned from Query. The first call to Next returns false when the result set has no rows.

The value sql.ErrNoRows is returned from a call to Scan on a placeholder row returned from ScanRow.

If the application is looking for zero or one rows, use QueryRow instead of Query.

row := database.QueryRow("SELECT title FROM accountProject WHERE accountID=? AND MATCH(title) AGAINST(?)", accountID, query)
err := row.Scan( .... address of variables here ... )
if err != nil {
    if err == sql.ErrNoRows {
        err = errProjectDoesNotExist
    }
    return err
}

Answered By – Bayta Darell

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.