0
0
SQLquery~5 mins

How string concatenation creates vulnerabilities in SQL - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: How string concatenation creates vulnerabilities
O(n^2)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As more conditions are added, the query string gets longer, so concatenation takes more time.

Input Size (conditions)Approx. Operations
1Small string concatenation
5Medium string concatenation, longer query
20Much longer string concatenation, more work

Pattern observation: The time to build the query grows roughly with the total length of the string being concatenated.

Final Time Complexity

Time Complexity: O(n^2)

This means the time to build the query grows quadratically with the number of parts added.

Common Mistake

[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.

Interview Connect

Understanding how building queries with string joins affects performance and security shows your care for writing safe and efficient database code.

Self-Check

"What if we used parameterized queries instead of string concatenation? How would the time complexity and security change?"