0
0
SQLquery~5 mins

TRIM, LTRIM, RTRIM in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: TRIM, LTRIM, RTRIM
O(n)
Understanding Time Complexity

When using TRIM, LTRIM, or RTRIM functions in SQL, it's helpful to understand how their execution time changes as the input string grows.

We want to know how the time to remove spaces depends on the length of the text.

Scenario Under Consideration

Analyze the time complexity of the following SQL snippet.


SELECT TRIM('   example   ') AS trimmed_text,
       LTRIM('   example   ') AS left_trimmed,
       RTRIM('   example   ') AS right_trimmed;
    

This code removes spaces from both ends, left end, and right end of the string respectively.

Identify Repeating Operations

Look for repeated steps inside these functions.

  • Primary operation: Scanning characters from the start or end of the string to find spaces.
  • How many times: Up to once per character at the string edges until a non-space is found.
How Execution Grows With Input

The time depends on how many spaces are at the edges of the string.

Input Size (n)Approx. Operations
10Up to 10 checks if all spaces
100Up to 100 checks if all spaces
1000Up to 1000 checks if all spaces

Pattern observation: The work grows linearly with the number of spaces at the edges, not the total string length.

Final Time Complexity

Time Complexity: O(n)

This means the time to trim grows in a straight line with the number of characters checked at the string edges.

Common Mistake

[X] Wrong: "TRIM functions always take the same time no matter the string length."

[OK] Correct: The functions scan characters from the edges until they find a non-space, so more spaces mean more work.

Interview Connect

Understanding how simple string functions scale helps you reason about performance in real queries and shows you think about efficiency.

Self-Check

"What if the string had no spaces at all? How would the time complexity of TRIM change then?"