---
title: Always Use Parameterized Queries
impact: CRITICAL
impactDescription: prevents SQL and NoSQL injection attacks
tags: injection, sql, nosql, database, parameterized, security
---

## Always Use Parameterized Queries

SQL injection allows attackers to execute arbitrary database commands, steal data, or destroy databases.

**Incorrect (string concatenation):**

```go
// SQL Injection vulnerability
userId := r.URL.Query().Get("id")
query := fmt.Sprintf("SELECT * FROM users WHERE id = '%s'", userId)
db.Query(query)

// Attacker input: ' OR '1'='1
// Resulting query: SELECT * FROM users WHERE id = '' OR '1'='1'
```

**Correct (parameterized queries):**

```go
// Parameterized query using database/sql
userId := r.URL.Query().Get("id")
db.Query("SELECT * FROM users WHERE id = ?", userId) // Postgres uses $1, $2

// Using GORM (safely handles parameters)
var user User
db.First(&user, "id = ?", userId)
```

**Tools:** SonarQube, Semgrep, `sqlclosecheck`, `gosec` (G201, G202)
