Hint: ARRAY_AGG(... ORDER BY ...) sorts array elements [OK]
Common Mistakes:
Ignoring ORDER BY inside ARRAY_AGG
Mixing names between groups
Assuming ARRAY_AGG sorts groups, not elements
4. Identify the error in this query:
SELECT class, ARRAY_AGG(name ORDER BY) FROM students GROUP BY class;
medium
A. Missing column name after ORDER BY inside ARRAY_AGG.
B. GROUP BY clause is not allowed with ARRAY_AGG.
C. ARRAY_AGG cannot be used with ORDER BY.
D. Missing FROM keyword before table name.
Solution
Step 1: Check syntax of ORDER BY inside ARRAY_AGG
ORDER BY inside ARRAY_AGG requires a column name to specify sorting order.
Step 2: Validate other parts of the query
GROUP BY is valid with ARRAY_AGG; FROM clause is present; ORDER BY without column is invalid.
Final Answer:
Missing column name after ORDER BY inside ARRAY_AGG. -> Option A
Quick Check:
ORDER BY needs a column name inside ARRAY_AGG [OK]
Hint: ORDER BY inside ARRAY_AGG needs a column name [OK]
Common Mistakes:
Leaving ORDER BY empty inside ARRAY_AGG
Thinking GROUP BY disallows ARRAY_AGG
Forgetting to specify sorting column
5. You have a table orders with columns customer_id and product. You want to create a query that returns each customer_id with an array of unique products they ordered, sorted alphabetically. Which query achieves this?
hard
A. SELECT customer_id, ARRAY_AGG(product ORDER BY product) FROM orders GROUP BY customer_id;
B. SELECT customer_id, ARRAY_AGG(DISTINCT product) FROM orders GROUP BY customer_id ORDER BY product;
C. SELECT customer_id, ARRAY_AGG(DISTINCT product ORDER BY product) FROM orders GROUP BY customer_id;
D. SELECT customer_id, ARRAY_AGG(product) FROM orders ORDER BY customer_id;
Solution
Step 1: Use ARRAY_AGG with DISTINCT and ORDER BY
To get unique products sorted, use ARRAY_AGG(DISTINCT product ORDER BY product).
Step 2: Group by customer_id to aggregate per customer
GROUP BY customer_id ensures aggregation per customer; ORDER BY inside ARRAY_AGG sorts products alphabetically.
Final Answer:
SELECT customer_id, ARRAY_AGG(DISTINCT product ORDER BY product) FROM orders GROUP BY customer_id; -> Option C
Quick Check:
Use DISTINCT inside ARRAY_AGG with ORDER BY for unique sorted arrays [OK]
Hint: Use DISTINCT inside ARRAY_AGG with ORDER BY for unique sorted arrays [OK]
Common Mistakes:
Omitting DISTINCT causes duplicates in array
Placing ORDER BY outside ARRAY_AGG affects rows, not array elements
Not grouping by customer_id
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.