SQL

Lesson 09

Parameterized queries

Bind user input as parameters instead of building SQL strings from untrusted values.

Good Code

users-repository.ts
export async function findUserByEmail(email: string) {
  const result = await db.query(
    "SELECT id, email, name FROM users WHERE email = $1",
    [email],
  );

  return result.rows[0] ?? null;
}

Bad Code

users-repository.ts
export async function findUserByEmail(email: string) {
  const result = await db.query(
    "SELECT id, email, name FROM users WHERE email = '" + email + "'",
  );

  return result.rows[0] ?? null;
}

Review Notes

What to review

Good Code

The good version keeps the SQL text fixed and sends email as a bound parameter.

Bad Code

The bad version inserts user input into the query string. A value that contains quotes or SQL syntax can change what the database executes.

Takeaways

  • User input should become query data, not query text.