0
0
MySQLquery~5 mins

LENGTH and CHAR_LENGTH in MySQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: LENGTH and CHAR_LENGTH
O(n * m)
Understanding Time 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?

Scenario Under Consideration

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

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

As the number of rows grows, the total work grows too because each string is checked once.

Input Size (n rows)Approx. Operations
1010 string length checks
100100 string length checks
10001000 string length checks

Pattern observation: The work grows directly with the number of rows; doubling rows doubles the work.

Final Time Complexity

Time Complexity: O(n * m)

This means the time grows with the number of rows (n) and the length of each string (m).

Common Mistake

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

Interview Connect

Knowing how string length functions scale helps you understand query costs when working with text data in databases.

Self-Check

"What if we only checked the length of strings for a filtered subset of rows? How would the time complexity change?"