LENGTH and CHAR_LENGTH in MySQL - Time & Space Complexity
We want to understand how the time to find the length of strings grows as we check more or longer strings.
How does the work change when the input strings get bigger or when we have more strings?
Analyze the time complexity of the following code snippet.
SELECT LENGTH(name), CHAR_LENGTH(name)
FROM employees;
This code gets the byte length and character count of the 'name' field for every employee.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: For each row, the database reads the string and counts bytes or characters.
- How many times: Once per row in the table, so it repeats for every employee.
As the number of rows grows, the total work grows too because each string is checked once.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | 10 string length checks |
| 100 | 100 string length checks |
| 1000 | 1000 string length checks |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles the work.
Time Complexity: O(n * m)
This means the time grows with the number of rows (n) and the length of each string (m).
[X] Wrong: "Counting string length is always quick and does not depend on string size."
[OK] Correct: The database must look at each character or byte to count, so longer strings take more time.
Knowing how string length functions scale helps you understand query costs when working with text data in databases.
"What if we only checked the length of strings for a filtered subset of rows? How would the time complexity change?"