Bird
Raised Fist0
PostgreSQLquery~20 mins

JSON aggregation with JSON_AGG in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JSON Aggregation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this JSON_AGG query?
Given a table employees with columns id, name, and department, what is the output of the following query?
SELECT department, JSON_AGG(name ORDER BY name) AS employee_names FROM employees GROUP BY department ORDER BY department;
PostgreSQL
CREATE TABLE employees (id INT, name TEXT, department TEXT);
INSERT INTO employees VALUES
(1, 'Alice', 'HR'),
(2, 'Bob', 'IT'),
(3, 'Charlie', 'HR'),
(4, 'David', 'IT'),
(5, 'Eve', 'Finance');

SELECT department, JSON_AGG(name ORDER BY name) AS employee_names FROM employees GROUP BY department ORDER BY department;
A[{"department":"Finance","employee_names":["Eve"]},{"department":"HR","employee_names":["Alice","Charlie"]},{"department":"IT","employee_names":["Bob","David"]}]
B[{"department":"Finance","employee_names":["Eve"]},{"department":"HR","employee_names":["Charlie","Alice"]},{"department":"IT","employee_names":["David","Bob"]}]
C[{"department":"Finance","employee_names":["Eve"]},{"department":"HR","employee_names":["Alice","Charlie"]},{"department":"IT","employee_names":["David","Bob"]}]
D[{"department":"Finance","employee_names":["Eve"]},{"department":"HR","employee_names":["Charlie","Alice"]},{"department":"IT","employee_names":["Bob","David"]}]
Attempts:
2 left
💡 Hint
Remember that JSON_AGG with ORDER BY sorts the aggregated values inside the array.
🧠 Conceptual
intermediate
1:30remaining
What does JSON_AGG do in PostgreSQL?
Choose the best description of what the JSON_AGG function does in PostgreSQL.
AAggregates JSON objects into a single JSON object by merging keys.
BAggregates multiple rows into a single JSON array.
CConverts a JSON array into multiple rows.
DConverts a JSON string into a JSON object.
Attempts:
2 left
💡 Hint
Think about how aggregation functions combine multiple rows.
📝 Syntax
advanced
2:30remaining
Which query correctly aggregates JSON objects per department?
You want to aggregate employee data as JSON objects per department with keys id and name. Which query is correct?
PostgreSQL
Table employees(id INT, name TEXT, department TEXT)
ASELECT department, JSON_AGG(JSON_BUILD_OBJECT('id', id, 'name', name)) AS employees FROM employees GROUP BY department;
BSELECT department, JSON_AGG(ROW(id, name)) AS employees FROM employees GROUP BY department;
CSELECT department, JSON_OBJECT_AGG(id, name) AS employees FROM employees GROUP BY department;
DSELECT department, JSON_AGG({'id': id, 'name': name}) AS employees FROM employees GROUP BY department;
Attempts:
2 left
💡 Hint
Remember JSON_BUILD_OBJECT creates JSON objects from key-value pairs.
🔧 Debug
advanced
2:00remaining
Why does this JSON_AGG query raise an error?
Consider this query:
SELECT department, JSON_AGG(name ORDER BY salary) FROM employees GROUP BY department;

Assuming salary is a column in employees, why does this query raise an error?
ABecause ORDER BY inside JSON_AGG requires a subquery.
BBecause JSON_AGG does not support ORDER BY inside its parentheses.
CBecause <code>name</code> is not a valid column in employees.
DBecause <code>salary</code> is not in the GROUP BY clause or an aggregate function.
Attempts:
2 left
💡 Hint
Check what columns are allowed in SELECT when using GROUP BY.
❓ optimization
expert
3:00remaining
How to optimize JSON_AGG for large datasets?
You have a large sales table with millions of rows. You want to aggregate sales data per region into JSON arrays using JSON_AGG. Which approach is best to optimize performance?
AUse a CROSS JOIN to combine all regions and sales before aggregation.
BUse JSON_AGG without any filtering or indexing to get all data at once.
CUse a subquery to pre-filter rows by date before applying JSON_AGG.
DUse JSON_AGG inside a window function partitioned by region.
Attempts:
2 left
💡 Hint
Filtering data early reduces the amount of data JSON_AGG processes.

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