Bird
Raised Fist0
PostgreSQLquery~10 mins

JSON aggregation with JSON_AGG in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - JSON aggregation with JSON_AGG
Start Query
↓
Select rows from table
↓
Extract JSON objects from each row
↓
Aggregate JSON objects into JSON array
↓
Return single JSON array as result
↓
End Query
The query selects rows, converts each row to a JSON object, then combines all these JSON objects into a single JSON array using JSON_AGG.
Execution Sample
PostgreSQL
SELECT JSON_AGG(row_to_json(t))
FROM (SELECT id, name FROM users) t;
This query collects all users' id and name into a JSON array of JSON objects.
Execution Table
StepActionRow DataJSON ObjectAggregation State
1Select first rowid=1, name='Alice'{"id":1,"name":"Alice"}[{"id":1,"name":"Alice"}]
2Select second rowid=2, name='Bob'{"id":2,"name":"Bob"}[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
3Select third rowid=3, name='Carol'{"id":3,"name":"Carol"}[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"}]
4No more rowsN/AN/AFinal JSON array returned
💡 All rows processed and aggregated into one JSON array.
Variable Tracker
VariableStartAfter 1After 2After 3Final
Aggregation State[][{"id":1,"name":"Alice"}][{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}][{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"}][{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"}]
Key Moments - 2 Insights
Why does JSON_AGG return a single JSON array instead of multiple rows?
Because JSON_AGG collects all JSON objects from each row into one array, it returns one row with the aggregated JSON array, as shown in execution_table step 4.
What happens if the table has no rows?
JSON_AGG returns NULL or an empty array depending on usage, since there are no JSON objects to aggregate. This is implied by the exit condition in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the aggregation state after processing the second row?
A[{"id":1,"name":"Alice"}]
B[{"id":2,"name":"Bob"}]
C[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
D[]
💡 Hint
Check the 'Aggregation State' column at step 2 in the execution_table.
At which step does the query finish aggregating all rows?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look for the step where 'No more rows' is indicated in the execution_table.
If a new row with id=4 and name='Dave' is added, what will be the aggregation state after processing it?
A[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"},{"id":4,"name":"Dave"}]
B[{"id":4,"name":"Dave"}]
C[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"}]
D[]
💡 Hint
Refer to the pattern of aggregation in variable_tracker and add the new JSON object at the end.
Concept Snapshot
JSON_AGG aggregates multiple JSON objects into a single JSON array.
Use it with row_to_json to convert rows to JSON.
Syntax: SELECT JSON_AGG(row_to_json(t)) FROM (SELECT ...) t;
Returns one JSON array containing all row objects.
If no rows, returns NULL or empty array.
Full Transcript
This visual execution trace shows how the PostgreSQL function JSON_AGG works. The query selects rows from a table, converts each row into a JSON object using row_to_json, and then aggregates all these JSON objects into a single JSON array. Step by step, each row's data is turned into JSON and added to the growing JSON array. After all rows are processed, the final JSON array is returned as the query result. Key points include that JSON_AGG returns one row with the full JSON array, and if there are no rows, the result is NULL or empty. This helps beginners see how JSON_AGG collects data visually and understand the aggregation process clearly.

Practice

(1/5)
1. What does the JSON_AGG function do in PostgreSQL?
easy
A. It collects multiple rows into a JSON array.
B. It converts a JSON array into separate rows.
C. It filters JSON data based on a condition.
D. It updates JSON data in a table.

Solution

  1. Step 1: Understand JSON_AGG purpose

    JSON_AGG is an aggregate function that collects multiple rows into a single JSON array.
  2. 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.
  3. Final Answer:

    It collects multiple rows into a JSON array. -> Option A
  4. Quick Check:

    JSON_AGG collects rows = It collects multiple rows into a JSON array [OK]
Hint: Remember: AGG means aggregate rows into one [OK]
Common Mistakes:
  • Confusing JSON_AGG with JSON functions that extract data
  • Thinking JSON_AGG filters rows
  • Assuming JSON_AGG updates JSON data
2. Which of the following is the correct syntax to use JSON_AGG in a query?
easy
A. SELECT JSON_AGG(column_name) table_name;
B. SELECT JSON_AGG FROM table_name WHERE column_name;
C. SELECT JSON_AGG(column_name) WHERE table_name;
D. SELECT JSON_AGG(column_name) FROM table_name;

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    SELECT JSON_AGG(column_name) FROM table_name; -> Option D
  4. Quick Check:

    Correct aggregate syntax = SELECT JSON_AGG(column_name) FROM table_name; [OK]
Hint: Aggregate functions need parentheses and FROM clause [OK]
Common Mistakes:
  • Omitting FROM clause
  • Missing parentheses after JSON_AGG
  • Misplacing WHERE clause
3. Given the table 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;
medium
A. [{"category":"Books","json_agg":["Novel","Comics"]}, {"category":"Toys","json_agg":["Car","Doll"]}]
B. [{"category":"Books","json_agg":"Novel,Comics"}, {"category":"Toys","json_agg":"Car,Doll"}]
C. [{"category":"Books","json_agg":["Novel"]}, {"category":"Toys","json_agg":["Car"]}]
D. [{"category":"Books","json_agg":null}, {"category":"Toys","json_agg":null}]

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    [{"category":"Books","json_agg":["Novel","Comics"]}, {"category":"Toys","json_agg":["Car","Doll"]}] -> Option A
  4. Quick Check:

    JSON_AGG groups names into arrays = [{"category":"Books","json_agg":["Novel","Comics"]}, {"category":"Toys","json_agg":["Car","Doll"]}] [OK]
Hint: JSON_AGG returns arrays, not comma-separated strings [OK]
Common Mistakes:
  • Expecting JSON_AGG to return strings instead of arrays
  • Ignoring GROUP BY effect
  • Assuming null results without data
4. Identify the error in this query:
SELECT category, JSON_AGG(name) FROM products GROUP category;
medium
A. Missing FROM clause
B. Incorrect GROUP BY syntax
C. JSON_AGG cannot be used with GROUP BY
D. Missing parentheses in JSON_AGG

Solution

  1. Step 1: Check GROUP BY syntax

    The correct syntax is GROUP BY column_name, but the query uses GROUP category without BY.
  2. 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.
  3. Final Answer:

    Incorrect GROUP BY syntax -> Option B
  4. Quick Check:

    GROUP BY must include BY keyword = Incorrect GROUP BY syntax [OK]
Hint: GROUP BY always needs the BY keyword [OK]
Common Mistakes:
  • Writing GROUP instead of GROUP BY
  • Forgetting parentheses in functions
  • Assuming JSON_AGG can't be grouped
5. You want to create a JSON object for each department with an array of employee names and their roles. Which query correctly uses JSON_AGG to achieve this?
hard
A. SELECT department, JSON_BUILD_OBJECT('employees', JSON_AGG(name, role)) FROM employees GROUP BY department;
B. SELECT department, JSON_AGG(name, role) FROM employees GROUP BY department;
C. SELECT department, JSON_AGG(JSON_BUILD_OBJECT('name', name, 'role', role)) FROM employees GROUP BY department;
D. SELECT department, JSON_AGG(name || role) FROM employees GROUP BY department;

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    SELECT department, JSON_AGG(JSON_BUILD_OBJECT('name', name, 'role', role)) FROM employees GROUP BY department; -> Option C
  4. Quick Check:

    Use JSON_BUILD_OBJECT inside JSON_AGG for objects [OK]
Hint: Use JSON_BUILD_OBJECT inside JSON_AGG for arrays of objects [OK]
Common Mistakes:
  • Passing multiple columns directly to JSON_AGG
  • Concatenating strings instead of building JSON objects
  • Misusing JSON_BUILD_OBJECT outside aggregation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard