CodeBlanks Logo Icon CodeBlanks

SQL injection

Learn injection attacks and prevention.

SQL injection

SQL injection is when an attacker changes a query by injecting user input into the SQL. String concatenation is the main risk; a parameterized PREPARE statement stops it.

-- YANLIŞ: '...' || user_input
-- DOĞRU: PREPARE find(text) AS
--   SELECT * FROM users WHERE email = $1;

Injection grows from string concatenation.

SQL injection — details

An attacker types ' OR '1'='1 and pulls all rows. A parameterized query treats input as a value, so it cannot act as SQL syntax.

Practice SQL injection

Create a prepared statement check_user(text) that selects from users where email = $1.

Starter code

query.sql
-- injection protection
PREPARE check_user(text)

Sample solution

query.sql
PREPARE check_user(text) AS SELECT * FROM users WHERE email = $1;

Expected output

PREPARE

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does SQL injection exploit?

  • Triggers
  • String concatenation Correct answer
  • The index
  • Views

Explanation: SQL injection exploits string concatenation.

2 Prepared statement

Question
PREPARE check_user(text) AS
SELECT * FROM users WHERE email = ____;
Answer
PREPARE check_user(text) AS
SELECT * FROM users WHERE email = $1;

Explanation: $1 is a parameter placeholder; user input is never concatenated into the query, which prevents SQL injection.

3 SQL injection: match the terms

Term Meaning
injection injection
concat concat
PREPARE prepare
parameter parameter

All lessons in Expert