TRIM, LTRIM, RTRIM in MySQL - Time & Space 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?
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 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.
As the text gets longer, the function checks more characters to trim spaces.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the length of the text.
Time Complexity: O(n)
This means the time to trim spaces grows linearly with the length of the text.
[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.
Understanding how string functions scale helps you write efficient queries and explain performance clearly.
"What if we used TRIM to remove a different character instead of space? How would the time complexity change?"