Why string functions matter in queries in SQL - Performance Analysis
When we use string functions in SQL queries, it affects how long the query takes to run.
We want to know how the work grows as the data gets bigger.
Analyze the time complexity of the following SQL query using string functions.
SELECT UPPER(name), LENGTH(description)
FROM products
WHERE SUBSTRING(name, 1, 3) = 'New';
This query changes the case of names, measures description length, and filters names starting with 'New'.
Look for repeated work done for each row in the table.
- Primary operation: Applying string functions (UPPER, LENGTH, SUBSTRING) on each row.
- How many times: Once per row in the products table.
As the number of rows grows, the query does more string work for each row.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 string function calls |
| 100 | About 300 string function calls |
| 1000 | About 3000 string function calls |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of rows increases.
[X] Wrong: "String functions run once, so they don't affect query time much."
[OK] Correct: String functions run for every row, so more rows mean more work and longer time.
Understanding how string functions affect query time helps you write better queries and explain their performance clearly.
"What if we added an index on the name column? How would that change the time complexity of filtering with SUBSTRING?"