SQL injection
SQL injection is when untrusted text becomes part of a query's structure — a quote that ends a string and starts a new clause. In Go you prevent it by binding parameters, not by concatenating strings.
Detailed Explanation
fmt.Sprintf("SELECT * FROM users WHERE name = '%s'", name) with name = "x' OR 1=1 --" is a different query than you wrote. The database parses the attacker's SQL. Parameter binding ($1, ?) sends the value out of band. The attacker can put anything in the value and it stays a value.
Go-specific forms of the same bug. + on strings, fmt.Sprintf, strings.Builder for values, and fmt.Sprintf for IN (%s) lists you built from user IDs without binding each element. An IN clause should be IN ($1,$2,$3) with one placeholder per id, or = ANY($1) with a driver array type.
Identifiers. You cannot bind a table or column name. ORDER BY + userField is injection if userField is query-string input. Map the input to a known column: switch f { case "name", "id": ... default: return err }.
ORMs and sqlx. They bind values when you use their parameter APIs. Raw string fragments you pass in (Where("id = " + id)) undo that. sqlc generates functions with typed arguments; you still must not splice strings into the SQL file from user input.
What it costs. One injection is a full table read or drop. Binding is not slower in any way that matters. Code review should treat fmt.Sprintf near SQL as a defect unless the format is a constant and the args are numbers you formatted, not user strings.
Code Examples
package main
import (
"context"
"database/sql"
)
func byName(ctx context.Context, db *sql.DB, name string) error {
_, err := db.QueryContext(ctx, `SELECT id FROM users WHERE name = $1`, name)
return err
}
func inj(name string) string {
return `SELECT id FROM users WHERE name = '` + name + `'`
}
func main() {}func orderOK(field string) (string, bool) {
switch field {
case "id", "name":
return field, true
default:
return "", false
}
}Common Gotchas
Quotes you escape yourself will miss an encoding
do not write a sanitizer; bind.