Course contentsShow
← Data Science
Lesson 1102 of 2,14528. Working with Databases from PythonFree lesson

What is SQL Injection?

Understanding SQL injection attacks, how they work, and why concatenating user input into queries is dangerous.

What is SQL Injection?

You'll learn what SQL injection attacks are, how they exploit vulnerable code, and why mixing user input with SQL is dangerous.

The Core Danger

SQL injection is a security vulnerability that occurs when an attacker manipulates a SQL query by inserting malicious code through user input. It happens when you build queries by directly concatenating or formatting user-provided strings into SQL commands instead of using proper safeguards.

Think of it like giving someone a form to fill out, but they write instructions that change what you're asking for entirely—not just answering your question, but rewriting the question itself.

How It Works

Imagine you build a query like this in Python:

username = input("Enter username: ")
query = f"SELECT * FROM users WHERE username = '{username}'"

If a user enters admin' OR '1'='1, the resulting query becomes:

SELECT * FROM users WHERE username = 'admin' OR '1'='1'

Since '1'='1' is always true, this returns all users, bypassing authentication. Worse attacks could include '; DROP TABLE users; -- which could delete your entire table.

Why It's Dangerous

SQL injection can:

  • Expose sensitive data (passwords, personal information)
  • Modify or delete database records
  • Execute administrative operations
  • Compromise entire systems

The vulnerability exists because the database can't distinguish between your intended SQL structure and the attacker's injected code—it's all just one string to execute.

Key Takeaway: Never concatenate user input directly into SQL queries. Always use parameterized queries (which you'll learn next) to keep data separate from SQL commands, preventing attackers from injecting malicious code.