Bird
0
0

Given the table orders with columns customer_id and product, what will this query return?

medium📝 query result Q4 of 15
PostgreSQL - Aggregate Functions and GROUP BY
Given the table orders with columns customer_id and product, what will this query return?
SELECT customer_id, ARRAY_AGG(product ORDER BY product) FROM orders GROUP BY customer_id;
AEach customer_id with an array of their products sorted alphabetically
BEach customer_id with an array of products in random order
CAn error because ORDER BY is not allowed inside ARRAY_AGG
DA single array of all products ignoring customer_id
Step-by-Step Solution
Solution:
  1. Step 1: Understand GROUP BY with ARRAY_AGG

    The query groups rows by customer_id and aggregates products per customer.
  2. Step 2: Effect of ORDER BY inside ARRAY_AGG

    ORDER BY inside ARRAY_AGG sorts the products alphabetically within each array.
  3. Final Answer:

    Each customer_id with an array of their products sorted alphabetically -> Option A
  4. Quick Check:

    ARRAY_AGG with ORDER BY sorts values inside arrays [OK]
Quick Trick: Use ORDER BY inside ARRAY_AGG to sort aggregated array elements [OK]
Common Mistakes:
  • Thinking ORDER BY inside ARRAY_AGG causes syntax error
  • Assuming products are unsorted
  • Ignoring GROUP BY effect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes