How to Write Raw SQL vs ORM in Go

Trade-Offs

Use Raw SQL for performance and control, and ORMs for speed and safety in Go database interactions.

Use Raw SQL for complex queries, performance tuning, or database-specific features; use an ORM for rapid development, type safety, and maintainability. Raw SQL offers full control but requires manual mapping and error handling, while ORMs abstract these details at the cost of flexibility and potential performance overhead.

// Raw SQL example using database/sql
rows, err := db.Query("SELECT id, name FROM users WHERE age > ?", 18)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ID: %d, Name: %s\n", id, name)
}