We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

SQL Injection

SQL is a very common way hackers attempt to cause damage or breach a database. One of my favorite XKCD comics of all time demonstrates the problem:

The joke here is that if someone was using this query:

INSERT INTO students(name) VALUES (?);

And the "name" of a student was Robert'); DROP TABLE students;-- then the resulting SQL query would look like this:

INSERT INTO students(name) VALUES ('Robert'); DROP TABLE students;--');

As you can see, this is actually two queries! The first one inserts "Robert" into the database, and the second one deletes the students table!

Protecting Against SQL Injection

You need to be aware of SQL injection attacks, but to be honest, the solution these days is simply to use a modern SQL library that sanitizes inputs. We don't often need to sanitize inputs by hand at the application level anymore.

For example, the Go standard library's SQL package automatically protects against SQL injection attacks if you use it properly.

In short, don't interpolate user input into raw query strings yourself – make sure your database library has a way to sanitize inputs, and pass user-provided values into that.