JSON aggregation with JSON_AGG in PostgreSQL - Time & Space Complexity
When we use JSON_AGG in PostgreSQL, we combine many rows into one JSON array. Understanding how long this takes helps us know how it will behave as data grows.
We want to find out how the time to create this JSON array changes when we have more rows.
Analyze the time complexity of the following code snippet.
SELECT department_id, JSON_AGG(employee_name) AS employees
FROM employees
GROUP BY department_id;
This query groups employees by their department and collects their names into a JSON array for each department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all employee rows and adding each employee name to a JSON array per department.
- How many times: Once for each employee row in the table.
As the number of employees grows, the work to add each name to the JSON array grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions to JSON arrays |
| 100 | About 100 additions to JSON arrays |
| 1000 | About 1000 additions to JSON arrays |
Pattern observation: The time grows directly with the number of employees; doubling employees roughly doubles the work.
Time Complexity: O(n)
This means the time to build the JSON arrays grows in a straight line as the number of rows increases.
[X] Wrong: "JSON_AGG runs in constant time no matter how many rows there are."
[OK] Correct: Each row must be processed and added to the JSON array, so more rows mean more work and more time.
Understanding how aggregation functions like JSON_AGG scale helps you explain query performance clearly and shows you know how databases handle data growth.
"What if we used JSON_AGG on a filtered subset of employees instead of all employees? How would the time complexity change?"
Practice
JSON_AGG function do in PostgreSQL?Solution
Step 1: Understand JSON_AGG purpose
JSON_AGG is an aggregate function that collects multiple rows into a single JSON array.Step 2: Compare options with function behavior
Only It collects multiple rows into a JSON array. correctly describes this behavior; others describe different functions or actions.Final Answer:
It collects multiple rows into a JSON array. -> Option AQuick Check:
JSON_AGG collects rows = It collects multiple rows into a JSON array [OK]
- Confusing JSON_AGG with JSON functions that extract data
- Thinking JSON_AGG filters rows
- Assuming JSON_AGG updates JSON data
JSON_AGG in a query?Solution
Step 1: Review correct SQL aggregate function syntax
Aggregate functions like JSON_AGG require parentheses around the column and a FROM clause specifying the table.Step 2: Check each option for syntax correctness
SELECT JSON_AGG(column_name) FROM table_name; uses correct syntax: SELECT JSON_AGG(column_name) FROM table_name; Others miss FROM or parentheses or have misplaced WHERE.Final Answer:
SELECT JSON_AGG(column_name) FROM table_name; -> Option DQuick Check:
Correct aggregate syntax = SELECT JSON_AGG(column_name) FROM table_name; [OK]
- Omitting FROM clause
- Missing parentheses after JSON_AGG
- Misplacing WHERE clause
products with columns category and name, what is the output of this query?SELECT category, JSON_AGG(name) FROM products GROUP BY category ORDER BY category;
Solution
Step 1: Understand GROUP BY with JSON_AGG
The query groups rows by category and collects all product names per category into a JSON array.Step 2: Analyze expected JSON_AGG output
JSON_AGG returns an array of names per category, so each category has a JSON array of product names, not a string or null.Final Answer:
[{"category":"Books","json_agg":["Novel","Comics"]}, {"category":"Toys","json_agg":["Car","Doll"]}] -> Option AQuick Check:
JSON_AGG groups names into arrays = [{"category":"Books","json_agg":["Novel","Comics"]}, {"category":"Toys","json_agg":["Car","Doll"]}] [OK]
- Expecting JSON_AGG to return strings instead of arrays
- Ignoring GROUP BY effect
- Assuming null results without data
SELECT category, JSON_AGG(name) FROM products GROUP category;
Solution
Step 1: Check GROUP BY syntax
The correct syntax is GROUP BY column_name, but the query uses GROUP category without BY.Step 2: Verify other parts of the query
FROM clause is present, JSON_AGG has parentheses, and it can be used with GROUP BY, so those are correct.Final Answer:
Incorrect GROUP BY syntax -> Option BQuick Check:
GROUP BY must include BY keyword = Incorrect GROUP BY syntax [OK]
- Writing GROUP instead of GROUP BY
- Forgetting parentheses in functions
- Assuming JSON_AGG can't be grouped
department with an array of employee names and their roles. Which query correctly uses JSON_AGG to achieve this?Solution
Step 1: Understand JSON_AGG with JSON_BUILD_OBJECT
To create JSON objects inside an array, use JSON_BUILD_OBJECT for each row, then aggregate with JSON_AGG.Step 2: Evaluate each option
SELECT department, JSON_AGG(JSON_BUILD_OBJECT('name', name, 'role', role)) FROM employees GROUP BY department; correctly builds JSON objects per employee and aggregates them by department. Options B and C misuse JSON_AGG arguments, and D concatenates strings incorrectly.Final Answer:
SELECT department, JSON_AGG(JSON_BUILD_OBJECT('name', name, 'role', role)) FROM employees GROUP BY department; -> Option CQuick Check:
Use JSON_BUILD_OBJECT inside JSON_AGG for objects [OK]
- Passing multiple columns directly to JSON_AGG
- Concatenating strings instead of building JSON objects
- Misusing JSON_BUILD_OBJECT outside aggregation
Ready to prove it?
Pass the test and this pattern moves unknown
