Bird
0
0

Given the table orders with columns customer_id and product, what will be the output of this query?

medium📝 query result Q4 of 15
PostgreSQL - Aggregate Functions and GROUP BY
Given the table orders with columns customer_id and product, what will be the output of this query?
SELECT customer_id, JSON_AGG(product) FROM orders GROUP BY customer_id ORDER BY customer_id;
AA single JSON array of all products ignoring customer_id
BEach customer_id with a JSON array of their products
CAn error because JSON_AGG cannot be used with GROUP BY
DEach product as a separate JSON object without aggregation
Step-by-Step Solution
Solution:
  1. Step 1: Understand GROUP BY with JSON_AGG

    The query groups rows by customer_id and aggregates the product values into JSON arrays per customer.
  2. Step 2: Analyze output structure

    Each row in the result shows a customer_id and a JSON array of products they ordered. No error occurs, and aggregation is per group.
  3. Final Answer:

    Each customer_id with a JSON array of their products -> Option B
  4. Quick Check:

    GROUP BY with JSON_AGG = grouped JSON arrays [OK]
Quick Trick: GROUP BY with JSON_AGG creates arrays per group [OK]
Common Mistakes:
  • Thinking JSON_AGG ignores GROUP BY and aggregates all rows
  • Assuming JSON_AGG cannot be used with GROUP BY
  • Expecting JSON objects instead of arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes