LENGTH and CHAR_LENGTH in SQL - Time & Space Complexity
We want to understand how the time to calculate string lengths grows as the input data grows.
How does the work change when we measure length of many strings?
Analyze the time complexity of the following code snippet.
SELECT LENGTH(name), CHAR_LENGTH(name)
FROM employees;
This query calculates the byte length and character length of each employee's name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calculating length of each string in the column.
- How many times: Once for each row in the employees table.
Each string length calculation takes time proportional to the string's size. Doing this for many rows adds up.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | Length calculations for 10 strings |
| 100 | Length calculations for 100 strings |
| 1000 | Length calculations for 1000 strings |
Pattern observation: The total work grows linearly with the number of rows.
Time Complexity: O(n * m)
This means the time grows directly in proportion to the number of rows processed and the average length of the strings.
[X] Wrong: "Calculating LENGTH or CHAR_LENGTH is instant and does not depend on string size or number of rows."
[OK] Correct: Each length calculation must look at the string characters, so longer strings or more rows take more time.
Understanding how simple functions like LENGTH scale helps you reason about query performance and data processing in real projects.
"What if we added a WHERE clause to filter rows before calculating LENGTH? How would the time complexity change?"