How string concatenation creates vulnerabilities in SQL - Performance & Efficiency
We want to see how building SQL commands by joining strings affects how long the database takes to run them.
Specifically, we ask: How does the work grow when we add more parts to the command?
Analyze the time complexity of the following code snippet.
DECLARE @sql NVARCHAR(MAX);
SET @sql = 'SELECT * FROM Users WHERE 1=1';
IF @name IS NOT NULL
SET @sql = @sql + ' AND name = ''' + @name + '''';
IF @age IS NOT NULL
SET @sql = @sql + ' AND age = ' + CAST(@age AS NVARCHAR(10));
EXEC sp_executesql @sql;
This code builds a SQL query by joining strings based on input values, then runs it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Concatenating strings to build the query.
- How many times: Once per condition checked, but string length grows with each addition.
As more conditions are added, the query string gets longer, so concatenation takes more time.
| Input Size (conditions) | Approx. Operations |
|---|---|
| 1 | Small string concatenation |
| 5 | Medium string concatenation, longer query |
| 20 | Much longer string concatenation, more work |
Pattern observation: The time to build the query grows roughly with the total length of the string being concatenated.
Time Complexity: O(n^2)
This means the time to build the query grows quadratically with the number of parts added.
[X] Wrong: "Concatenating strings is always fast and safe regardless of input size."
[OK] Correct: As the query grows, concatenation takes more time and can cause security risks if inputs are not handled safely.
Understanding how building queries with string joins affects performance and security shows your care for writing safe and efficient database code.
"What if we used parameterized queries instead of string concatenation? How would the time complexity and security change?"
Practice
Solution
Step 1: Understand string concatenation in SQL queries
Concatenating user input directly into SQL commands can mix code and data.Step 2: Recognize the risk of SQL injection
This mixing allows attackers to add harmful SQL commands, called SQL injection.Final Answer:
It can allow attackers to inject malicious SQL code. -> Option AQuick Check:
SQL injection risk = A [OK]
- Thinking concatenation speeds up queries
- Believing concatenation encrypts input
- Assuming concatenation prevents errors
Solution
Step 1: Check string delimiters and concatenation syntax
In SQL, string literals are enclosed in single quotes. Concatenation in code requires proper quotes and plus signs.Step 2: Identify correct syntax for concatenation in code
SELECT * FROM users WHERE name = '\'' + userName + '\''; correctly escapes single quotes for SQL string literals and concatenates userName with plus signs.Final Answer:
"SELECT * FROM users WHERE name = '\'' + userName + '\'';" -> Option AQuick Check:
Proper quotes and concatenation = A [OK]
- Missing semicolon at end
- Mismatched or missing quotes
- Using wrong concatenation operators
"SELECT * FROM users WHERE username = '" + input + "';" and input = admin' OR '1'='1, what will be the effect when executed?Solution
Step 1: Substitute input into the query string
The query becomes: SELECT * FROM users WHERE username = 'admin' OR '1'='1';Step 2: Analyze the WHERE clause logic
The condition '1'='1' is always true, so the WHERE clause matches all rows.Final Answer:
Returns all users because the WHERE clause is always true. -> Option BQuick Check:
Injected OR '1'='1' returns all rows = D [OK]
- Thinking it returns only 'admin'
- Assuming syntax error occurs
- Believing no rows are returned
query = "SELECT * FROM users WHERE id = " + userId; where userId is a string input.Solution
Step 1: Check how userId is inserted in query
The query concatenates userId without quotes, so if userId is a string, SQL syntax breaks.Step 2: Understand SQL string literal requirements
String values must be enclosed in single quotes in SQL to be valid.Final Answer:
Missing quotes around userId value causing syntax error. -> Option DQuick Check:
String values need quotes = B [OK]
- Thinking plus sign is invalid in code
- Assuming query is safe from injection
- Ignoring missing quotes causes errors
Solution
Step 1: Understand the problem with string concatenation
Concatenation mixes code and data, allowing injection if input is malicious.Step 2: Identify secure alternatives
Parameterized queries separate code from data, preventing injection regardless of input.Final Answer:
Use parameterized queries or prepared statements instead of concatenation. -> Option CQuick Check:
Parameterized queries prevent injection = C [OK]
- Relying on manual escaping which is error-prone
- Thinking removing spaces prevents injection
- Assuming uppercase conversion secures input
Ready to prove it?
Pass the test and this pattern moves unknown
