UPPER, LOWER, INITCAP in PostgreSQL - Time & Space Complexity
We want to understand how the time it takes to change text case grows as the text gets longer.
How does the work increase when we use UPPER, LOWER, or INITCAP on bigger strings?
Analyze the time complexity of the following code snippet.
SELECT UPPER(name) AS upper_name,
LOWER(name) AS lower_name,
INITCAP(name) AS initcap_name
FROM employees;
This code converts the 'name' column to all uppercase, all lowercase, and capitalizes the first letter of each word for every employee.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The functions scan each character of the string to change its case.
- How many times: Once per character in each string, for every row in the table.
As the length of each string grows, the work grows roughly in direct proportion.
| Input Size (string length) | Approx. Operations |
|---|---|
| 10 | About 10 character checks and changes |
| 100 | About 100 character checks and changes |
| 1000 | About 1000 character checks and changes |
Pattern observation: The time grows steadily as the string gets longer, like walking down a hallway one step at a time.
Time Complexity: O(n)
This means the time to change case grows directly with the length of the string.
[X] Wrong: "Changing case is instant no matter how long the text is."
[OK] Correct: Each character must be checked and changed, so longer text takes more time.
Knowing how string functions scale helps you write efficient queries and understand performance when working with text data.
"What if we applied these functions to an array of strings instead of one string? How would the time complexity change?"