String aggregation with STRING_AGG in PostgreSQL - Time & Space Complexity
When we combine many text values into one string using STRING_AGG, it takes some time to do this work.
We want to understand how the time needed grows as we add more text values.
Analyze the time complexity of the following code snippet.
SELECT department_id, STRING_AGG(employee_name, ', ' ORDER BY employee_name) AS employees
FROM employees
GROUP BY department_id;
This query groups employees by their department and joins their names into one string per department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each employee record and concatenating their names per group.
- How many times: Once for each employee in the table, grouped by department.
As the number of employees grows, the work to combine their names grows roughly in proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 concatenations |
| 100 | About 100 concatenations |
| 1000 | About 1000 concatenations |
Pattern observation: The time grows roughly in a straight line as more names are combined.
Time Complexity: O(n log n)
This means the time to combine strings grows proportionally to n log n due to the ORDER BY sorting inside STRING_AGG.
[X] Wrong: "STRING_AGG runs instantly no matter how many rows there are."
[OK] Correct: Each name must be read and added to the result, so more rows mean more work and more time.
Understanding how aggregation functions like STRING_AGG scale helps you explain query performance clearly and confidently.
"What if we added an ORDER BY inside STRING_AGG? How would that affect the time complexity?"
Practice
STRING_AGG function do in PostgreSQL?Solution
Step 1: Understand STRING_AGG purpose
STRING_AGG is used to join multiple text values into a single string with a separator.Step 2: Compare with other options
Counting rows, sorting, or deleting duplicates are different functions, not STRING_AGG.Final Answer:
It combines multiple text values into one string with a separator. -> Option AQuick Check:
STRING_AGG joins text values = It combines multiple text values into one string with a separator. [OK]
- Confusing STRING_AGG with COUNT or ORDER BY
- Thinking STRING_AGG sorts rows
- Assuming STRING_AGG removes duplicates
Solution
Step 1: Check basic STRING_AGG syntax
STRING_AGG requires two arguments: the column and the separator, e.g., STRING_AGG(name, ',').Step 2: Validate query structure
ORDER BY inside STRING_AGG needs to be inside parentheses, not outside. SELECT STRING_AGG(name, ',') FROM users; is correct syntax without ordering.Final Answer:
SELECT STRING_AGG(name, ',') FROM users; -> Option DQuick Check:
Correct STRING_AGG syntax = SELECT STRING_AGG(name, ',') FROM users; [OK]
- Omitting separator argument
- Placing ORDER BY outside STRING_AGG
- Using STRING_AGG without parentheses
fruits with rows: ('apple'), ('banana'), ('cherry'), what is the result of this query?SELECT STRING_AGG(name, '; ' ORDER BY name) FROM fruits;
Solution
Step 1: Understand ORDER BY inside STRING_AGG
The query orders names alphabetically: apple, banana, cherry.Step 2: Check separator and output
Separator is '; ', so the result joins names with '; ' in order.Final Answer:
'apple; banana; cherry' -> Option AQuick Check:
Ordered join with '; ' separator = 'apple; banana; cherry' [OK]
- Ignoring ORDER BY inside STRING_AGG
- Using wrong separator
- Assuming default comma separator
SELECT STRING_AGG(name, ', ' ORDER BY name) FROM users ORDER BY name;
Solution
Step 1: Check ORDER BY usage inside STRING_AGG
ORDER BY inside STRING_AGG after the separator is valid syntax.Step 2: Check outer ORDER BY
Without GROUP BY, the outer ORDER BY name causes an error because 'name' must appear in GROUP BY or be used in an aggregate function.Final Answer:
ORDER BY must be inside STRING_AGG parentheses, not outside. -> Option CQuick Check:
Outer ORDER BY invalid without GROUP BY = ORDER BY must be inside STRING_AGG parentheses, not outside. [OK]
- Thinking ORDER BY inside STRING_AGG is invalid
- Confusing outer ORDER BY with inner
- Misplacing ORDER BY arguments
orders with columns customer_id and product. How do you write a query to list each customer with a semicolon-separated list of their products sorted alphabetically?Solution
Step 1: Group by customer_id
We need to group rows by customer_id to aggregate products per customer.Step 2: Use STRING_AGG with ORDER BY inside
STRING_AGG(product, '; ' ORDER BY product) joins products with '; ' separator sorted alphabetically.Step 3: Validate options
SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; correctly uses GROUP BY and STRING_AGG with ORDER BY inside parentheses.Final Answer:
SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; -> Option BQuick Check:
Group by customer and ordered STRING_AGG = SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; [OK]
- Placing ORDER BY outside STRING_AGG
- Omitting GROUP BY when aggregating
- Swapping arguments inside STRING_AGG
Ready to prove it?
Pass the test and this pattern moves unknown
