SQL
SQL Security
Protecting your database from attacks
By TechCoder TeamLast updated: 2026-06-02
In a Nutshell
Protecting your database from attacks This hands-on tutorial focuses on practical implementation of sql security concepts.
SQL Injection (SQLi)
SQL Injection is a vulnerability where an attacker interferes with the queries an application makes to its database.
The Attack
Imagine this login query:
sql = "SELECT * FROM users WHERE name = '" + userName + "'";
If userName is input as ' OR '1'='1, the query becomes:
SELECT * FROM users WHERE name = '' OR '1'='1';
This always returns true, logging the attacker in without a password.
Prevention: Prepared Statements
Prepared Statements separate the code from the data. The database treats the input as data, not executable code.
Vulnerable (DO NOT USE)
db.query(`SELECT * FROM posts WHERE id = ${userInput}`);
Secure (USE THIS)
// Parameterized query
db.query('SELECT * FROM posts WHERE id = $1', [userInput]);
Other Security Practices
- Principle of Least Privilege: Give applications only the permissions they need (e.g.,
SELECT,INSERTonly, noDROP). - Encrypt Sensitive Data: Hash passwords (bcrypt/argon2) before storing.
- Disable Remote Root Access: Lock down database network access.
sql-injection-fix
Fix the Query
Problem Statement
Rewrite this pseudo-code query to be secure: query("SELECT * FROM users WHERE id = " + id). Use ? as placeholder.