0
0
PostgreSQLquery~5 mins

JSON aggregation with JSON_AGG in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the PostgreSQL function JSON_AGG do?

JSON_AGG collects multiple rows into a single JSON array. It helps group data as JSON objects inside one array.

Click to reveal answer
beginner
How do you use JSON_AGG to aggregate rows from a table?

You select the columns you want as JSON objects and wrap them inside JSON_AGG. For example: SELECT JSON_AGG(row_to_json(t)) FROM (SELECT * FROM table_name) t;

Click to reveal answer
intermediate
Can JSON_AGG be combined with GROUP BY?

Yes. You can group rows by a column and aggregate related rows as JSON arrays for each group.

Click to reveal answer
intermediate
What is the difference between JSON_AGG and ARRAY_AGG?

JSON_AGG returns a JSON array, which can contain JSON objects. ARRAY_AGG returns a SQL array of values, not JSON formatted.

Click to reveal answer
beginner
Why use row_to_json inside JSON_AGG?

row_to_json converts a table row into a JSON object. Using it inside JSON_AGG creates an array of JSON objects instead of simple values.

Click to reveal answer
What type of data does JSON_AGG return?
AA JSON array
BA SQL array
CA JSON object
DA text string
Which function is commonly used inside JSON_AGG to convert rows to JSON objects?
AJSON_BUILD_OBJECT
BTO_JSON
CROW_TO_JSON
DJSON_OBJECT_AGG
Can JSON_AGG be used with GROUP BY to create grouped JSON arrays?
AOnly with <code>ORDER BY</code>
BYes
CNo
DOnly with <code>HAVING</code>
What does this query return?<br>SELECT JSON_AGG(name) FROM users;
AA JSON array of user names
BA JSON object of user names
CA SQL array of user names
DA single user name
Which is true about JSON_AGG compared to ARRAY_AGG?
A<code>JSON_AGG</code> returns SQL arrays, <code>ARRAY_AGG</code> returns JSON arrays
BBoth return SQL arrays
CBoth return JSON arrays
D<code>JSON_AGG</code> returns JSON arrays, <code>ARRAY_AGG</code> returns SQL arrays
Explain how to use JSON_AGG to create a JSON array of objects from a table.
Think about how to turn each row into JSON and then collect them.
You got /4 concepts.
    Describe a scenario where combining GROUP BY with JSON_AGG is useful.
    Imagine grouping orders by customer and returning JSON arrays of orders.
    You got /4 concepts.