0
0
MySQLquery~5 mins

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

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

When we use TRIM, LTRIM, or RTRIM in MySQL, we want to remove spaces from text.

We ask: How does the time to do this change as the text gets longer?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


SELECT TRIM(BOTH ' ' FROM column_name) AS trimmed_text
FROM example_table;

SELECT LTRIM(column_name) AS left_trimmed
FROM example_table;

SELECT RTRIM(column_name) AS right_trimmed
FROM example_table;
    

This code removes spaces from both sides, left side, or right side of text in a column.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Scanning each character of the text string to find spaces to remove.
  • How many times: Once per character in the string, from left or right depending on the function.
How Execution Grows With Input

As the text gets longer, the function checks more characters to trim spaces.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows roughly in direct proportion to the length of the text.

Final Time Complexity

Time Complexity: O(n)

This means the time to trim spaces grows linearly with the length of the text.

Common Mistake

[X] Wrong: "TRIM functions remove spaces instantly no matter the text length."

[OK] Correct: The function must check characters one by one, so longer text takes more time.

Interview Connect

Understanding how string functions scale helps you write efficient queries and explain performance clearly.

Self-Check

"What if we used TRIM to remove a different character instead of space? How would the time complexity change?"