Go SQL QueryRow: No Rows Found
In this tutorial, you'll learn about Go SQL QueryRow: No Rows Found. We cover key concepts, practical examples, and best practices.
QueryRow error handling -- Handle sql.ErrNoRows from QueryRow correctly by checking Scan's error return.
The Problem
Row.Scan() returns sql.ErrNoRows when QueryRow finds no matching row. Ignoring this error gives zero-value structs.
Wrong
var name string
err := db.QueryRow("SELECT name FROM users WHERE id = $1", 42).Scan(&name)
fmt.Println("Name:", name)
Output:
$ go run main.go
Name:
// id 42 doesn't exist -- silent failure
Right
var name string
err := db.QueryRow("SELECT name FROM users WHERE id = $1", 42).Scan(&name)
if err == sql.ErrNoRows {
fmt.Println("User not found")
} else if err != nil {
log.Fatal(err)
} else {
fmt.Println("Name:", name)
}
Output:
$ go run main.go
User not found
Prevention
- Always check the error from Scan()
- Use errors.Is(err, sql.ErrNoRows) for Go 1.13+
- Return 404 for no rows, 500 for real errors
- QueryRow = Query + one Row.Next()
- Use QueryContext with context for cancellation
Common Mistakes with sql query row
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro