Concatenation with || operator in PostgreSQL - Time & Space Complexity
We want to understand how the time needed to join text pieces grows when using the || operator in PostgreSQL.
How does the work change as we add more text parts to join?
Analyze the time complexity of the following code snippet.
SELECT first_name || ' ' || last_name || ' - ' || city AS full_info
FROM users;
This code joins several text columns and strings to create a full information string for each user.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Concatenating strings using the || operator for each row.
- How many times: Once per row in the users table.
As the number of rows grows, the database does more concatenations, one set per row.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 concatenations |
| 100 | 100 concatenations |
| 1000 | 1000 concatenations |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to concatenate grows in a straight line as the number of rows increases.
[X] Wrong: "Concatenation time depends on the length of the strings, not the number of rows."
[OK] Correct: While string length matters for each operation, the total time mainly grows with how many rows need concatenation.
Knowing how string operations scale helps you write efficient queries and understand performance in real projects.
"What if we concatenated a variable number of strings per row instead of a fixed number? How would the time complexity change?"