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?"